chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
/** Event detail for OAuth connect events dispatched by the copilot. */
|
||||
export interface OAuthConnectEventDetail {
|
||||
providerName: string
|
||||
serviceId: string
|
||||
providerId: string
|
||||
requiredScopes: string[]
|
||||
newScopes?: string[]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getHiddenToolNames, isToolHiddenInUi } from './hidden-tools'
|
||||
|
||||
describe('isToolHiddenInUi', () => {
|
||||
it('hides the internal loaders', () => {
|
||||
expect(isToolHiddenInUi('load_custom_tool')).toBe(true)
|
||||
expect(isToolHiddenInUi('load_integration_tool')).toBe(true)
|
||||
// Retained for historical persisted messages even though it is no longer emitted.
|
||||
expect(isToolHiddenInUi('load_agent_skill')).toBe(true)
|
||||
})
|
||||
|
||||
it('does not hide user skill loads, ordinary tools, or undefined', () => {
|
||||
// load_user_skill renders like the old per-skill loaders so the load is visible.
|
||||
expect(isToolHiddenInUi('load_user_skill')).toBe(false)
|
||||
expect(isToolHiddenInUi('read')).toBe(false)
|
||||
expect(isToolHiddenInUi(undefined)).toBe(false)
|
||||
})
|
||||
|
||||
it('exposes the hidden set', () => {
|
||||
expect(getHiddenToolNames().has('load_custom_tool')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
// load_agent_skill is retained for historical persisted messages; it is no
|
||||
// longer emitted now that internal skills autoload. load_user_skill is NOT
|
||||
// hidden — it renders like the old per-skill loaders so users see the skill load.
|
||||
const HIDDEN_TOOL_NAMES = new Set(['load_agent_skill', 'load_custom_tool', 'load_integration_tool'])
|
||||
|
||||
export function isToolHiddenInUi(toolName: string | undefined): boolean {
|
||||
return !!toolName && HIDDEN_TOOL_NAMES.has(toolName)
|
||||
}
|
||||
|
||||
export function getHiddenToolNames(): ReadonlySet<string> {
|
||||
return HIDDEN_TOOL_NAMES
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
clearExecutionPointer,
|
||||
executeWorkflowWithFullLogging,
|
||||
getWorkflowEntries,
|
||||
loadExecutionPointer,
|
||||
MockSSEEventHandlerError,
|
||||
MockSSEStreamInterruptedError,
|
||||
saveExecutionPointer,
|
||||
setActiveWorkflow,
|
||||
} = vi.hoisted(() => ({
|
||||
clearExecutionPointer: vi.fn(),
|
||||
executeWorkflowWithFullLogging: vi.fn(),
|
||||
getWorkflowEntries: vi.fn(() => []),
|
||||
loadExecutionPointer: vi.fn(),
|
||||
MockSSEEventHandlerError: class SSEEventHandlerError extends Error {
|
||||
executionId?: string
|
||||
|
||||
constructor(message: string, executionId?: string) {
|
||||
super(message)
|
||||
this.name = 'SSEEventHandlerError'
|
||||
this.executionId = executionId
|
||||
}
|
||||
},
|
||||
MockSSEStreamInterruptedError: class SSEStreamInterruptedError extends Error {
|
||||
executionId?: string
|
||||
|
||||
constructor(message: string, executionId?: string) {
|
||||
super(message)
|
||||
this.name = 'SSEStreamInterruptedError'
|
||||
this.executionId = executionId
|
||||
}
|
||||
},
|
||||
saveExecutionPointer: vi.fn(),
|
||||
setActiveWorkflow: vi.fn(),
|
||||
}))
|
||||
|
||||
const setIsExecuting = vi.fn()
|
||||
const setActiveBlocks = vi.fn()
|
||||
const setCurrentExecutionId = vi.fn()
|
||||
const getCurrentExecutionId = vi.fn()
|
||||
const getWorkflowExecution = vi.fn(() => ({ isExecuting: false }))
|
||||
|
||||
vi.mock('@/app/workspace/[workspaceId]/w/[workflowId]/utils/workflow-execution-utils', () => ({
|
||||
executeWorkflowWithFullLogging,
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/execution/store', () => ({
|
||||
useExecutionStore: {
|
||||
getState: () => ({
|
||||
getCurrentExecutionId,
|
||||
getWorkflowExecution,
|
||||
setActiveBlocks,
|
||||
setIsExecuting,
|
||||
setCurrentExecutionId,
|
||||
}),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/use-execution-stream', () => ({
|
||||
SSEEventHandlerError: MockSSEEventHandlerError,
|
||||
SSEStreamInterruptedError: MockSSEStreamInterruptedError,
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/workflows/registry/store', () => ({
|
||||
useWorkflowRegistry: {
|
||||
getState: () => ({
|
||||
activeWorkflowId: 'wf-1',
|
||||
setActiveWorkflow,
|
||||
}),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/terminal', () => ({
|
||||
consolePersistence: {
|
||||
executionStarted: vi.fn(),
|
||||
executionEnded: vi.fn(),
|
||||
persist: vi.fn(),
|
||||
},
|
||||
clearExecutionPointer,
|
||||
loadExecutionPointer,
|
||||
saveExecutionPointer,
|
||||
useTerminalConsoleStore: {
|
||||
getState: () => ({
|
||||
getWorkflowEntries,
|
||||
}),
|
||||
},
|
||||
}))
|
||||
|
||||
import {
|
||||
bindRunToolToExecution,
|
||||
cancelRunToolExecution,
|
||||
executeRunToolOnClient,
|
||||
reportManualRunToolStop,
|
||||
} from './run-tool-execution'
|
||||
|
||||
describe('run tool execution cancellation', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
getCurrentExecutionId.mockReturnValue(null)
|
||||
getWorkflowEntries.mockReturnValue([])
|
||||
loadExecutionPointer.mockResolvedValue(null)
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }))
|
||||
})
|
||||
|
||||
it('passes an abort signal into executeWorkflowWithFullLogging and aborts it', async () => {
|
||||
let capturedSignal: AbortSignal | undefined
|
||||
executeWorkflowWithFullLogging.mockImplementationOnce(async (options: any) => {
|
||||
capturedSignal = options.abortSignal
|
||||
await new Promise((_, reject) => {
|
||||
options.abortSignal.addEventListener(
|
||||
'abort',
|
||||
() => reject(new DOMException('Aborted', 'AbortError')),
|
||||
{ once: true }
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
executeRunToolOnClient('tool-1', 'run_workflow', { workflowId: 'wf-1' })
|
||||
await Promise.resolve()
|
||||
|
||||
cancelRunToolExecution('wf-1')
|
||||
await Promise.resolve()
|
||||
|
||||
expect(capturedSignal?.aborted).toBe(true)
|
||||
})
|
||||
|
||||
it('can report a manual stop using the explicit toolCallId override', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({ ok: true })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await reportManualRunToolStop('wf-1', 'tool-override')
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/copilot/confirm',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: expect.stringContaining('"toolCallId":"tool-override"'),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('prefers workflow_input, forwards triggerBlockId, and respects useDeployedState', async () => {
|
||||
executeWorkflowWithFullLogging.mockResolvedValueOnce({
|
||||
success: true,
|
||||
output: { ok: true },
|
||||
logs: [],
|
||||
})
|
||||
|
||||
executeRunToolOnClient('tool-2', 'run_workflow', {
|
||||
workflowId: 'wf-1',
|
||||
workflow_input: { prompt: 'preferred' },
|
||||
input: { prompt: 'fallback' },
|
||||
triggerBlockId: 'trigger-1',
|
||||
useDeployedState: true,
|
||||
})
|
||||
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
|
||||
expect(executeWorkflowWithFullLogging).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
workflowId: 'wf-1',
|
||||
workflowInput: { prompt: 'preferred' },
|
||||
overrideTriggerType: 'copilot',
|
||||
triggerBlockId: 'trigger-1',
|
||||
useDraftState: false,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('treats a tab-local execution pointer as handled in background', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({ ok: true })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
loadExecutionPointer.mockResolvedValueOnce({
|
||||
workflowId: 'wf-1',
|
||||
executionId: 'exec-existing',
|
||||
lastEventId: 7,
|
||||
})
|
||||
|
||||
await expect(bindRunToolToExecution('tool-3', 'wf-1')).resolves.toBe(true)
|
||||
|
||||
expect(setActiveWorkflow).not.toHaveBeenCalled()
|
||||
expect(setIsExecuting).not.toHaveBeenCalled()
|
||||
expect(setCurrentExecutionId).not.toHaveBeenCalled()
|
||||
expect(saveExecutionPointer).not.toHaveBeenCalled()
|
||||
expect(executeWorkflowWithFullLogging).not.toHaveBeenCalled()
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/copilot/confirm',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: expect.stringContaining('"status":"background"'),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('does not recover from shared console rows without a tab-local pointer', async () => {
|
||||
loadExecutionPointer.mockResolvedValueOnce(null)
|
||||
getWorkflowEntries.mockReturnValueOnce([
|
||||
{
|
||||
workflowId: 'wf-1',
|
||||
executionId: 'exec-shared',
|
||||
isRunning: true,
|
||||
startedAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
|
||||
await expect(bindRunToolToExecution('tool-4', 'wf-1')).resolves.toBe(false)
|
||||
|
||||
expect(setActiveWorkflow).not.toHaveBeenCalled()
|
||||
expect(setIsExecuting).not.toHaveBeenCalled()
|
||||
expect(setCurrentExecutionId).not.toHaveBeenCalled()
|
||||
expect(saveExecutionPointer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports local stream handler failures as background instead of workflow errors', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({ ok: true })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
getCurrentExecutionId.mockImplementation(
|
||||
() => saveExecutionPointer.mock.calls[0]?.[0]?.executionId ?? null
|
||||
)
|
||||
executeWorkflowWithFullLogging.mockRejectedValueOnce(
|
||||
new MockSSEEventHandlerError('handler failed', 'exec-1')
|
||||
)
|
||||
|
||||
executeRunToolOnClient('tool-5', 'run_workflow', { workflowId: 'wf-1' })
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/copilot/confirm',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: expect.stringContaining('"status":"background"'),
|
||||
})
|
||||
)
|
||||
})
|
||||
expect(clearExecutionPointer).not.toHaveBeenCalled()
|
||||
expect(setIsExecuting).toHaveBeenCalledWith('wf-1', false)
|
||||
expect(fetchMock).not.toHaveBeenCalledWith(
|
||||
'/api/copilot/confirm',
|
||||
expect.objectContaining({
|
||||
body: expect.stringContaining('"status":"error"'),
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,638 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { sleep } from '@sim/utils/helpers'
|
||||
import { generateId } from '@sim/utils/id'
|
||||
import { isRecordLike } from '@sim/utils/object'
|
||||
import {
|
||||
ASYNC_TOOL_CONFIRMATION_STATUS,
|
||||
type AsyncCompletionData,
|
||||
type AsyncConfirmationStatus,
|
||||
} from '@/lib/copilot/async-runs/lifecycle'
|
||||
import { COPILOT_CONFIRM_API_PATH } from '@/lib/copilot/constants'
|
||||
import { MothershipStreamV1ToolOutcome } from '@/lib/copilot/generated/mothership-stream-v1'
|
||||
import {
|
||||
RunBlock,
|
||||
RunFromBlock,
|
||||
RunWorkflowUntilBlock,
|
||||
} from '@/lib/copilot/generated/tool-catalog-v1'
|
||||
import { traceparentHeader } from '@/lib/copilot/tools/client/trace-context'
|
||||
import { executeWorkflowWithFullLogging } from '@/app/workspace/[workspaceId]/w/[workflowId]/utils/workflow-execution-utils'
|
||||
import { SSEEventHandlerError, SSEStreamInterruptedError } from '@/hooks/use-execution-stream'
|
||||
import { useExecutionStore } from '@/stores/execution/store'
|
||||
import {
|
||||
clearExecutionPointer,
|
||||
consolePersistence,
|
||||
loadExecutionPointer,
|
||||
saveExecutionPointer,
|
||||
} from '@/stores/terminal'
|
||||
import { useWorkflowRegistry } from '@/stores/workflows/registry/store'
|
||||
|
||||
const logger = createLogger('CopilotRunToolExecution')
|
||||
const activeRunToolByWorkflowId = new Map<string, string>()
|
||||
const activeRunAbortByWorkflowId = new Map<string, AbortController>()
|
||||
const manuallyStoppedToolCallIds = new Set<string>()
|
||||
const PENDING_COMPLETION_STORAGE_PREFIX = 'sim:copilot:run-tool-completion:'
|
||||
|
||||
interface PendingCompletionReport {
|
||||
status: AsyncConfirmationStatus
|
||||
message?: string
|
||||
data?: AsyncCompletionData
|
||||
}
|
||||
|
||||
class CompletionReportError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.name = 'CompletionReportError'
|
||||
}
|
||||
}
|
||||
|
||||
function resolveWorkflowInput(params: Record<string, unknown>): unknown {
|
||||
if (Object.hasOwn(params, 'workflow_input')) {
|
||||
return params.workflow_input
|
||||
}
|
||||
if (Object.hasOwn(params, 'input')) {
|
||||
return params.input
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function resolveTriggerBlockId(params: Record<string, unknown>): string | undefined {
|
||||
return typeof params.triggerBlockId === 'string' && params.triggerBlockId.length > 0
|
||||
? params.triggerBlockId
|
||||
: undefined
|
||||
}
|
||||
|
||||
function pendingCompletionStorageKey(toolCallId: string): string {
|
||||
return `${PENDING_COMPLETION_STORAGE_PREFIX}${toolCallId}`
|
||||
}
|
||||
|
||||
function savePendingCompletionReport(toolCallId: string, report: PendingCompletionReport): void {
|
||||
if (typeof window === 'undefined') return
|
||||
try {
|
||||
window.sessionStorage.setItem(pendingCompletionStorageKey(toolCallId), JSON.stringify(report))
|
||||
} catch (error) {
|
||||
logger.warn('[RunTool] Failed to persist pending completion report', {
|
||||
toolCallId,
|
||||
error: toError(error).message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function loadPendingCompletionReport(toolCallId: string): PendingCompletionReport | null {
|
||||
if (typeof window === 'undefined') return null
|
||||
try {
|
||||
const raw = window.sessionStorage.getItem(pendingCompletionStorageKey(toolCallId))
|
||||
if (!raw) return null
|
||||
const parsed = JSON.parse(raw) as PendingCompletionReport
|
||||
return parsed?.status ? parsed : null
|
||||
} catch (error) {
|
||||
logger.warn('[RunTool] Failed to load pending completion report', {
|
||||
toolCallId,
|
||||
error: toError(error).message,
|
||||
})
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function clearPendingCompletionReport(toolCallId: string): void {
|
||||
if (typeof window === 'undefined') return
|
||||
try {
|
||||
window.sessionStorage.removeItem(pendingCompletionStorageKey(toolCallId))
|
||||
} catch (error) {
|
||||
logger.warn('[RunTool] Failed to clear pending completion report', {
|
||||
toolCallId,
|
||||
error: toError(error).message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function bindRunToolToExecution(
|
||||
toolCallId: string,
|
||||
workflowId: string
|
||||
): Promise<boolean> {
|
||||
const existingToolCallId = activeRunToolByWorkflowId.get(workflowId)
|
||||
if (existingToolCallId === toolCallId) {
|
||||
logger.info('[RunTool] Recovery skipped: run tool is already active in this tab', {
|
||||
workflowId,
|
||||
toolCallId,
|
||||
})
|
||||
return true
|
||||
}
|
||||
if (existingToolCallId && existingToolCallId !== toolCallId) {
|
||||
logger.warn('[RunTool] Recovery skipped: another run tool is already active', {
|
||||
workflowId,
|
||||
toolCallId,
|
||||
existingToolCallId,
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
const pointer = await loadExecutionPointer(workflowId).catch(() => null)
|
||||
if (!pointer?.executionId) {
|
||||
logger.info('[RunTool] Recovery skipped: no tab-local execution pointer', {
|
||||
workflowId,
|
||||
toolCallId,
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
logger.info('[RunTool] Recovery moved to background for existing execution pointer', {
|
||||
workflowId,
|
||||
toolCallId,
|
||||
executionId: pointer.executionId,
|
||||
})
|
||||
const pendingCompletion = loadPendingCompletionReport(toolCallId)
|
||||
if (pendingCompletion) {
|
||||
try {
|
||||
await reportCompletion(
|
||||
toolCallId,
|
||||
pendingCompletion.status,
|
||||
pendingCompletion.message,
|
||||
pendingCompletion.data
|
||||
)
|
||||
clearPendingCompletionReport(toolCallId)
|
||||
} catch (error) {
|
||||
logger.warn('[RunTool] Failed to report recovered terminal completion', {
|
||||
workflowId,
|
||||
toolCallId,
|
||||
executionId: pointer.executionId,
|
||||
error: toError(error).message,
|
||||
})
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
try {
|
||||
await reportCompletion(
|
||||
toolCallId,
|
||||
ASYNC_TOOL_CONFIRMATION_STATUS.background,
|
||||
'Client recovered an existing workflow execution; continuing in background.',
|
||||
{
|
||||
workflowId,
|
||||
executionId: pointer.executionId,
|
||||
lastEventId: pointer.lastEventId,
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
logger.warn('[RunTool] Failed to report recovered execution as background', {
|
||||
workflowId,
|
||||
toolCallId,
|
||||
executionId: pointer.executionId,
|
||||
error: toError(error).message,
|
||||
})
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a run tool on the client side using the streaming execute endpoint.
|
||||
* This gives full interactive feedback: block pulsing, console logs, stop button.
|
||||
*
|
||||
* Mirrors staging's RunWorkflowClientTool.handleAccept():
|
||||
* 1. Execute via executeWorkflowWithFullLogging
|
||||
* 2. Update client tool state directly (success/error)
|
||||
* 3. Report completion to server via /api/copilot/confirm (Redis),
|
||||
* where the server-side handler picks it up and tells Go
|
||||
*/
|
||||
export function executeRunToolOnClient(
|
||||
toolCallId: string,
|
||||
toolName: string,
|
||||
params: Record<string, unknown>
|
||||
): void {
|
||||
doExecuteRunTool(toolCallId, toolName, params).catch((err) => {
|
||||
logger.error('[RunTool] Unhandled error in client-side run tool execution', {
|
||||
toolCallId,
|
||||
toolName,
|
||||
error: toError(err).message,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronously mark the active run tool for a workflow as manually stopped.
|
||||
* Must be called before issuing the cancellation request so that the
|
||||
* concurrent doExecuteRunTool catch/success paths see the marker and skip
|
||||
* their own completion report.
|
||||
*/
|
||||
export function markRunToolManuallyStopped(workflowId: string): string | null {
|
||||
const toolCallId = activeRunToolByWorkflowId.get(workflowId)
|
||||
if (!toolCallId) return null
|
||||
manuallyStoppedToolCallIds.add(toolCallId)
|
||||
return toolCallId
|
||||
}
|
||||
|
||||
export function isRunToolActiveForId(toolCallId: string): boolean {
|
||||
for (const activeId of activeRunToolByWorkflowId.values()) {
|
||||
if (activeId === toolCallId) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function cancelRunToolExecution(workflowId: string): void {
|
||||
const controller = activeRunAbortByWorkflowId.get(workflowId)
|
||||
if (!controller) return
|
||||
controller.abort('user_stop:cancelRunToolExecution')
|
||||
activeRunAbortByWorkflowId.delete(workflowId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Report a manual user-initiated stop for an active client-executed run tool.
|
||||
* This lets Copilot know the run was intentionally cancelled by the user.
|
||||
* Call markRunToolManuallyStopped first to prevent race conditions.
|
||||
*/
|
||||
export async function reportManualRunToolStop(
|
||||
workflowId: string,
|
||||
toolCallIdOverride?: string | null
|
||||
): Promise<void> {
|
||||
const toolCallId = toolCallIdOverride || activeRunToolByWorkflowId.get(workflowId)
|
||||
if (!toolCallId) return
|
||||
|
||||
if (!manuallyStoppedToolCallIds.has(toolCallId)) {
|
||||
manuallyStoppedToolCallIds.add(toolCallId)
|
||||
}
|
||||
|
||||
await reportCompletion(
|
||||
toolCallId,
|
||||
MothershipStreamV1ToolOutcome.cancelled,
|
||||
'Workflow execution was stopped manually by the user.',
|
||||
{
|
||||
reason: 'user_cancelled',
|
||||
cancelledByUser: true,
|
||||
workflowId,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
async function doExecuteRunTool(
|
||||
toolCallId: string,
|
||||
toolName: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
const { activeWorkflowId, setActiveWorkflow } = useWorkflowRegistry.getState()
|
||||
const targetWorkflowId =
|
||||
typeof params.workflowId === 'string' && params.workflowId.length > 0
|
||||
? params.workflowId
|
||||
: activeWorkflowId
|
||||
|
||||
if (!targetWorkflowId) {
|
||||
logger.warn('[RunTool] Execution prevented: no active workflow', { toolCallId, toolName })
|
||||
await reportCompletion(
|
||||
toolCallId,
|
||||
MothershipStreamV1ToolOutcome.error,
|
||||
'No active workflow found'
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const existingToolCallId = activeRunToolByWorkflowId.get(targetWorkflowId)
|
||||
if (existingToolCallId) {
|
||||
logger.warn('[RunTool] Execution prevented: another run tool is already active', {
|
||||
toolCallId,
|
||||
toolName,
|
||||
existingToolCallId,
|
||||
})
|
||||
await reportCompletion(
|
||||
toolCallId,
|
||||
MothershipStreamV1ToolOutcome.error,
|
||||
'Workflow is already being executed by another tool. Wait for it to complete.'
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
setActiveWorkflow(targetWorkflowId)
|
||||
activeRunToolByWorkflowId.set(targetWorkflowId, toolCallId)
|
||||
|
||||
const { getWorkflowExecution, setIsExecuting } = useExecutionStore.getState()
|
||||
const { isExecuting } = getWorkflowExecution(targetWorkflowId)
|
||||
|
||||
if (isExecuting) {
|
||||
logger.warn('[RunTool] Execution prevented: already executing', { toolCallId, toolName })
|
||||
activeRunToolByWorkflowId.delete(targetWorkflowId)
|
||||
await reportCompletion(
|
||||
toolCallId,
|
||||
MothershipStreamV1ToolOutcome.error,
|
||||
'Workflow is already executing. Try again later'
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Extract params for all tool types
|
||||
const workflowInput = resolveWorkflowInput(params)
|
||||
const triggerBlockId = resolveTriggerBlockId(params)
|
||||
const useDraftState = params.useDeployedState !== true
|
||||
|
||||
const stopAfterBlockId = (() => {
|
||||
if (toolName === RunWorkflowUntilBlock.id) return params.stopAfterBlockId as string | undefined
|
||||
if (toolName === RunBlock.id) return params.blockId as string | undefined
|
||||
return undefined
|
||||
})()
|
||||
|
||||
const runFromBlock = (() => {
|
||||
if (toolName === RunFromBlock.id && params.startBlockId) {
|
||||
return {
|
||||
startBlockId: params.startBlockId as string,
|
||||
executionId: (params.executionId as string | undefined) || 'latest',
|
||||
}
|
||||
}
|
||||
if (toolName === RunBlock.id && params.blockId) {
|
||||
return {
|
||||
startBlockId: params.blockId as string,
|
||||
executionId: (params.executionId as string | undefined) || 'latest',
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
})()
|
||||
|
||||
const { setCurrentExecutionId } = useExecutionStore.getState()
|
||||
const abortController = new AbortController()
|
||||
activeRunAbortByWorkflowId.set(targetWorkflowId, abortController)
|
||||
|
||||
consolePersistence.executionStarted()
|
||||
setIsExecuting(targetWorkflowId, true)
|
||||
const executionId = generateId()
|
||||
setCurrentExecutionId(targetWorkflowId, executionId)
|
||||
saveExecutionPointer({ workflowId: targetWorkflowId, executionId, lastEventId: 0 })
|
||||
const executionStartTime = new Date().toISOString()
|
||||
const releaseVisibleExecutionForBackground = () => {
|
||||
const { setCurrentExecutionId: clearExecId, setActiveBlocks } = useExecutionStore.getState()
|
||||
if (activeRunToolByWorkflowId.get(targetWorkflowId) === toolCallId) {
|
||||
clearExecId(targetWorkflowId, null)
|
||||
consolePersistence.executionEnded()
|
||||
setIsExecuting(targetWorkflowId, false)
|
||||
setActiveBlocks(targetWorkflowId, new Set())
|
||||
}
|
||||
}
|
||||
|
||||
const onPageHide = () => {
|
||||
if (manuallyStoppedToolCallIds.has(toolCallId)) return
|
||||
navigator.sendBeacon(
|
||||
COPILOT_CONFIRM_API_PATH,
|
||||
new Blob(
|
||||
[
|
||||
JSON.stringify({
|
||||
toolCallId,
|
||||
status: 'background',
|
||||
message: 'Client disconnected, execution continuing server-side',
|
||||
}),
|
||||
],
|
||||
{ type: 'application/json' }
|
||||
)
|
||||
)
|
||||
}
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('pagehide', onPageHide)
|
||||
}
|
||||
|
||||
logger.info('[RunTool] Starting client-side workflow execution', {
|
||||
toolCallId,
|
||||
toolName,
|
||||
executionId,
|
||||
workflowId: targetWorkflowId,
|
||||
hasInput: !!workflowInput,
|
||||
triggerBlockId,
|
||||
useDraftState,
|
||||
stopAfterBlockId,
|
||||
runFromBlock: runFromBlock ? { startBlockId: runFromBlock.startBlockId } : undefined,
|
||||
})
|
||||
|
||||
let leaveExecutionRecoverable = false
|
||||
|
||||
try {
|
||||
const result = await executeWorkflowWithFullLogging({
|
||||
workflowId: targetWorkflowId,
|
||||
workflowInput,
|
||||
executionId,
|
||||
overrideTriggerType: 'copilot',
|
||||
triggerBlockId,
|
||||
useDraftState,
|
||||
stopAfterBlockId,
|
||||
runFromBlock,
|
||||
abortSignal: abortController.signal,
|
||||
preserveExecutionOnTerminal: true,
|
||||
})
|
||||
|
||||
// Determine success (same logic as staging's RunWorkflowClientTool)
|
||||
let succeeded = true
|
||||
let errorMessage: string | undefined
|
||||
try {
|
||||
if (result && typeof result === 'object' && 'success' in (result as any)) {
|
||||
succeeded = Boolean((result as any).success)
|
||||
if (!succeeded) {
|
||||
errorMessage = (result as any)?.error || (result as any)?.output?.error
|
||||
}
|
||||
} else if (
|
||||
result &&
|
||||
typeof result === 'object' &&
|
||||
'execution' in (result as any) &&
|
||||
(result as any).execution
|
||||
) {
|
||||
succeeded = Boolean((result as any).execution.success)
|
||||
if (!succeeded) {
|
||||
errorMessage =
|
||||
(result as any).execution?.error || (result as any).execution?.output?.error
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
if (manuallyStoppedToolCallIds.has(toolCallId)) {
|
||||
logger.info('[RunTool] Skipping generic completion — already manually stopped', {
|
||||
toolCallId,
|
||||
toolName,
|
||||
})
|
||||
} else if (succeeded) {
|
||||
logger.info('[RunTool] Workflow execution succeeded', { toolCallId, toolName })
|
||||
const pendingCompletion = {
|
||||
status: MothershipStreamV1ToolOutcome.success,
|
||||
message: `Workflow execution completed. Started at: ${executionStartTime}`,
|
||||
data: buildResultData(result),
|
||||
}
|
||||
savePendingCompletionReport(toolCallId, pendingCompletion)
|
||||
await reportCompletion(
|
||||
toolCallId,
|
||||
pendingCompletion.status,
|
||||
pendingCompletion.message,
|
||||
pendingCompletion.data
|
||||
)
|
||||
clearPendingCompletionReport(toolCallId)
|
||||
} else {
|
||||
const msg = errorMessage || 'Workflow execution failed'
|
||||
logger.error('[RunTool] Workflow execution failed', { toolCallId, toolName, error: msg })
|
||||
const pendingCompletion = {
|
||||
status: MothershipStreamV1ToolOutcome.error,
|
||||
message: msg,
|
||||
data: buildResultData(result),
|
||||
}
|
||||
savePendingCompletionReport(toolCallId, pendingCompletion)
|
||||
await reportCompletion(
|
||||
toolCallId,
|
||||
pendingCompletion.status,
|
||||
pendingCompletion.message,
|
||||
pendingCompletion.data
|
||||
)
|
||||
clearPendingCompletionReport(toolCallId)
|
||||
}
|
||||
} catch (err) {
|
||||
if (manuallyStoppedToolCallIds.has(toolCallId)) {
|
||||
logger.info('[RunTool] Skipping error completion — already manually stopped', {
|
||||
toolCallId,
|
||||
toolName,
|
||||
})
|
||||
} else {
|
||||
const msg = toError(err).message
|
||||
if (err instanceof SSEEventHandlerError || err instanceof SSEStreamInterruptedError) {
|
||||
leaveExecutionRecoverable = true
|
||||
logger.warn(
|
||||
'[RunTool] Execution stream interrupted; leaving workflow execution in background',
|
||||
{
|
||||
toolCallId,
|
||||
toolName,
|
||||
executionId: err.executionId,
|
||||
error: msg,
|
||||
}
|
||||
)
|
||||
releaseVisibleExecutionForBackground()
|
||||
await reportCompletion(
|
||||
toolCallId,
|
||||
ASYNC_TOOL_CONFIRMATION_STATUS.background,
|
||||
'Client lost local stream processing; workflow execution may still be continuing server-side.'
|
||||
)
|
||||
return
|
||||
}
|
||||
if (err instanceof CompletionReportError) {
|
||||
leaveExecutionRecoverable = true
|
||||
logger.warn('[RunTool] Completion report failed; leaving workflow execution recoverable', {
|
||||
toolCallId,
|
||||
toolName,
|
||||
error: msg,
|
||||
})
|
||||
releaseVisibleExecutionForBackground()
|
||||
return
|
||||
}
|
||||
logger.error('[RunTool] Workflow execution threw', { toolCallId, toolName, error: msg })
|
||||
await reportCompletion(toolCallId, MothershipStreamV1ToolOutcome.error, msg)
|
||||
}
|
||||
} finally {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.removeEventListener('pagehide', onPageHide)
|
||||
}
|
||||
manuallyStoppedToolCallIds.delete(toolCallId)
|
||||
const activeToolCallId = activeRunToolByWorkflowId.get(targetWorkflowId)
|
||||
if (activeToolCallId === toolCallId) {
|
||||
activeRunToolByWorkflowId.delete(targetWorkflowId)
|
||||
}
|
||||
const activeAbortController = activeRunAbortByWorkflowId.get(targetWorkflowId)
|
||||
if (activeAbortController === abortController) {
|
||||
activeRunAbortByWorkflowId.delete(targetWorkflowId)
|
||||
}
|
||||
const { setCurrentExecutionId: clearExecId, setActiveBlocks } = useExecutionStore.getState()
|
||||
if (!leaveExecutionRecoverable && activeToolCallId === toolCallId) {
|
||||
clearExecId(targetWorkflowId, null)
|
||||
clearExecutionPointer(targetWorkflowId)
|
||||
consolePersistence.executionEnded()
|
||||
setIsExecuting(targetWorkflowId, false)
|
||||
setActiveBlocks(targetWorkflowId, new Set())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a structured result payload from the raw execution result
|
||||
* for the LLM to see the actual workflow output.
|
||||
*/
|
||||
function buildResultData(result: unknown): Record<string, unknown> | undefined {
|
||||
if (!result || typeof result !== 'object') return undefined
|
||||
|
||||
const r = result as Record<string, unknown>
|
||||
|
||||
if ('success' in r) {
|
||||
return {
|
||||
success: r.success,
|
||||
output: r.output,
|
||||
logs: r.logs,
|
||||
error: r.error,
|
||||
}
|
||||
}
|
||||
|
||||
if ('execution' in r && r.execution && typeof r.execution === 'object') {
|
||||
const exec = r.execution as Record<string, unknown>
|
||||
return {
|
||||
success: exec.success,
|
||||
output: exec.output,
|
||||
logs: exec.logs,
|
||||
error: exec.error,
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Report tool completion to the server via the existing /api/copilot/confirm endpoint.
|
||||
* This persists the durable async-tool row and wakes the server-side waiter so
|
||||
* it can continue the paused Copilot run and notify Go.
|
||||
*/
|
||||
async function reportCompletion(
|
||||
toolCallId: string,
|
||||
status: AsyncConfirmationStatus,
|
||||
message?: string,
|
||||
data?: AsyncCompletionData
|
||||
): Promise<void> {
|
||||
const basePayload = {
|
||||
toolCallId,
|
||||
status,
|
||||
message: message || (status === 'success' ? 'Tool completed' : 'Tool failed'),
|
||||
...(data !== undefined ? { data } : {}),
|
||||
}
|
||||
const send = async (body: string) =>
|
||||
fetch(COPILOT_CONFIRM_API_PATH, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...traceparentHeader() },
|
||||
body,
|
||||
})
|
||||
|
||||
const body = JSON.stringify(basePayload)
|
||||
const LARGE_PAYLOAD_THRESHOLD = 10 * 1024 * 1024
|
||||
const bodySize = new Blob([body]).size
|
||||
let lastError: Error | null = null
|
||||
|
||||
for (let attempt = 1; attempt <= 2; attempt++) {
|
||||
try {
|
||||
const res = await send(body)
|
||||
if (res.ok) return
|
||||
|
||||
if (isRecordLike(data) && bodySize > LARGE_PAYLOAD_THRESHOLD) {
|
||||
const { logs: _logs, ...dataWithoutLogs } = data
|
||||
logger.warn('[RunTool] reportCompletion failed with large payload, retrying without logs', {
|
||||
toolCallId,
|
||||
status: res.status,
|
||||
bodySize,
|
||||
})
|
||||
const retryRes = await send(
|
||||
JSON.stringify({
|
||||
toolCallId,
|
||||
status,
|
||||
message: message || (status === 'success' ? 'Tool completed' : 'Tool failed'),
|
||||
data: dataWithoutLogs,
|
||||
})
|
||||
)
|
||||
if (retryRes.ok) return
|
||||
lastError = new Error(`reportCompletion retry failed with status ${retryRes.status}`)
|
||||
} else {
|
||||
lastError = new Error(`reportCompletion failed with status ${res.status}`)
|
||||
}
|
||||
} catch (err) {
|
||||
lastError = toError(err)
|
||||
}
|
||||
|
||||
if (attempt < 2) {
|
||||
await sleep(250)
|
||||
}
|
||||
}
|
||||
|
||||
logger.error('[RunTool] reportCompletion failed after retries', {
|
||||
toolCallId,
|
||||
error: lastError?.message,
|
||||
})
|
||||
throw new CompletionReportError(lastError?.message ?? 'Failed to report tool completion')
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Read as ReadTool } from '@/lib/copilot/generated/tool-catalog-v1'
|
||||
import { resolveToolDisplay } from './store-utils'
|
||||
import { ClientToolCallState } from './tool-call-state'
|
||||
|
||||
describe('resolveToolDisplay', () => {
|
||||
it('uses a friendly label for internal respond tools', () => {
|
||||
expect(resolveToolDisplay('respond', ClientToolCallState.executing)?.text).toBe(
|
||||
'Gathering thoughts'
|
||||
)
|
||||
expect(resolveToolDisplay('workflow_respond', ClientToolCallState.success)?.text).toBe(
|
||||
'Gathering thoughts'
|
||||
)
|
||||
})
|
||||
|
||||
it('formats read targets from workspace paths', () => {
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.executing, {
|
||||
path: 'files/report.pdf',
|
||||
})?.text
|
||||
).toBe('Reading report.pdf')
|
||||
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.success, {
|
||||
path: 'workflows/My Workflow/meta.json',
|
||||
})?.text
|
||||
).toBe('Read My Workflow')
|
||||
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.success, {
|
||||
path: 'workflows/Folder 1/RET XYZ/state.json',
|
||||
})?.text
|
||||
).toBe('Read RET XYZ')
|
||||
})
|
||||
|
||||
it('decodes percent-encoded VFS path segments for display', () => {
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.executing, {
|
||||
path: 'files/My%20Report.txt',
|
||||
})?.text
|
||||
).toBe('Reading My Report.txt')
|
||||
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.success, {
|
||||
path: 'workflows/My%20Workflow/meta.json',
|
||||
})?.text
|
||||
).toBe('Read My Workflow')
|
||||
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.executing, {
|
||||
path: 'files/caf%C3%A9.txt',
|
||||
})?.text
|
||||
).toBe('Reading café.txt')
|
||||
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.success, {
|
||||
path: 'files/Quarterly%20Report.docx/content',
|
||||
})?.text
|
||||
).toBe('Read Quarterly Report.docx')
|
||||
})
|
||||
|
||||
it('shows only the file name for file reads, dropping the folder path and content qualifier', () => {
|
||||
// Bare file leaf inside a folder → just the file name (with extension).
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.success, {
|
||||
path: 'files/Skills/Skill%20%E2%80%94%20PostHog%20Analytics.md',
|
||||
})?.text
|
||||
).toBe('Read Skill — PostHog Analytics.md')
|
||||
|
||||
// Explicit content facet → no "the content of", folder dropped too.
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.success, {
|
||||
path: 'files/Skills/Skill%20%E2%80%94%20PostHog%20Analytics.md/content',
|
||||
})?.text
|
||||
).toBe('Read Skill — PostHog Analytics.md')
|
||||
|
||||
// Non-content facets keep their descriptive label but still show only the name.
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.executing, {
|
||||
path: 'files/Reports/brief.docx/meta.json',
|
||||
})?.text
|
||||
).toBe('Reading metadata for brief.docx')
|
||||
})
|
||||
|
||||
it('falls back to the raw segment when it is not valid percent-encoding', () => {
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.executing, {
|
||||
path: 'files/100%done.txt',
|
||||
})?.text
|
||||
).toBe('Reading 100%done.txt')
|
||||
})
|
||||
|
||||
it('formats special workspace file reads as natural language', () => {
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.error, {
|
||||
path: 'files/haiku_collection_sim.pptx/compiled-check',
|
||||
})?.text
|
||||
).toBe('Attempted to read the final file check for haiku_collection_sim.pptx')
|
||||
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.success, {
|
||||
path: 'files/Reports/brief.docx/content',
|
||||
})?.text
|
||||
).toBe('Read brief.docx')
|
||||
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.executing, {
|
||||
path: 'files/report.pdf/meta.json',
|
||||
})?.text
|
||||
).toBe('Reading metadata for report.pdf')
|
||||
|
||||
expect(
|
||||
resolveToolDisplay(ReadTool.id, ClientToolCallState.success, {
|
||||
path: 'files/deck.pptx/style',
|
||||
})?.text
|
||||
).toBe('Read style details for deck.pptx')
|
||||
})
|
||||
|
||||
it('falls back to a humanized tool label for generic tools', () => {
|
||||
expect(resolveToolDisplay('deploy_api', ClientToolCallState.success)?.text).toBe(
|
||||
'Executed Deploy Api'
|
||||
)
|
||||
})
|
||||
|
||||
it('hides internal deferred tool loaders', () => {
|
||||
expect(resolveToolDisplay('load_custom_tool', ClientToolCallState.executing)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,184 @@
|
||||
import type { ComponentType } from 'react'
|
||||
import { Loader } from '@sim/emcn'
|
||||
import { FileText } from 'lucide-react'
|
||||
import { Read as ReadTool } from '@/lib/copilot/generated/tool-catalog-v1'
|
||||
import { VFS_DIR_TO_RESOURCE } from '@/lib/copilot/resources/types'
|
||||
import { isToolHiddenInUi } from '@/lib/copilot/tools/client/hidden-tools'
|
||||
import { ClientToolCallState } from '@/lib/copilot/tools/client/tool-call-state'
|
||||
import { decodeVfsSegment } from '@/lib/copilot/vfs/path-utils'
|
||||
|
||||
/** Respond tools are internal handoff tools shown with a friendly generic label. */
|
||||
const HIDDEN_TOOL_SUFFIX = '_respond'
|
||||
const INTERNAL_RESPOND_TOOL = 'respond'
|
||||
|
||||
interface ClientToolDisplay {
|
||||
text: string
|
||||
icon: ComponentType<{ className?: string }>
|
||||
}
|
||||
|
||||
export function resolveToolDisplay(
|
||||
toolName: string | undefined,
|
||||
state: ClientToolCallState,
|
||||
params?: Record<string, unknown>
|
||||
): ClientToolDisplay | undefined {
|
||||
if (!toolName) return undefined
|
||||
if (isToolHiddenInUi(toolName)) return undefined
|
||||
|
||||
const specialDisplay = specialToolDisplay(toolName, state, params)
|
||||
if (specialDisplay) return specialDisplay
|
||||
|
||||
return humanizedFallback(toolName, state)
|
||||
}
|
||||
|
||||
function specialToolDisplay(
|
||||
toolName: string,
|
||||
state: ClientToolCallState,
|
||||
params?: Record<string, unknown>
|
||||
): ClientToolDisplay | undefined {
|
||||
if (toolName === INTERNAL_RESPOND_TOOL || toolName.endsWith(HIDDEN_TOOL_SUFFIX)) {
|
||||
return {
|
||||
text: formatRespondLabel(state),
|
||||
icon: Loader,
|
||||
}
|
||||
}
|
||||
|
||||
if (toolName === ReadTool.id) {
|
||||
const target = describeReadTarget(readStringParam(params, 'path'))
|
||||
return {
|
||||
text: formatReadingLabel(target, state),
|
||||
icon: FileText,
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
function formatRespondLabel(state: ClientToolCallState): string {
|
||||
void state
|
||||
return 'Gathering thoughts'
|
||||
}
|
||||
|
||||
function readStringParam(
|
||||
params: Record<string, unknown> | undefined,
|
||||
key: string
|
||||
): string | undefined {
|
||||
const value = params?.[key]
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : undefined
|
||||
}
|
||||
|
||||
function formatReadingLabel(target: string | undefined, state: ClientToolCallState): string {
|
||||
const suffix = target ? ` ${target}` : ''
|
||||
switch (state) {
|
||||
case ClientToolCallState.success:
|
||||
return `Read${suffix}`
|
||||
case ClientToolCallState.error:
|
||||
return `Attempted to read${suffix}`
|
||||
case ClientToolCallState.rejected:
|
||||
case ClientToolCallState.aborted:
|
||||
return `Skipped reading${suffix}`
|
||||
default:
|
||||
return `Reading${suffix}`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* VFS paths store each segment percent-encoded (see {@link encodeVfsSegment}), so
|
||||
* a read on "My Report.txt" arrives as "files/My%20Report.txt". Decode for
|
||||
* display so the user sees the real file name. Falls back to the raw segment when
|
||||
* it is not valid encoding (e.g. a literal "%" that was never encoded).
|
||||
*/
|
||||
function decodeVfsSegmentSafe(segment: string): string {
|
||||
try {
|
||||
return decodeVfsSegment(segment)
|
||||
} catch {
|
||||
return segment
|
||||
}
|
||||
}
|
||||
|
||||
function describeReadTarget(path: string | undefined): string | undefined {
|
||||
if (!path) return undefined
|
||||
|
||||
const segments = path
|
||||
.split('/')
|
||||
.map((segment) => segment.trim())
|
||||
.filter(Boolean)
|
||||
.map(decodeVfsSegmentSafe)
|
||||
|
||||
if (segments.length === 0) return undefined
|
||||
|
||||
const resourceType = VFS_DIR_TO_RESOURCE[segments[0]]
|
||||
if (!resourceType) {
|
||||
return stripExtension(segments[segments.length - 1])
|
||||
}
|
||||
|
||||
if (resourceType === 'file') {
|
||||
return describeFileReadTarget(segments)
|
||||
}
|
||||
|
||||
if (resourceType === 'workflow') {
|
||||
return stripExtension(getLeafResourceSegment(segments))
|
||||
}
|
||||
|
||||
const resourceName = segments[1] || segments[segments.length - 1]
|
||||
return stripExtension(resourceName)
|
||||
}
|
||||
|
||||
// A workspace file is addressed as a directory of facets in the VFS
|
||||
// (files/{...path}/{name}/{facet}). `content` is the default facet — reading a
|
||||
// file means reading its content — so it carries no qualifier, matching a bare
|
||||
// `files/{...path}/{name}` read. The remaining facets are genuinely distinct, so
|
||||
// they keep a descriptive label.
|
||||
const FILE_FACET_LABELS: Record<string, string> = {
|
||||
content: '',
|
||||
'meta.json': 'metadata for',
|
||||
style: 'style details for',
|
||||
'compiled-check': 'the final file check for',
|
||||
}
|
||||
|
||||
function describeFileReadTarget(segments: string[]): string {
|
||||
const lastSegment = segments[segments.length - 1] || ''
|
||||
const facetLabel = FILE_FACET_LABELS[lastSegment]
|
||||
// Treat the suffix as a facet only when a real file name precedes it; otherwise
|
||||
// the leaf is the file itself (e.g. a file literally named "content").
|
||||
if (facetLabel !== undefined && segments.length > 2) {
|
||||
const fileName = segments[segments.length - 2]
|
||||
return facetLabel ? `${facetLabel} ${fileName}` : fileName
|
||||
}
|
||||
// Show just the file name, not the folder path — these are glanceable status
|
||||
// lines, and the other resource types already render the leaf only.
|
||||
return lastSegment
|
||||
}
|
||||
|
||||
function getLeafResourceSegment(segments: string[]): string {
|
||||
const lastSegment = segments[segments.length - 1] || ''
|
||||
if (hasFileExtension(lastSegment) && segments.length > 1) {
|
||||
return segments[segments.length - 2] || lastSegment
|
||||
}
|
||||
return lastSegment
|
||||
}
|
||||
|
||||
function hasFileExtension(value: string): boolean {
|
||||
return /\.[^/.]+$/.test(value)
|
||||
}
|
||||
|
||||
function stripExtension(value: string): string {
|
||||
return value.replace(/\.[^/.]+$/, '')
|
||||
}
|
||||
|
||||
function humanizedFallback(
|
||||
toolName: string,
|
||||
state: ClientToolCallState
|
||||
): ClientToolDisplay | undefined {
|
||||
const titleCaseName = toolName.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
|
||||
if (state === ClientToolCallState.error) {
|
||||
const lowerCaseName = toolName.replace(/_/g, ' ').toLowerCase()
|
||||
return { text: `Attempted to ${lowerCaseName}`, icon: Loader }
|
||||
}
|
||||
const stateVerb =
|
||||
state === ClientToolCallState.success
|
||||
? 'Executed'
|
||||
: state === ClientToolCallState.rejected || state === ClientToolCallState.aborted
|
||||
? 'Skipped'
|
||||
: 'Executing'
|
||||
return { text: `${stateVerb} ${titleCaseName}`, icon: Loader }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export enum ClientToolCallState {
|
||||
generating = 'generating',
|
||||
pending = 'pending',
|
||||
executing = 'executing',
|
||||
aborted = 'aborted',
|
||||
rejected = 'rejected',
|
||||
success = 'success',
|
||||
error = 'error',
|
||||
cancelled = 'cancelled',
|
||||
review = 'review',
|
||||
background = 'background',
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Browser-side W3C traceparent holder for the active copilot chat.
|
||||
// Module-level singleton because client tool callbacks fire from deep
|
||||
// inside runtime code that can't thread a React ref. The browser only
|
||||
// has one active chat at a time (gated by the stop-barrier), so a
|
||||
// singleton is safe.
|
||||
|
||||
let currentTraceparent: string | undefined
|
||||
|
||||
export function setCurrentChatTraceparent(value: string | undefined): void {
|
||||
currentTraceparent = value
|
||||
}
|
||||
|
||||
// `fetch` header spread: `headers: { ...traceparentHeader(), ... }`.
|
||||
export function traceparentHeader(): Record<string, string> {
|
||||
const tp = currentTraceparent
|
||||
return tp ? { traceparent: tp } : {}
|
||||
}
|
||||
Reference in New Issue
Block a user