diff --git a/packages/app/src/main/api/agentThreadFileEditProxy.test.ts b/packages/app/src/main/api/agentThreadFileEditProxy.test.ts index f4a695153..5c975c15f 100644 --- a/packages/app/src/main/api/agentThreadFileEditProxy.test.ts +++ b/packages/app/src/main/api/agentThreadFileEditProxy.test.ts @@ -7,18 +7,48 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' vi.unmock('node:fs') vi.unmock('node:fs/promises') const h = vi.hoisted(() => ({ - data: '', fromId: vi.fn(), parent: vi.fn(), fetch: vi.fn(), handle: vi.fn(), invoke: vi.fn(), + data: '', + fromId: vi.fn(), + parent: vi.fn(), + fetch: vi.fn(), + handle: vi.fn(), + invoke: vi.fn(), runtime: undefined as import('../assistantRuntime/runtime').AssistantRuntime | undefined })) -vi.mock('electron', () => ({ ipcMain: { handle: h.handle, on: vi.fn() }, ipcRenderer: { invoke: h.invoke }, MessagePortMain: class {}, net: {}, app: { getPath: () => h.data, getAppPath: () => process.cwd(), isReady: () => true }, webContents: { fromId: h.fromId }, BrowserWindow: { fromWebContents: h.parent } })) -vi.mock('../config/buildEnv', () => ({ getBuildEnv: () => ({ ...DEFAULT_BUILD_ENV, pathMap: { data: h.data, file: h.data, resources: '' } }) })) -vi.mock('../config/config', () => ({ getConfig: vi.fn(), saveConfig: vi.fn(), onConfigCommitted: vi.fn() })) -vi.mock(import('@shared/llm'), async original => ({ ...(await original()), cliFromProfile: vi.fn() })) +vi.mock('electron', () => ({ + ipcMain: { handle: h.handle, on: vi.fn() }, + ipcRenderer: { invoke: h.invoke }, + MessagePortMain: class {}, + net: {}, + app: { getPath: () => h.data, getAppPath: () => process.cwd(), isReady: () => true }, + webContents: { fromId: h.fromId }, + BrowserWindow: { fromWebContents: h.parent } +})) +vi.mock('../config/buildEnv', () => ({ + getBuildEnv: () => ({ + ...DEFAULT_BUILD_ENV, + pathMap: { data: h.data, file: h.data, resources: '' } + }) +})) +vi.mock('../config/config', () => ({ + getConfig: vi.fn(), + saveConfig: vi.fn(), + onConfigCommitted: vi.fn() +})) +vi.mock(import('@shared/llm'), async (original) => ({ + ...(await original()), + cliFromProfile: vi.fn() +})) import { projectNativeToolTurns } from '@shared/llm/nativeTools' import type { LLMChatParams, LLMChatResult } from '@shared/llm/types' import { DEFAULT_BUILD_ENV } from '@shared/config/buildEnv' -import { llmProxySvcDef, type LLMChatStreamResp, type LLMChatReq, type LLMChatResp } from '@shared/api/svcLLMProxy' +import { + llmProxySvcDef, + type LLMChatStreamResp, + type LLMChatReq, + type LLMChatResp +} from '@shared/api/svcLLMProxy' import { registerIpcServer } from '@shared/api/createServer/registerIpcServer' import { createIpcClient } from '@shared/api/createClient/createIpcClient' import { IpcServiceError } from '@shared/api/apiUtils/unaryIpcResult' @@ -30,17 +60,34 @@ import { AssistantRuntime } from '../assistantRuntime/runtime' import { AssistantSessionStore } from '../assistantRuntime/sessionStore' import { ensureAssistantWorkspaceState } from '../assistantRuntime/workspace' import { LLMProxySvcImpl } from './svcLLMProxyImpl' -import { getAssistantTerminalPolicyRuntime, closeAssistantTerminalPolicyRuntime } from '../magicAgentPlatform2/productionRuntime' +import { + getAssistantTerminalPolicyRuntime, + closeAssistantTerminalPolicyRuntime +} from '../magicAgentPlatform2/productionRuntime' import { stopMcpClientManager } from '../mcp/runtime' import { stopMagicPotMcpPlatformRuntime } from '../mcp/platform/runtime' import { TOOL_AUDIT_STREAM_ID } from '../magicAgentPlatform2/toolHost/auditSink' -import { clearMagicAgentTrustedRouteBindingsForTest, registerMagicAgentTrustedRouteBinding } from '../magicAgentRuntime/trustedRouteBinding' +import { + clearMagicAgentTrustedRouteBindingsForTest, + registerMagicAgentTrustedRouteBinding +} from '../magicAgentRuntime/trustedRouteBinding' import { createNodeTestArtifactDir } from '../testSupport/nodeTestArtifacts' -const route = { channel: 'canvas', scopeType: 'thread', scopeId: 'file-edit-project', threadId: 'pane' } as const +const route = { + channel: 'canvas', + scopeType: 'thread', + scopeId: 'file-edit-project', + threadId: 'pane' +} as const const scope = { route, conversationId: 'file-edit-chat' } const url = 'file:///D:/owned/app/index.html#/canvas?id=file-edit-project' -const invoke = (name: string) => ({ methodName: `svcLLMProxy.${name}`, senderId: 96, frameUrl: url, senderUrl: url, isMainFrame: true }) +const invoke = (name: string) => ({ + methodName: `svcLLMProxy.${name}`, + senderId: 96, + frameUrl: url, + senderUrl: url, + isMainFrame: true +}) const hash = (text: string) => createHash('sha256').update(text).digest('hex') let sender: EventEmitter, root: string, store: AssistantSessionStore, service: LLMProxySvcImpl @@ -48,17 +95,35 @@ beforeEach(async () => { h.data = await fs.realpath(await createNodeTestArtifactDir('proxy-file-edit')) const config = structuredClone(DEFAULT_CONFIG) config.mcp_config.client.servers = [] - config.llm_config.api_profiles = [{ id: 'agent-profile', model_name: 'Agent Model', base_url: 'https://model.example/v1', api_key: 'not-used' }] + config.llm_config.api_profiles = [ + { + id: 'agent-profile', + model_name: 'Agent Model', + base_url: 'https://model.example/v1', + api_key: 'not-used' + } + ] vi.mocked(getConfig).mockReturnValue(config) vi.stubEnv('MAGICPOT_MCP_STDIO_SERVER', '') h.fetch.mockReset().mockRejectedValue(Error('This fixture must not use the network.')) vi.stubGlobal('fetch', h.fetch) - sender = Object.assign(new EventEmitter(), { id: 96, isDestroyed: () => false, getURL: () => url }) - registerMagicAgentTrustedRouteBinding(96, route, { trustedUrl: url, trustedWebContents: sender as never }) + sender = Object.assign(new EventEmitter(), { + id: 96, + isDestroyed: () => false, + getURL: () => url + }) + registerMagicAgentTrustedRouteBinding(96, route, { + trustedUrl: url, + trustedWebContents: sender as never + }) h.fromId.mockReturnValue(sender) h.parent.mockReturnValue({ isDestroyed: () => false, webContents: sender }) store = new AssistantSessionStore(path.join(h.data, 'sessions.json')) - h.runtime = new AssistantRuntime({ sessionStore: store, configProvider: getConfig, chatService: { chat: vi.fn() } }) + h.runtime = new AssistantRuntime({ + sessionStore: store, + configProvider: getConfig, + chatService: { chat: vi.fn() } + }) // Install after the runtime/proxy cycle has evaluated. An async partial mock's // importOriginal can let the proxy capture the real singleton during that cycle. vi.spyOn(runtimeModule, 'getAssistantRuntime').mockReturnValue(h.runtime) @@ -72,7 +137,10 @@ beforeEach(async () => { afterEach(async () => { sender?.emit('did-start-navigation') closeAssistantTerminalPolicyRuntime() - await service?.cancelConversation({ conversationId: scope.conversationId }, invoke('cancelConversation')) + await service?.cancelConversation( + { conversationId: scope.conversationId }, + invoke('cancelConversation') + ) await h.runtime?.flush() await stopMcpClientManager() await stopMagicPotMcpPlatformRuntime() @@ -87,20 +155,31 @@ afterEach(async () => { describe('file edit via existing thread, actual runtime/kernel/registry/host and formal approval (model/window stubs)', () => { it.each( - (['chat', 'chatStream'] as const).flatMap(method => - [false, true].flatMap(native => - (['ask_user', 'show_card'] as const).flatMap(name => - [false, true].flatMap(alias => - (name === 'show_card' ? [false, true] : [false]).flatMap(withFields => - (name === 'show_card' ? [false, true] : [false]).flatMap(withSubtitle => - (name === 'show_card' ? [1, 2] : [0]).flatMap(actionCount => - (name === 'show_card' ? [false, true] : [false]).flatMap(withFooter => - (name === 'show_card' ? [false, true] : [false]).flatMap(withAccent => - (name === 'show_card' ? [false, true] : [false]).flatMap(withActionStyle => - (name === 'show_card' ? [false, true] : [false]).flatMap(withIcon => - (name === 'show_card' ? [false, true] : [false]).map(withBody => - ({ method, native, name, alias, withFields, withSubtitle, actionCount, withFooter, withAccent, withActionStyle, withIcon, withBody }) - ) + (['chat', 'chatStream'] as const).flatMap((method) => + [false, true].flatMap((native) => + (['ask_user', 'show_card'] as const).flatMap((name) => + [false, true].flatMap((alias) => + (name === 'show_card' ? [false, true] : [false]).flatMap((withFields) => + (name === 'show_card' ? [false, true] : [false]).flatMap((withSubtitle) => + (name === 'show_card' ? [1, 2] : [0]).flatMap((actionCount) => + (name === 'show_card' ? [false, true] : [false]).flatMap((withFooter) => + (name === 'show_card' ? [false, true] : [false]).flatMap((withAccent) => + (name === 'show_card' ? [false, true] : [false]).flatMap((withActionStyle) => + (name === 'show_card' ? [false, true] : [false]).flatMap((withIcon) => + (name === 'show_card' ? [false, true] : [false]).map((withBody) => ({ + method, + native, + name, + alias, + withFields, + withSubtitle, + actionCount, + withFooter, + withAccent, + withActionStyle, + withIcon, + withBody + })) ) ) ) @@ -113,86 +192,270 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and ) ) )( - 'reads an interaction manual passively, still waits for $method native=$native tool=$name timeout_s=$alias fields=$withFields subtitle=$withSubtitle actions=$actionCount footer=$withFooter accent=$withAccent style=$withActionStyle icon=$withIcon body=$withBody and never turns its answer into edit approval', async ({ method, native, name, alias, withFields, withSubtitle, actionCount, withFooter, withAccent, withActionStyle, withIcon, withBody }) => { - const before = 'original\n', file = path.join(root, 'interaction-feedback-not-approval.txt') + 'reads an interaction manual passively, still waits for $method native=$native tool=$name timeout_s=$alias fields=$withFields subtitle=$withSubtitle actions=$actionCount footer=$withFooter accent=$withAccent style=$withActionStyle icon=$withIcon body=$withBody and never turns its answer into edit approval', + async ({ + method, + native, + name, + alias, + withFields, + withSubtitle, + actionCount, + withFooter, + withAccent, + withActionStyle, + withIcon, + withBody + }) => { + const before = 'original\n', + file = path.join(root, 'interaction-feedback-not-approval.txt') await fs.writeFile(file, before) - const edit = { path: 'interaction-feedback-not-approval.txt', expectedSha256: hash(before), replacements: [{ old: 'original', new: 'changed', expectedOccurrences: 1 }] } - const fields = [{ label: 'Status', value: 'Read-only context, not authorization', inline: true }, { label: 'Next', value: 'A file edit requires separate formal approval', inline: false }] - const body = '**Review only**\n\nBearer a**RAW_PROXY_SUFFIX**\n\n[Not authorization](https://external.invalid/no-open)\n\n- [x] No approval' - const input = { ...(name === 'ask_user' ? { question: 'Reply for conversation only; not edit authorization.' } : { title: 'Conversation feedback only', ...(withBody ? { body } : {}), ...(withIcon ? { icon: '✓👩🏽‍💻' } : {}), actions: [{ id: 'approve', label: 'Feedback yes (not authorization)', ...(withActionStyle ? { style: 'primary' } : {}) }, { id: 'no', label: 'Feedback no', ...(withActionStyle ? { style: 'danger' } : {}) }].slice(0, actionCount) }), ...(alias ? { timeout_s: 17 } : {}), ...(withFields ? { fields } : {}), ...(withSubtitle ? { subtitle: 'Smaller context, never authorization for this edit' } : {}), ...(withFooter ? { footer: 'Closing context, never authorization for this edit' } : {}), ...(withAccent ? { accent: 'success' } : {}) } - const answer = name === 'ask_user' ? { status: 'answered' as const, text: 'approve' } : { status: 'answered' as const, actionId: 'approve' } - const script = [{ name: 'info', args: { name } }, { name, args: input }, { name: 'files.edit', args: edit }] - const policy = getAssistantTerminalPolicyRuntime(), runtimeCalls = vi.spyOn(h.runtime!, 'callTool') + const edit = { + path: 'interaction-feedback-not-approval.txt', + expectedSha256: hash(before), + replacements: [{ old: 'original', new: 'changed', expectedOccurrences: 1 }] + } + const fields = [ + { label: 'Status', value: 'Read-only context, not authorization', inline: true }, + { label: 'Next', value: 'A file edit requires separate formal approval', inline: false } + ] + const body = + '**Review only**\n\nBearer a**RAW_PROXY_SUFFIX**\n\n[Not authorization](https://external.invalid/no-open)\n\n- [x] No approval' + const input = { + ...(name === 'ask_user' + ? { question: 'Reply for conversation only; not edit authorization.' } + : { + title: 'Conversation feedback only', + ...(withBody ? { body } : {}), + ...(withIcon ? { icon: '✓👩🏽‍💻' } : {}), + actions: [ + { + id: 'approve', + label: 'Feedback yes (not authorization)', + ...(withActionStyle ? { style: 'primary' } : {}) + }, + { id: 'no', label: 'Feedback no', ...(withActionStyle ? { style: 'danger' } : {}) } + ].slice(0, actionCount) + }), + ...(alias ? { timeout_s: 17 } : {}), + ...(withFields ? { fields } : {}), + ...(withSubtitle ? { subtitle: 'Smaller context, never authorization for this edit' } : {}), + ...(withFooter ? { footer: 'Closing context, never authorization for this edit' } : {}), + ...(withAccent ? { accent: 'success' } : {}) + } + const answer = + name === 'ask_user' + ? { status: 'answered' as const, text: 'approve' } + : { status: 'answered' as const, actionId: 'approve' } + const script = [ + { name: 'info', args: { name } }, + { name, args: input }, + { name: 'files.edit', args: edit } + ] + const policy = getAssistantTerminalPolicyRuntime(), + runtimeCalls = vi.spyOn(h.runtime!, 'callTool') const chat = vi.fn(async (params: LLMChatParams): Promise => { const step = chat.mock.calls.length - 1 expect(step).toBeLessThan(3) expect(await fs.readFile(file, 'utf8')).toBe(before) expect(policy.listPendingTerminalApprovals()).toEqual([]) - expect((await service.listAgentInteractions(scope, invoke('listAgentInteractions'))).interactions).toEqual([]) - expect(await fs.stat(path.join(root, '.magicpot', 'tool-host', 'snapshots')).then(() => true, () => false)).toBe(false) + expect( + (await service.listAgentInteractions(scope, invoke('listAgentInteractions'))).interactions + ).toEqual([]) + expect( + await fs.stat(path.join(root, '.magicpot', 'tool-host', 'snapshots')).then( + () => true, + () => false + ) + ).toBe(false) if (step > 0) { - const raw = String(native ? params.toolTurns?.at(-1)?.results[0]?.output : params.messages.at(-1)?.content) + const raw = String( + native ? params.toolTurns?.at(-1)?.results[0]?.output : params.messages.at(-1)?.content + ) if (!native) expect(raw).toMatch(/^\[Tool Result\]\ntoolName: /) const output = JSON.parse(native ? raw : raw.slice(raw.indexOf('\n\n') + 2)) - if (step === 1) expect(output).toMatchObject({ name, grantsPermission: false, documentation: { contract: 'magicpot-local-interaction-manual/v1', name, documentationOnly: true, grantsPermission: false, authority: { readingUnlocksTool: false, answersGrantPermission: false }, ...(alias ? { timeout: { alias: 'timeout_s', mutuallyExclusive: true } } : {}) } }) + if (step === 1) + expect(output).toMatchObject({ + name, + grantsPermission: false, + documentation: { + contract: 'magicpot-local-interaction-manual/v1', + name, + documentationOnly: true, + grantsPermission: false, + authority: { readingUnlocksTool: false, answersGrantPermission: false }, + ...(alias ? { timeout: { alias: 'timeout_s', mutuallyExclusive: true } } : {}) + } + }) else expect(output).toEqual(answer) if (step === 1 && withBody) { expect(output.documentation.behavior.bodyMarkdown).toContain('formatting-only Markdown') - expect(output.documentation.behavior.bodyMarkdown).toContain('no links, no images, no task controls') - expect(Buffer.byteLength(JSON.stringify(output.documentation), 'utf8')).toBeLessThan(10000) + expect(output.documentation.behavior.bodyMarkdown).toContain( + 'no links, no images, no task controls' + ) + expect(Buffer.byteLength(JSON.stringify(output.documentation), 'utf8')).toBeLessThan( + 10000 + ) } if (step === 1 && withIcon) { - expect(output.documentation.limits).toMatchObject({ iconSchemaCharacters: 64, iconUtf16Units: 64 }) + expect(output.documentation.limits).toMatchObject({ + iconSchemaCharacters: 64, + iconUtf16Units: 64 + }) expect(output.documentation.behavior.historyDisplay).toContain('decorative') - expect(output.documentation.behavior.choices).toContain('No field values, footer, accent, icon or permission extras') + expect(output.documentation.behavior.choices).toContain( + 'No field values, footer, accent, icon or permission extras' + ) } if (step === 1 && withActionStyle) { - expect(output.documentation.limits).toMatchObject({ actionStyles: ['primary', 'secondary', 'danger'] }) + expect(output.documentation.limits).toMatchObject({ + actionStyles: ['primary', 'secondary', 'danger'] + }) expect(output.documentation.behavior.choices).toContain('never approval') } if (step === 1 && withAccent) { - expect(output.documentation.limits).toMatchObject({ accents: ['primary', 'info', 'success', 'warning', 'danger', 'neutral'] }) - expect(output.documentation.behavior.input).toContain('never means business success, tool outcome') + expect(output.documentation.limits).toMatchObject({ + accents: ['primary', 'info', 'success', 'warning', 'danger', 'neutral'] + }) + expect(output.documentation.behavior.input).toContain( + 'never means business success, tool outcome' + ) } if (step === 1 && withFooter) { - expect(output.documentation.limits).toMatchObject({ footerSchemaCharacters: 200, footerUtf16Units: 200 }) - expect(output.documentation.behavior.input).toContain('read-only context, never an input value or answer') + expect(output.documentation.limits).toMatchObject({ + footerSchemaCharacters: 200, + footerUtf16Units: 200 + }) + expect(output.documentation.behavior.input).toContain( + 'read-only context, never an input value or answer' + ) } if (step === 1 && actionCount === 1) { - expect(output.documentation.limits).toMatchObject({ minimumInteractiveActions: 1, maximumActions: 4 }) - expect(output.documentation.behavior.choices).toContain('One action still waits for an explicit click') + expect(output.documentation.limits).toMatchObject({ + minimumInteractiveActions: 1, + maximumActions: 4 + }) + expect(output.documentation.behavior.choices).toContain( + 'One action still waits for an explicit click' + ) } } const call = script[step] if (!native) return JSON.stringify({ toolName: call.name, args: call.args }) - const index = params.tools!.findIndex(tool => tool.name === call.name) + const index = params.tools!.findIndex((tool) => tool.name === call.name) expect(index).toBeGreaterThanOrEqual(0) - if (alias && step === 1) expect(params.tools!.at(index)!.inputSchema).toMatchObject({ properties: { timeout_s: { type: 'integer', minimum: 1, maximum: 600 } } }) - if (withBody && step === 1) expect(params.tools!.at(index)!.inputSchema).toMatchObject({ properties: { body: { type: 'string', maxLength: 4000 } } }) - if (withIcon && step === 1) expect(params.tools!.at(index)!.inputSchema).toMatchObject({ properties: { icon: { type: 'string', maxLength: 64 } } }) - if (withActionStyle && step === 1) expect(params.tools!.at(index)!.inputSchema).toMatchObject({ properties: { actions: { items: { properties: { style: { type: 'string', enum: ['primary', 'secondary', 'danger'] } } } } } }) - if (withAccent && step === 1) expect(params.tools!.at(index)!.inputSchema).toMatchObject({ properties: { accent: { type: 'string', enum: ['primary', 'info', 'success', 'warning', 'danger', 'neutral'] } } }) - if (withFooter && step === 1) expect(params.tools!.at(index)!.inputSchema).toMatchObject({ properties: { footer: { type: 'string', maxLength: 200 } } }) - if (withSubtitle && step === 1) expect(params.tools!.at(index)!.inputSchema).toMatchObject({ properties: { subtitle: { type: 'string', maxLength: 200 } } }) - if (withFields && step === 1) expect(params.tools!.at(index)!.inputSchema).toMatchObject({ properties: { fields: { type: 'array', maxItems: 8, items: { required: ['label', 'value'] } } } }) - return { content: '', toolCalls: [{ id: `manual-feedback-${step}`, name: call.name, wireName: `mp_tool_${index}`, arguments: JSON.stringify(call.args) }] } + if (alias && step === 1) + expect(params.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { timeout_s: { type: 'integer', minimum: 1, maximum: 600 } } + }) + if (withBody && step === 1) + expect(params.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { body: { type: 'string', maxLength: 4000 } } + }) + if (withIcon && step === 1) + expect(params.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { icon: { type: 'string', maxLength: 64 } } + }) + if (withActionStyle && step === 1) + expect(params.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { + actions: { + items: { + properties: { + style: { type: 'string', enum: ['primary', 'secondary', 'danger'] } + } + } + } + } + }) + if (withAccent && step === 1) + expect(params.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { + accent: { + type: 'string', + enum: ['primary', 'info', 'success', 'warning', 'danger', 'neutral'] + } + } + }) + if (withFooter && step === 1) + expect(params.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { footer: { type: 'string', maxLength: 200 } } + }) + if (withSubtitle && step === 1) + expect(params.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { subtitle: { type: 'string', maxLength: 200 } } + }) + if (withFields && step === 1) + expect(params.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { + fields: { type: 'array', maxItems: 8, items: { required: ['label', 'value'] } } + } + }) + return { + content: '', + toolCalls: [ + { + id: `manual-feedback-${step}`, + name: call.name, + wireName: `mp_tool_${index}`, + arguments: JSON.stringify(call.args) + } + ] + } }) vi.mocked(cliFromProfile).mockReturnValue({ chat, supportsNativeTools: native } as never) - const onData = vi.fn<(event: LLMChatStreamResp) => void>(), request: LLMChatReq = { ...scope, profileId: 'agent-profile', messages: [{ role: 'user', content: 'Read the local interaction manual, collect conversational feedback, then submit the exact edit for separate formal approval.' }] } - const pending = (method === 'chat' ? service.chat(request, invoke(method)) : service.chatStream(request, { onData }, invoke(method))).then(value => ({ status: 'fulfilled' as const, value }), (reason: unknown) => ({ status: 'rejected' as const, reason })) + const onData = vi.fn<(event: LLMChatStreamResp) => void>(), + request: LLMChatReq = { + ...scope, + profileId: 'agent-profile', + messages: [ + { + role: 'user', + content: + 'Read the local interaction manual, collect conversational feedback, then submit the exact edit for separate formal approval.' + } + ] + } + const pending = ( + method === 'chat' + ? service.chat(request, invoke(method)) + : service.chatStream(request, { onData }, invoke(method)) + ).then( + (value) => ({ status: 'fulfilled' as const, value }), + (reason: unknown) => ({ status: 'rejected' as const, reason }) + ) let promptId = '' const startedAt = Date.now() await vi.waitFor(async () => { - const prompts = (await service.listAgentInteractions(scope, invoke('listAgentInteractions'))).interactions + const prompts = ( + await service.listAgentInteractions(scope, invoke('listAgentInteractions')) + ).interactions expect(prompts).toHaveLength(1) expect(prompts[0].prompt.kind).toBe(name) - if (actionCount === 1) expect(prompts[0].prompt).toMatchObject({ kind: 'show_card', actions: [{ id: 'approve', label: 'Feedback yes (not authorization)' }] }) + if (actionCount === 1) + expect(prompts[0].prompt).toMatchObject({ + kind: 'show_card', + actions: [{ id: 'approve', label: 'Feedback yes (not authorization)' }] + }) if (withBody) expect(prompts[0].prompt).toMatchObject({ kind: 'show_card', body }) if (withIcon) expect(prompts[0].prompt).toMatchObject({ kind: 'show_card', icon: '✓👩🏽‍💻' }) - if (withActionStyle) expect(prompts[0].prompt).toMatchObject({ kind: 'show_card', actions: actionCount === 1 ? [{ id: 'approve', style: 'primary' }] : [{ id: 'approve', style: 'primary' }, { id: 'no', style: 'danger' }] }) - if (withAccent) expect(prompts[0].prompt).toMatchObject({ kind: 'show_card', accent: 'success' }) - if (withFooter) expect(prompts[0].prompt).toMatchObject({ kind: 'show_card', footer: input.footer }) - if (withSubtitle) expect(prompts[0].prompt).toMatchObject({ kind: 'show_card', subtitle: input.subtitle }) + if (withActionStyle) + expect(prompts[0].prompt).toMatchObject({ + kind: 'show_card', + actions: + actionCount === 1 + ? [{ id: 'approve', style: 'primary' }] + : [ + { id: 'approve', style: 'primary' }, + { id: 'no', style: 'danger' } + ] + }) + if (withAccent) + expect(prompts[0].prompt).toMatchObject({ kind: 'show_card', accent: 'success' }) + if (withFooter) + expect(prompts[0].prompt).toMatchObject({ kind: 'show_card', footer: input.footer }) + if (withSubtitle) + expect(prompts[0].prompt).toMatchObject({ kind: 'show_card', subtitle: input.subtitle }) if (withFields) expect(prompts[0].prompt).toMatchObject({ kind: 'show_card', fields }) if (alias) { expect(prompts[0].expiresAt).toBeGreaterThanOrEqual(startedAt + 17000) @@ -201,117 +464,402 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and promptId = prompts[0].id }) expect(chat).toHaveBeenCalledTimes(2) - expect(runtimeCalls.mock.calls.map(call => call[1])).toEqual(['info', name]) + expect(runtimeCalls.mock.calls.map((call) => call[1])).toEqual(['info', name]) expect(policy.listPendingTerminalApprovals()).toEqual([]) expect(await fs.readFile(file, 'utf8')).toBe(before) - if (withFields || withSubtitle || actionCount === 1 || withFooter || withAccent || withActionStyle || withIcon || withBody) { - await expect(service.resolveAgentInteraction({ ...scope, conversationId: 'foreign-conversation', interactionId: promptId, answer }, invoke('resolveAgentInteraction'))).rejects.toThrow('not active') - await expect(service.resolveAgentInteraction({ ...scope, interactionId: promptId, answer: { ...answer, values: { approved: true } } as never }, invoke('resolveAgentInteraction'))).rejects.toThrow('Invalid') - if (withBody) await expect(service.resolveAgentInteraction({ ...scope, interactionId: promptId, answer: { ...answer, body } as never }, invoke('resolveAgentInteraction'))).rejects.toThrow('Invalid') - if (withIcon) await expect(service.resolveAgentInteraction({ ...scope, interactionId: promptId, answer: { ...answer, icon: '✓' } as never }, invoke('resolveAgentInteraction'))).rejects.toThrow('Invalid') - if (withActionStyle) await expect(service.resolveAgentInteraction({ ...scope, interactionId: promptId, answer: { ...answer, style: 'primary' } as never }, invoke('resolveAgentInteraction'))).rejects.toThrow('Invalid') - if (withAccent) await expect(service.resolveAgentInteraction({ ...scope, interactionId: promptId, answer: { ...answer, accent: 'success' } as never }, invoke('resolveAgentInteraction'))).rejects.toThrow('Invalid') + if ( + withFields || + withSubtitle || + actionCount === 1 || + withFooter || + withAccent || + withActionStyle || + withIcon || + withBody + ) { + await expect( + service.resolveAgentInteraction( + { ...scope, conversationId: 'foreign-conversation', interactionId: promptId, answer }, + invoke('resolveAgentInteraction') + ) + ).rejects.toThrow('not active') + await expect( + service.resolveAgentInteraction( + { + ...scope, + interactionId: promptId, + answer: { ...answer, values: { approved: true } } as never + }, + invoke('resolveAgentInteraction') + ) + ).rejects.toThrow('Invalid') + if (withBody) + await expect( + service.resolveAgentInteraction( + { ...scope, interactionId: promptId, answer: { ...answer, body } as never }, + invoke('resolveAgentInteraction') + ) + ).rejects.toThrow('Invalid') + if (withIcon) + await expect( + service.resolveAgentInteraction( + { ...scope, interactionId: promptId, answer: { ...answer, icon: '✓' } as never }, + invoke('resolveAgentInteraction') + ) + ).rejects.toThrow('Invalid') + if (withActionStyle) + await expect( + service.resolveAgentInteraction( + { + ...scope, + interactionId: promptId, + answer: { ...answer, style: 'primary' } as never + }, + invoke('resolveAgentInteraction') + ) + ).rejects.toThrow('Invalid') + if (withAccent) + await expect( + service.resolveAgentInteraction( + { + ...scope, + interactionId: promptId, + answer: { ...answer, accent: 'success' } as never + }, + invoke('resolveAgentInteraction') + ) + ).rejects.toThrow('Invalid') expect(chat).toHaveBeenCalledTimes(2) expect(policy.listPendingTerminalApprovals()).toEqual([]) } - if (actionCount === 1) await expect(service.resolveAgentInteraction({ ...scope, interactionId: promptId, answer: { ...answer, approved: true } as never }, invoke('resolveAgentInteraction'))).rejects.toThrow('Invalid') - if (withFooter) await expect(service.resolveAgentInteraction({ ...scope, interactionId: promptId, answer: { ...answer, footer: input.footer } as never }, invoke('resolveAgentInteraction'))).rejects.toThrow('Invalid') - if (withSubtitle) await expect(service.resolveAgentInteraction({ ...scope, interactionId: promptId, answer: { ...answer, subtitle: input.subtitle } as never }, invoke('resolveAgentInteraction'))).rejects.toThrow('Invalid') - await service.resolveAgentInteraction({ ...scope, interactionId: promptId, answer }, invoke('resolveAgentInteraction')) - if (withFields || withSubtitle || actionCount === 1 || withFooter || withIcon || withBody) await expect(service.resolveAgentInteraction({ ...scope, interactionId: promptId, answer }, invoke('resolveAgentInteraction'))).rejects.toThrow('not active') + if (actionCount === 1) + await expect( + service.resolveAgentInteraction( + { ...scope, interactionId: promptId, answer: { ...answer, approved: true } as never }, + invoke('resolveAgentInteraction') + ) + ).rejects.toThrow('Invalid') + if (withFooter) + await expect( + service.resolveAgentInteraction( + { + ...scope, + interactionId: promptId, + answer: { ...answer, footer: input.footer } as never + }, + invoke('resolveAgentInteraction') + ) + ).rejects.toThrow('Invalid') + if (withSubtitle) + await expect( + service.resolveAgentInteraction( + { + ...scope, + interactionId: promptId, + answer: { ...answer, subtitle: input.subtitle } as never + }, + invoke('resolveAgentInteraction') + ) + ).rejects.toThrow('Invalid') + await service.resolveAgentInteraction( + { ...scope, interactionId: promptId, answer }, + invoke('resolveAgentInteraction') + ) + if (withFields || withSubtitle || actionCount === 1 || withFooter || withIcon || withBody) + await expect( + service.resolveAgentInteraction( + { ...scope, interactionId: promptId, answer }, + invoke('resolveAgentInteraction') + ) + ).rejects.toThrow('not active') await vi.waitFor(() => expect(policy.listPendingTerminalApprovals()).toHaveLength(1)) expect(chat).toHaveBeenCalledTimes(3) - expect(runtimeCalls.mock.calls.map(call => call[1])).toEqual(['info', name, 'files.edit']) - expect((await service.listAgentInteractions(scope, invoke('listAgentInteractions'))).interactions).toEqual([]) + expect(runtimeCalls.mock.calls.map((call) => call[1])).toEqual(['info', name, 'files.edit']) + expect( + (await service.listAgentInteractions(scope, invoke('listAgentInteractions'))).interactions + ).toEqual([]) expect(await fs.readFile(file, 'utf8')).toBe(before) const approval = policy.listPendingTerminalApprovals()[0] expect(approval.request.request.input).toEqual(edit) - policy.resolvePendingTerminalApproval({ approvalId: approval.approvalId, expectedRevision: approval.revision, approved: false }) + policy.resolvePendingTerminalApproval({ + approvalId: approval.approvalId, + expectedRevision: approval.revision, + approved: false + }) const outcome = await pending if (method === 'chat') expect(outcome.status).toBe('rejected') - else expect(onData.mock.calls.filter(([event]) => event.type === 'done')).toEqual([[expect.objectContaining({ finishReason: 'error' })]]) + else + expect(onData.mock.calls.filter(([event]) => event.type === 'done')).toEqual([ + [expect.objectContaining({ finishReason: 'error' })] + ]) expect(chat).toHaveBeenCalledTimes(3) expect(await fs.readFile(file, 'utf8')).toBe(before) expect(policy.listPendingTerminalApprovals()).toEqual([]) - expect(await fs.stat(path.join(root, '.magicpot', 'tool-host', 'snapshots')).then(() => true, () => false)).toBe(false) + expect( + await fs.stat(path.join(root, '.magicpot', 'tool-host', 'snapshots')).then( + () => true, + () => false + ) + ).toBe(false) await store.flush() const reopened = new AssistantSessionStore(path.join(h.data, 'sessions.json')) - const results = (await reopened.getSession(route))!.eventLog.map(event => event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined).filter(action => action?.type === 'tool.result') + const results = (await reopened.getSession(route))!.eventLog + .map( + (event) => + event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined + ) + .filter((action) => action?.type === 'tool.result') expect(results).toHaveLength(3) - expect(results[0]!.payload).toMatchObject({ ok: true, content: expect.stringContaining('magicpot-local-interaction-manual/v1') }) + expect(results[0]!.payload).toMatchObject({ + ok: true, + content: expect.stringContaining('magicpot-local-interaction-manual/v1') + }) expect(results[1]!.payload).toMatchObject({ ok: true, content: JSON.stringify(answer) }) expect(results[2]!.payload.ok).toBe(false) expect(h.fetch).not.toHaveBeenCalled() } ) - it.each((['chat', 'chatStream'] as const).flatMap(method => [false, true].flatMap(native => [false, true].flatMap(emptyActions => [false, true].flatMap(withFields => [false, true].flatMap(withSubtitle => [false, true].flatMap(withFooter => [false, true].flatMap(withAccent => [false, true].flatMap(withIcon => [false, true].map(withBody => [method, native, emptyActions, withFields, withSubtitle, withFooter, withAccent, withIcon, withBody] as const)))))))))) ( - 'provides a display-only card without input, effects or approval through %s native=%s emptyActions=%s fields=%s subtitle=%s footer=%s accent=%s icon=%s body=%s', async (method, native, emptyActions, withFields, withSubtitle, withFooter, withAccent, withIcon, withBody) => { - const before = 'This file must stay untouched.\n', file = path.join(root, 'card-no-edit.txt') + it.each( + (['chat', 'chatStream'] as const).flatMap((method) => + [false, true].flatMap((native) => + [false, true].flatMap((emptyActions) => + [false, true].flatMap((withFields) => + [false, true].flatMap((withSubtitle) => + [false, true].flatMap((withFooter) => + [false, true].flatMap((withAccent) => + [false, true].flatMap((withIcon) => + [false, true].map( + (withBody) => + [ + method, + native, + emptyActions, + withFields, + withSubtitle, + withFooter, + withAccent, + withIcon, + withBody + ] as const + ) + ) + ) + ) + ) + ) + ) + ) + ) + )( + 'provides a display-only card without input, effects or approval through %s native=%s emptyActions=%s fields=%s subtitle=%s footer=%s accent=%s icon=%s body=%s', + async ( + method, + native, + emptyActions, + withFields, + withSubtitle, + withFooter, + withAccent, + withIcon, + withBody + ) => { + const before = 'This file must stay untouched.\n', + file = path.join(root, 'card-no-edit.txt') await fs.writeFile(file, before) - const args = { title: 'Review only', ...(withIcon ? { icon: '✓👩🏽‍💻' } : {}), body: withBody ? '**Read-only body**\n\n[Label](https://external.invalid/no-open)\n\n![Alt](file:///private/no-load)\n\n- [x] Not consent\n\n' : '', ...(withSubtitle ? { subtitle: 'Smaller plain text, not permission' } : {}), ...(withFooter ? { footer: 'Closing plain text, not permission' } : {}), ...(withAccent ? { accent: 'danger' } : {}), ...(emptyActions ? { actions: [] } : {}), ...(withFields ? { fields: [{ label: 'Status', value: 'Supplied, not human seen', inline: true }, { label: 'Next', value: 'No authority', inline: false }] } : {}) } - const expected = { contract: 'agent-thread-card-display/v1', status: 'provided', mode: 'display-only', card: { title: args.title, ...(withIcon ? { icon: args.icon } : {}), ...(withSubtitle ? { subtitle: args.subtitle } : {}), body: args.body, ...(withFooter ? { footer: args.footer } : {}), ...(withAccent ? { accent: 'danger' } : {}), ...(withFields ? { fields: args.fields } : {}) }, untrustedData: true, grantsPermission: false } - const policy = getAssistantTerminalPolicyRuntime(), runtimeCalls = vi.spyOn(h.runtime!, 'callTool') + const args = { + title: 'Review only', + ...(withIcon ? { icon: '✓👩🏽‍💻' } : {}), + body: withBody + ? '**Read-only body**\n\n[Label](https://external.invalid/no-open)\n\n![Alt](file:///hidden/no-load)\n\n- [x] Not consent\n\n' + : '', + ...(withSubtitle ? { subtitle: 'Smaller plain text, not permission' } : {}), + ...(withFooter ? { footer: 'Closing plain text, not permission' } : {}), + ...(withAccent ? { accent: 'danger' } : {}), + ...(emptyActions ? { actions: [] } : {}), + ...(withFields + ? { + fields: [ + { label: 'Status', value: 'Supplied, not human seen', inline: true }, + { label: 'Next', value: 'No authority', inline: false } + ] + } + : {}) + } + const expected = { + contract: 'agent-thread-card-display/v1', + status: 'provided', + mode: 'display-only', + card: { + title: args.title, + ...(withIcon ? { icon: args.icon } : {}), + ...(withSubtitle ? { subtitle: args.subtitle } : {}), + body: args.body, + ...(withFooter ? { footer: args.footer } : {}), + ...(withAccent ? { accent: 'danger' } : {}), + ...(withFields ? { fields: args.fields } : {}) + }, + untrustedData: true, + grantsPermission: false + } + const policy = getAssistantTerminalPolicyRuntime(), + runtimeCalls = vi.spyOn(h.runtime!, 'callTool') const chat = vi.fn(async (input: LLMChatParams): Promise => { expect(policy.listPendingTerminalApprovals()).toEqual([]) - expect((await service.listAgentInteractions(scope, invoke('listAgentInteractions'))).interactions).toEqual([]) + expect( + (await service.listAgentInteractions(scope, invoke('listAgentInteractions'))).interactions + ).toEqual([]) if (chat.mock.calls.length === 1) { if (!native) return JSON.stringify({ toolName: 'show_card', args }) - const index = input.tools!.findIndex(tool => tool.name === 'show_card') + const index = input.tools!.findIndex((tool) => tool.name === 'show_card') expect(index).toBeGreaterThanOrEqual(0) - if (withBody) { expect(input.tools!.at(index)!.description).toContain('formatting-only Markdown body'); expect(input.tools!.at(index)!.inputSchema).toMatchObject({ properties: { body: { type: 'string', maxLength: 4000 } } }) } - if (withIcon) expect(input.tools!.at(index)!.inputSchema).toMatchObject({ properties: { icon: { type: 'string', maxLength: 64 } } }) - if (withAccent) expect(input.tools!.at(index)!.inputSchema).toMatchObject({ properties: { accent: { type: 'string', enum: ['primary', 'info', 'success', 'warning', 'danger', 'neutral'] } } }) - if (withFooter) expect(input.tools!.at(index)!.inputSchema).toMatchObject({ properties: { footer: { type: 'string', maxLength: 200 } } }) - if (withSubtitle) expect(input.tools!.at(index)!.inputSchema).toMatchObject({ properties: { subtitle: { type: 'string', maxLength: 200 } } }) - if (withFields) expect(input.tools!.at(index)!.inputSchema).toMatchObject({ properties: { fields: { type: 'array', maxItems: 8, items: { required: ['label', 'value'], additionalProperties: false } } } }) - return { content: '', toolCalls: [{ id: 'provided-card-call', name: 'show_card', wireName: `mp_tool_${index}`, arguments: JSON.stringify(args) }] } + if (withBody) { + expect(input.tools!.at(index)!.description).toContain('formatting-only Markdown body') + expect(input.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { body: { type: 'string', maxLength: 4000 } } + }) + } + if (withIcon) + expect(input.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { icon: { type: 'string', maxLength: 64 } } + }) + if (withAccent) + expect(input.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { + accent: { + type: 'string', + enum: ['primary', 'info', 'success', 'warning', 'danger', 'neutral'] + } + } + }) + if (withFooter) + expect(input.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { footer: { type: 'string', maxLength: 200 } } + }) + if (withSubtitle) + expect(input.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { subtitle: { type: 'string', maxLength: 200 } } + }) + if (withFields) + expect(input.tools!.at(index)!.inputSchema).toMatchObject({ + properties: { + fields: { + type: 'array', + maxItems: 8, + items: { required: ['label', 'value'], additionalProperties: false } + } + } + }) + return { + content: '', + toolCalls: [ + { + id: 'provided-card-call', + name: 'show_card', + wireName: `mp_tool_${index}`, + arguments: JSON.stringify(args) + } + ] + } } expect(chat.mock.calls.length).toBe(2) - const raw = String(native ? input.toolTurns?.at(-1)?.results[0]?.output : input.messages.at(-1)?.content) + const raw = String( + native ? input.toolTurns?.at(-1)?.results[0]?.output : input.messages.at(-1)?.content + ) if (!native) expect(raw).toMatch(/^\[Tool Result\]\ntoolName: show_card\nargs:\n/) expect(JSON.parse(native ? raw : raw.slice(raw.indexOf('\n\n') + 2))).toEqual(expected) - return { content: 'Read-only card content was provided; no answer or approval was collected.', finishReason: 'stop' } + return { + content: 'Read-only card content was provided; no answer or approval was collected.', + finishReason: 'stop' + } }) vi.mocked(cliFromProfile).mockReturnValue({ chat, supportsNativeTools: native } as never) - const request: LLMChatReq = { ...scope, profileId: 'agent-profile', messages: [{ role: 'user', content: 'Provide a read-only status card; do not ask for a choice or change any file.' }] }, onData = vi.fn<(event: LLMChatStreamResp) => void>() + const request: LLMChatReq = { + ...scope, + profileId: 'agent-profile', + messages: [ + { + role: 'user', + content: + 'Provide a read-only status card; do not ask for a choice or change any file.' + } + ] + }, + onData = vi.fn<(event: LLMChatStreamResp) => void>() let history: import('@shared/llm/types').ToolHistoryEntry[] if (method === 'chat') { const value = await service.chat(request, invoke(method)) history = value.metadata!.toolHistory as typeof history } else { await service.chatStream(request, { onData }, invoke(method)) - const terminals = onData.mock.calls.map(([event]) => event).filter(event => event.type === 'done') + const terminals = onData.mock.calls + .map(([event]) => event) + .filter((event) => event.type === 'done') expect(terminals).toHaveLength(1) expect(terminals[0].finishReason).toBe('stop') history = terminals[0].metadata!.toolHistory as typeof history } expect(chat).toHaveBeenCalledTimes(2) - expect(runtimeCalls.mock.calls.map(call => call[1])).toEqual(['show_card']) + expect(runtimeCalls.mock.calls.map((call) => call[1])).toEqual(['show_card']) expect(history!).toHaveLength(1) - expect(history![0]).toMatchObject({ toolName: 'show_card', status: 'completed', args, content: JSON.stringify(expected) }) + expect(history![0]).toMatchObject({ + toolName: 'show_card', + status: 'completed', + args, + content: JSON.stringify(expected) + }) expect(history![0]).not.toHaveProperty('error') - expect((await service.listAgentInteractions(scope, invoke('listAgentInteractions'))).interactions).toEqual([]) + expect( + (await service.listAgentInteractions(scope, invoke('listAgentInteractions'))).interactions + ).toEqual([]) expect(policy.listPendingTerminalApprovals()).toEqual([]) expect(await fs.readFile(file, 'utf8')).toBe(before) - expect(await fs.stat(path.join(root, '.magicpot', 'tool-host', 'snapshots')).then(() => true, () => false)).toBe(false) - const actions = (await store.getSession(route))!.eventLog.map(event => event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined).filter(action => action?.type === 'tool.result') + expect( + await fs.stat(path.join(root, '.magicpot', 'tool-host', 'snapshots')).then( + () => true, + () => false + ) + ).toBe(false) + const actions = (await store.getSession(route))!.eventLog + .map( + (event) => + event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined + ) + .filter((action) => action?.type === 'tool.result') expect(actions).toHaveLength(1) expect(actions[0]!.payload).toMatchObject({ ok: true, content: JSON.stringify(expected) }) await store.flush() const reopened = new AssistantSessionStore(path.join(h.data, 'sessions.json')) - const retained = (await reopened.getSession(route))!.eventLog.map(event => event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined).find(action => action?.type === 'tool.result') + const retained = (await reopened.getSession(route))!.eventLog + .map( + (event) => + event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined + ) + .find((action) => action?.type === 'tool.result') expect(retained!.payload).toMatchObject({ ok: true, content: JSON.stringify(expected) }) expect(h.fetch).not.toHaveBeenCalled() } ) - it.each((['chat', 'chatStream'] as const).flatMap(method => [false, true].flatMap(native => ['approve', 'deny'].map(decision => [method, native, decision] as const))))( - 'reads local mutation manuals without approval/effects before %s native=%s decision=%s', async (method, native, decision) => { - const before = 'a b a\n', file = path.join(root, 'manual-then-edit.txt') + it.each( + (['chat', 'chatStream'] as const).flatMap((method) => + [false, true].flatMap((native) => + ['approve', 'deny'].map((decision) => [method, native, decision] as const) + ) + ) + )( + 'reads local mutation manuals without approval/effects before %s native=%s decision=%s', + async (method, native, decision) => { + const before = 'a b a\n', + file = path.join(root, 'manual-then-edit.txt') await fs.writeFile(file, before) - const edit = { path: 'manual-then-edit.txt', expectedSha256: hash(before), replacements: [{ old: 'a', new: 'A', expectedOccurrences: 2 }] } - const policy = getAssistantTerminalPolicyRuntime(), runtimeCalls = vi.spyOn(h.runtime!, 'callTool') + const edit = { + path: 'manual-then-edit.txt', + expectedSha256: hash(before), + replacements: [{ old: 'a', new: 'A', expectedOccurrences: 2 }] + } + const policy = getAssistantTerminalPolicyRuntime(), + runtimeCalls = vi.spyOn(h.runtime!, 'callTool') const script: Array<{ name: string; args: Record }> = [ { name: 'info', args: { name: 'files.edit' } }, { name: 'info', args: { kind: 'tool', name: 'files.patch' } }, @@ -323,154 +871,386 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and if (index <= 3) { expect(policy.listPendingTerminalApprovals()).toEqual([]) expect(await fs.readFile(file, 'utf8')).toBe(before) - expect(await fs.stat(path.join(root, '.magicpot', 'tool-host', 'snapshots')).then(() => true, () => false)).toBe(false) + expect( + await fs.stat(path.join(root, '.magicpot', 'tool-host', 'snapshots')).then( + () => true, + () => false + ) + ).toBe(false) if (index > 0) { - const previous = native ? input.toolTurns?.at(-1)?.results[0]?.output : input.messages.at(-1)?.content + const previous = native + ? input.toolTurns?.at(-1)?.results[0]?.output + : input.messages.at(-1)?.content expect(typeof previous).toBe('string') const raw = String(previous) if (!native) expect(raw).toMatch(/^\[Tool Result\]\ntoolName: info\nargs:\n/) const manual = JSON.parse(native ? raw : raw.slice(raw.indexOf('\n\n') + 2)) - expect(manual).toMatchObject({ name: script[index - 1].args.name, grantsPermission: false, documentation: { - contract: 'magicpot-local-file-mutation-manual/v1', name: script[index - 1].args.name, - documentationOnly: true, grantsPermission: false, authority: { readingUnlocksTool: false, requiresFreshApproval: true }, failure: { automaticRetry: false } - } }) + expect(manual).toMatchObject({ + name: script[index - 1].args.name, + grantsPermission: false, + documentation: { + contract: 'magicpot-local-file-mutation-manual/v1', + name: script[index - 1].args.name, + documentationOnly: true, + grantsPermission: false, + authority: { readingUnlocksTool: false, requiresFreshApproval: true }, + failure: { automaticRetry: false } + } + }) } const call = script[index] if (!native) return JSON.stringify({ toolName: call.name, args: call.args }) - const wire = input.tools!.findIndex(tool => tool.name === call.name) + const wire = input.tools!.findIndex((tool) => tool.name === call.name) expect(wire).toBeGreaterThanOrEqual(0) - return { content: '', toolCalls: [{ id: `manual-first-${index}`, name: call.name, wireName: `mp_tool_${wire}`, arguments: JSON.stringify(call.args) }] } + return { + content: '', + toolCalls: [ + { + id: `manual-first-${index}`, + name: call.name, + wireName: `mp_tool_${wire}`, + arguments: JSON.stringify(call.args) + } + ] + } } expect(decision).toBe('approve') return { content: 'The separately approved edit completed.', finishReason: 'stop' } }) vi.mocked(cliFromProfile).mockReturnValue({ chat, supportsNativeTools: native } as never) - const onData = vi.fn<(event: LLMChatStreamResp) => void>(), request: LLMChatReq = { ...scope, profileId: 'agent-profile', messages: [{ role: 'user', content: 'Read current local edit manuals first; then submit the exact edit for separate approval.' }] } - const pending = (method === 'chat' ? service.chat(request, invoke(method)) : service.chatStream(request, { onData }, invoke(method))).then(value => ({ status: 'fulfilled' as const, value }), (reason: unknown) => ({ status: 'rejected' as const, reason })) + const onData = vi.fn<(event: LLMChatStreamResp) => void>(), + request: LLMChatReq = { + ...scope, + profileId: 'agent-profile', + messages: [ + { + role: 'user', + content: + 'Read current local edit manuals first; then submit the exact edit for separate approval.' + } + ] + } + const pending = ( + method === 'chat' + ? service.chat(request, invoke(method)) + : service.chatStream(request, { onData }, invoke(method)) + ).then( + (value) => ({ status: 'fulfilled' as const, value }), + (reason: unknown) => ({ status: 'rejected' as const, reason }) + ) await vi.waitFor(() => expect(policy.listPendingTerminalApprovals()).toHaveLength(1)) - expect(runtimeCalls.mock.calls.map(call => call[1])).toEqual(['info', 'info', 'info', 'files.edit']) + expect(runtimeCalls.mock.calls.map((call) => call[1])).toEqual([ + 'info', + 'info', + 'info', + 'files.edit' + ]) expect(await fs.readFile(file, 'utf8')).toBe(before) const approval = policy.listPendingTerminalApprovals()[0] expect(approval.request.request.input).toEqual(edit) - policy.resolvePendingTerminalApproval({ approvalId: approval.approvalId, expectedRevision: approval.revision, approved: decision === 'approve' }) + policy.resolvePendingTerminalApproval({ + approvalId: approval.approvalId, + expectedRevision: approval.revision, + approved: decision === 'approve' + }) const outcome = await pending expect(chat).toHaveBeenCalledTimes(decision === 'approve' ? 5 : 4) expect(await fs.readFile(file, 'utf8')).toBe(decision === 'approve' ? 'A b A\n' : before) expect(policy.listPendingTerminalApprovals()).toEqual([]) - const actions = (await store.getSession(route))!.eventLog.map(event => event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined).filter(action => action?.type === 'tool.result') + const actions = (await store.getSession(route))!.eventLog + .map( + (event) => + event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined + ) + .filter((action) => action?.type === 'tool.result') expect(actions).toHaveLength(4) - for (const action of actions.slice(0, 3)) expect(action!.payload).toMatchObject({ ok: true, content: expect.stringContaining('magicpot-local-file-mutation-manual/v1') }) + for (const action of actions.slice(0, 3)) + expect(action!.payload).toMatchObject({ + ok: true, + content: expect.stringContaining('magicpot-local-file-mutation-manual/v1') + }) expect(actions[3]!.payload.ok).toBe(decision === 'approve') - if (method === 'chat') expect(outcome.status).toBe(decision === 'approve' ? 'fulfilled' : 'rejected') - else expect(onData.mock.calls.filter(([event]) => event.type === 'done')).toEqual([[expect.objectContaining({ finishReason: decision === 'approve' ? 'stop' : 'error' })]]) + if (method === 'chat') + expect(outcome.status).toBe(decision === 'approve' ? 'fulfilled' : 'rejected') + else + expect(onData.mock.calls.filter(([event]) => event.type === 'done')).toEqual([ + [expect.objectContaining({ finishReason: decision === 'approve' ? 'stop' : 'error' })] + ]) expect(h.fetch).not.toHaveBeenCalled() } ) - it.each((['chat', 'chatStream'] as const).flatMap(method => [false, true].flatMap(native => (['strict', 'partial', 'best_effort'] as const).flatMap(mode => (method === 'chat' ? ['main', 'ipc'] as const : ['main'] as const).map(transport => [method, native, mode, transport] as const)))))('same-file %s native=%s mode=%s transport=%s preserves actual bytes, failed terminal and reopened receipt', async (method, native, mode, transport) => { - const before = 'a b a\n', after = mode === 'strict' ? before : mode === 'partial' ? 'A b A\n' : 'Z b Z\n' - const file = path.join(root, 'mode.txt') - await fs.writeFile(file, before) - const args = { path: 'mode.txt', expectedSha256: hash(before), mode, replacements: [ - { old: 'a', new: 'A', expectedOccurrences: 2 }, - { old: 'not present', new: 'never', expectedOccurrences: 1 }, - { old: 'A', new: 'Z', expectedOccurrences: 2 } - ] } - const chat = vi.fn().mockImplementation(async input => { - expect(chat).toHaveBeenCalledTimes(1) - if (!native) return JSON.stringify({ toolName: 'files.edit', args }) - const index = input.tools.findIndex((tool: { name: string }) => tool.name === 'files.edit') - expect(index).toBeGreaterThanOrEqual(0) - return { content: '', toolCalls: [ - { id: 'same-file-mode-call', name: 'files.edit', wireName: `mp_tool_${index}`, arguments: JSON.stringify(args) }, - { id: 'unstarted-same-file-call', name: 'files.edit', wireName: `mp_tool_${index}`, arguments: JSON.stringify(args) } - ] } - }) - vi.mocked(cliFromProfile).mockReturnValue({ chat, supportsNativeTools: native } as never) - const req: LLMChatReq = { ...scope, profileId: 'agent-profile', messages: [{ role: 'user', content: 'Apply the reviewed ordered edit; keep any match failure visible.' }] } - const onData = vi.fn<(event: LLMChatStreamResp) => void>() - const policy = getAssistantTerminalPolicyRuntime() - let call: Promise - if (transport === 'ipc') { - type Api = { svcLLMProxy: { chat(req: LLMChatReq): Promise } } - const definition = { svcLLMProxy: { chat: llmProxySvcDef.chat } } - registerIpcServer(definition, { svcLLMProxy: service }) - const handler = h.handle.mock.calls.find(([name]) => name === 'svcLLMProxy.chat')![1] - h.invoke.mockImplementation(async (name, request) => { - expect(name).toBe('svcLLMProxy.chat') - try { return structuredClone(await handler({ sender, senderFrame: { url, parent: null } }, structuredClone(request))) } - catch (error) { throw new Error(error instanceof Error ? error.message : 'IPC handler failed') } - }) - call = createIpcClient(definition).svcLLMProxy.chat(req) - } else call = method === 'chat' ? service.chat(req, invoke(method)) : service.chatStream(req, { onData }, invoke(method)) - const pending = call.then(value => ({ status: 'fulfilled' as const, value }), (reason: unknown) => ({ status: 'rejected' as const, reason })) - await vi.waitFor(() => expect(policy.listPendingTerminalApprovals()).toHaveLength(1)) - const approval = policy.listPendingTerminalApprovals()[0] - expect(approval.request.request.input).toEqual(args) - expect(await fs.readFile(file, 'utf8')).toBe(before) - policy.resolvePendingTerminalApproval({ approvalId: approval.approvalId, expectedRevision: approval.revision, approved: true }) - const outcome = await pending - expect(policy.listPendingTerminalApprovals()).toEqual([]) - const expectedReport = { mode, failed: 1, applied: mode === 'best_effort' ? 2 : 1, skipped: mode === 'best_effort' ? 0 : 1, writeStatus: mode === 'strict' ? 'not-written' : 'committed', fileChanged: mode !== 'strict' } - if (method === 'chat') { - expect(outcome.status).toBe('rejected') - if (outcome.status === 'rejected') { - if (transport === 'main') expect(outcome.reason).toBeInstanceOf(IpcServiceError) - else { expect(outcome.reason).not.toBeInstanceOf(Error); expect(h.invoke).toHaveBeenCalledOnce() } - expect(outcome.reason).toMatchObject({ code: 'MAGIC_AGENT_FILES_EDIT_FAILED', payload: { kind: 'agent-tool-failure/v1', toolResult: { metadata: { report: expectedReport } }, toolHistory: [expect.objectContaining({ status: 'failed', toolName: 'files.edit' })] } }) - } - } else { - expect(outcome).toEqual({ status: 'fulfilled', value: undefined }) - const terminals = onData.mock.calls.map(([event]) => event).filter(event => event.type === 'error' || event.type === 'done') - expect(terminals.map(event => event.type)).toEqual(['error', 'done']) - for (const event of terminals) expect(event).toMatchObject({ finishReason: 'error', metadata: { toolHistory: [expect.objectContaining({ status: 'failed', toolName: 'files.edit', metadata: expect.objectContaining({ report: expect.objectContaining(expectedReport) }) })] } }) - } - const session = await store.getSession(route) - const actions = (session?.eventLog ?? []).map(event => event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined).filter(action => action?.type === 'tool.result') - expect(actions).toHaveLength(1) - const resultAction = actions[0]! - expect(resultAction.payload).toMatchObject({ ok: false, error: { code: 'MAGIC_AGENT_FILES_EDIT_FAILED' }, metadata: { report: expectedReport } }) - const content = resultAction.payload.content! - const receipt = JSON.parse(content) - expect(resultAction.payload.metadata).toEqual(receipt) - expect(await fs.readFile(file, 'utf8')).toBe(after) - if (mode === 'strict') { - expect(receipt).not.toHaveProperty('mutation') - await expect(fs.stat(path.join(root, '.magicpot'))).rejects.toMatchObject({ code: 'ENOENT' }) - } else { - const expectedDiff = `--- a/mode.txt\n+++ b/mode.txt\n@@ -1,1 +1,1 @@\n-${before}+${after}` - expect(receipt.mutation).toMatchObject({ beforeSha256: hash(before), afterSha256: hash(after), path: 'mode.txt', diff: expectedDiff, diffBytes: Buffer.byteLength(expectedDiff), additions: 1, deletions: 1 }) - expect(await fs.readFile(path.join(root, '.magicpot', 'tool-host', 'snapshots', receipt.mutation.snapshotId, 'content'), 'utf8')).toBe(before) + it.each( + (['chat', 'chatStream'] as const).flatMap((method) => + [false, true].flatMap((native) => + (['strict', 'partial', 'best_effort'] as const).flatMap((mode) => + (method === 'chat' ? (['main', 'ipc'] as const) : (['main'] as const)).map( + (transport) => [method, native, mode, transport] as const + ) + ) + ) + ) + )( + 'same-file %s native=%s mode=%s transport=%s preserves actual bytes, failed terminal and reopened receipt', + async (method, native, mode, transport) => { + const before = 'a b a\n', + after = mode === 'strict' ? before : mode === 'partial' ? 'A b A\n' : 'Z b Z\n' + const file = path.join(root, 'mode.txt') + await fs.writeFile(file, before) + const args = { + path: 'mode.txt', + expectedSha256: hash(before), + mode, + replacements: [ + { old: 'a', new: 'A', expectedOccurrences: 2 }, + { old: 'not present', new: 'never', expectedOccurrences: 1 }, + { old: 'A', new: 'Z', expectedOccurrences: 2 } + ] + } + const chat = vi.fn().mockImplementation(async (input) => { + expect(chat).toHaveBeenCalledTimes(1) + if (!native) return JSON.stringify({ toolName: 'files.edit', args }) + const index = input.tools.findIndex((tool: { name: string }) => tool.name === 'files.edit') + expect(index).toBeGreaterThanOrEqual(0) + return { + content: '', + toolCalls: [ + { + id: 'same-file-mode-call', + name: 'files.edit', + wireName: `mp_tool_${index}`, + arguments: JSON.stringify(args) + }, + { + id: 'unstarted-same-file-call', + name: 'files.edit', + wireName: `mp_tool_${index}`, + arguments: JSON.stringify(args) + } + ] + } + }) + vi.mocked(cliFromProfile).mockReturnValue({ chat, supportsNativeTools: native } as never) + const req: LLMChatReq = { + ...scope, + profileId: 'agent-profile', + messages: [ + { + role: 'user', + content: 'Apply the reviewed ordered edit; keep any match failure visible.' + } + ] + } + const onData = vi.fn<(event: LLMChatStreamResp) => void>() + const policy = getAssistantTerminalPolicyRuntime() + let call: Promise + if (transport === 'ipc') { + type Api = { svcLLMProxy: { chat(req: LLMChatReq): Promise } } + const definition = { svcLLMProxy: { chat: llmProxySvcDef.chat } } + registerIpcServer(definition, { svcLLMProxy: service }) + const handler = h.handle.mock.calls.find(([name]) => name === 'svcLLMProxy.chat')![1] + h.invoke.mockImplementation(async (name, request) => { + expect(name).toBe('svcLLMProxy.chat') + try { + return structuredClone( + await handler( + { sender, senderFrame: { url, parent: null } }, + structuredClone(request) + ) + ) + } catch (error) { + throw new Error(error instanceof Error ? error.message : 'IPC handler failed') + } + }) + call = createIpcClient(definition).svcLLMProxy.chat(req) + } else + call = + method === 'chat' + ? service.chat(req, invoke(method)) + : service.chatStream(req, { onData }, invoke(method)) + const pending = call.then( + (value) => ({ status: 'fulfilled' as const, value }), + (reason: unknown) => ({ status: 'rejected' as const, reason }) + ) + await vi.waitFor(() => expect(policy.listPendingTerminalApprovals()).toHaveLength(1)) + const approval = policy.listPendingTerminalApprovals()[0] + expect(approval.request.request.input).toEqual(args) + expect(await fs.readFile(file, 'utf8')).toBe(before) + policy.resolvePendingTerminalApproval({ + approvalId: approval.approvalId, + expectedRevision: approval.revision, + approved: true + }) + const outcome = await pending + expect(policy.listPendingTerminalApprovals()).toEqual([]) + const expectedReport = { + mode, + failed: 1, + applied: mode === 'best_effort' ? 2 : 1, + skipped: mode === 'best_effort' ? 0 : 1, + writeStatus: mode === 'strict' ? 'not-written' : 'committed', + fileChanged: mode !== 'strict' + } + if (method === 'chat') { + expect(outcome.status).toBe('rejected') + if (outcome.status === 'rejected') { + if (transport === 'main') expect(outcome.reason).toBeInstanceOf(IpcServiceError) + else { + expect(outcome.reason).not.toBeInstanceOf(Error) + expect(h.invoke).toHaveBeenCalledOnce() + } + expect(outcome.reason).toMatchObject({ + code: 'MAGIC_AGENT_FILES_EDIT_FAILED', + payload: { + kind: 'agent-tool-failure/v1', + toolResult: { metadata: { report: expectedReport } }, + toolHistory: [expect.objectContaining({ status: 'failed', toolName: 'files.edit' })] + } + }) + } + } else { + expect(outcome).toEqual({ status: 'fulfilled', value: undefined }) + const terminals = onData.mock.calls + .map(([event]) => event) + .filter((event) => event.type === 'error' || event.type === 'done') + expect(terminals.map((event) => event.type)).toEqual(['error', 'done']) + for (const event of terminals) + expect(event).toMatchObject({ + finishReason: 'error', + metadata: { + toolHistory: [ + expect.objectContaining({ + status: 'failed', + toolName: 'files.edit', + metadata: expect.objectContaining({ + report: expect.objectContaining(expectedReport) + }) + }) + ] + } + }) + } + const session = await store.getSession(route) + const actions = (session?.eventLog ?? []) + .map( + (event) => + event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined + ) + .filter((action) => action?.type === 'tool.result') + expect(actions).toHaveLength(1) + const resultAction = actions[0]! + expect(resultAction.payload).toMatchObject({ + ok: false, + error: { code: 'MAGIC_AGENT_FILES_EDIT_FAILED' }, + metadata: { report: expectedReport } + }) + const content = resultAction.payload.content! + const receipt = JSON.parse(content) + expect(resultAction.payload.metadata).toEqual(receipt) + expect(await fs.readFile(file, 'utf8')).toBe(after) + if (mode === 'strict') { + expect(receipt).not.toHaveProperty('mutation') + await expect(fs.stat(path.join(root, '.magicpot'))).rejects.toMatchObject({ + code: 'ENOENT' + }) + } else { + const expectedDiff = `--- a/mode.txt\n+++ b/mode.txt\n@@ -1,1 +1,1 @@\n-${before}+${after}` + expect(receipt.mutation).toMatchObject({ + beforeSha256: hash(before), + afterSha256: hash(after), + path: 'mode.txt', + diff: expectedDiff, + diffBytes: Buffer.byteLength(expectedDiff), + additions: 1, + deletions: 1 + }) + expect( + await fs.readFile( + path.join( + root, + '.magicpot', + 'tool-host', + 'snapshots', + receipt.mutation.snapshotId, + 'content' + ), + 'utf8' + ) + ).toBe(before) + } + expect(chat).toHaveBeenCalledOnce() + expect(h.fetch).not.toHaveBeenCalled() + await store.flush() + const reopenedStore = new AssistantSessionStore(path.join(h.data, 'sessions.json')) + const reopenedRuntime = new AssistantRuntime({ + sessionStore: reopenedStore, + configProvider: getConfig, + chatService: { chat: vi.fn() } + }) + await expect( + reopenedRuntime.callTool(route, 'files.edit', args, { + runId: resultAction.correlationId, + toolCallId: resultAction.payload.toolCallId, + allowedToolNames: ['files.edit'] + }) + ).rejects.toMatchObject({ + code: 'TOOL_EXECUTION_ALREADY_SETTLED', + toolResult: { content, metadata: receipt } + }) + expect((await reopenedStore.getSession(route))?.eventLog).toEqual(session!.eventLog) + expect(policy.listPendingTerminalApprovals()).toEqual([]) + expect(await fs.readFile(file, 'utf8')).toBe(after) + await reopenedRuntime.flush() } - expect(chat).toHaveBeenCalledOnce() - expect(h.fetch).not.toHaveBeenCalled() - await store.flush() - const reopenedStore = new AssistantSessionStore(path.join(h.data, 'sessions.json')) - const reopenedRuntime = new AssistantRuntime({ sessionStore: reopenedStore, configProvider: getConfig, chatService: { chat: vi.fn() } }) - await expect(reopenedRuntime.callTool(route, 'files.edit', args, { runId: resultAction.correlationId, toolCallId: resultAction.payload.toolCallId, allowedToolNames: ['files.edit'] })).rejects.toMatchObject({ code: 'TOOL_EXECUTION_ALREADY_SETTLED', toolResult: { content, metadata: receipt } }) - expect((await reopenedStore.getSession(route))?.eventLog).toEqual(session!.eventLog) - expect(policy.listPendingTerminalApprovals()).toEqual([]) - expect(await fs.readFile(file, 'utf8')).toBe(after) - await reopenedRuntime.flush() - }) + ) - it.each((['chat', 'chatStream'] as const).flatMap(method => (['strict', 'partial', 'best_effort'] as const).map(mode => [method, mode] as const)))( - 'bounded native failed-edit feedback via %s mode=%s explains once without success or more execution', async (method, mode) => { - const before = 'a b a\n', after = mode === 'strict' ? before : mode === 'partial' ? 'A b A\n' : 'Z b Z\n' + it.each( + (['chat', 'chatStream'] as const).flatMap((method) => + (['strict', 'partial', 'best_effort'] as const).map((mode) => [method, mode] as const) + ) + )( + 'bounded native failed-edit feedback via %s mode=%s explains once without success or more execution', + async (method, mode) => { + const before = 'a b a\n', + after = mode === 'strict' ? before : mode === 'partial' ? 'A b A\n' : 'Z b Z\n' const file = path.join(root, 'feedback.txt') await fs.writeFile(file, before) - const args = { path: 'feedback.txt', expectedSha256: hash(before), mode, replacements: [ - { old: 'a', new: 'A', expectedOccurrences: 2 }, - { old: 'not present', new: 'never', expectedOccurrences: 1 }, - { old: 'A', new: 'Z', expectedOccurrences: 2 } - ] } - const expectedReport = { mode, failed: 1, applied: mode === 'best_effort' ? 2 : 1, skipped: mode === 'best_effort' ? 0 : 1, writeStatus: mode === 'strict' ? 'not-written' : 'committed', fileChanged: mode !== 'strict' } - const explanation = 'The edit failed. Review the reported file state; no automatic retry was performed.' + const args = { + path: 'feedback.txt', + expectedSha256: hash(before), + mode, + replacements: [ + { old: 'a', new: 'A', expectedOccurrences: 2 }, + { old: 'not present', new: 'never', expectedOccurrences: 1 }, + { old: 'A', new: 'Z', expectedOccurrences: 2 } + ] + } + const expectedReport = { + mode, + failed: 1, + applied: mode === 'best_effort' ? 2 : 1, + skipped: mode === 'best_effort' ? 0 : 1, + writeStatus: mode === 'strict' ? 'not-written' : 'committed', + fileChanged: mode !== 'strict' + } + const explanation = + 'The edit failed. Review the reported file state; no automatic retry was performed.' const chat = vi.fn(async (input: LLMChatParams): Promise => { if (chat.mock.calls.length === 1) { - const index = input.tools!.findIndex(tool => tool.name === 'files.edit') + const index = input.tools!.findIndex((tool) => tool.name === 'files.edit') expect(index).toBeGreaterThanOrEqual(0) - return { content: '', usage: { promptTokens: 12, completionTokens: 3, totalTokens: 15 }, toolCalls: [{ id: 'native-failed-feedback', name: 'files.edit', wireName: `mp_tool_${index}`, arguments: JSON.stringify(args) }] } + return { + content: '', + usage: { promptTokens: 12, completionTokens: 3, totalTokens: 15 }, + toolCalls: [ + { + id: 'native-failed-feedback', + name: 'files.edit', + wireName: `mp_tool_${index}`, + arguments: JSON.stringify(args) + } + ] + } } expect(chat).toHaveBeenCalledTimes(2) expect(input.tools).toBeUndefined() @@ -482,27 +1262,64 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and expect(input.videoGenerationOptions).toBeUndefined() expect(input.imageGenerationOptions).toEqual({ enabled: false }) expect(input.onDelta).toBeUndefined() - expect(input.messages.every(message => !message.attachments?.length && !message.ocrResult && !message.hiddenContext)).toBe(true) + expect( + input.messages.every( + (message) => + !message.attachments?.length && !message.ocrResult && !message.hiddenContext + ) + ).toBe(true) const turns = input.toolTurns! expect(turns).toHaveLength(1) - expect(turns[0].calls.map(call => call.id)).toEqual(['native-failed-feedback']) - expect(turns[0].results.map(result => result.callId)).toEqual(['native-failed-feedback']) - expect(JSON.parse(turns[0].results[0].output)).toMatchObject({ error: { code: 'MAGIC_AGENT_FILES_EDIT_FAILED' }, report: expectedReport }) + expect(turns[0].calls.map((call) => call.id)).toEqual(['native-failed-feedback']) + expect(turns[0].results.map((result) => result.callId)).toEqual(['native-failed-feedback']) + expect(JSON.parse(turns[0].results[0].output)).toMatchObject({ + error: { code: 'MAGIC_AGENT_FILES_EDIT_FAILED' }, + report: expectedReport + }) expect(projectNativeToolTurns(turns, 'chat-completions')).toHaveLength(2) expect(projectNativeToolTurns(turns, 'responses')).toHaveLength(2) - return { content: explanation, finishReason: 'stop' as const, usage: { promptTokens: 20, completionTokens: 6, totalTokens: 26 } } + return { + content: explanation, + finishReason: 'stop' as const, + usage: { promptTokens: 20, completionTokens: 6, totalTokens: 26 } + } }) - vi.mocked(cliFromProfile).mockReturnValue({ chat, supportsNativeTools: true, supportsIsolatedReadOnlyTurns: true } as never) - const runtimeCalls = vi.spyOn(h.runtime!, 'callTool'), policy = getAssistantTerminalPolicyRuntime() - const req = { ...scope, profileId: 'agent-profile', messages: [{ role: 'user' as const, content: 'Apply the reviewed edit once; if a match fails, explain the actual reported failure without retrying.' }] } + vi.mocked(cliFromProfile).mockReturnValue({ + chat, + supportsNativeTools: true, + supportsIsolatedReadOnlyTurns: true + } as never) + const runtimeCalls = vi.spyOn(h.runtime!, 'callTool'), + policy = getAssistantTerminalPolicyRuntime() + const req = { + ...scope, + profileId: 'agent-profile', + messages: [ + { + role: 'user' as const, + content: + 'Apply the reviewed edit once; if a match fails, explain the actual reported failure without retrying.' + } + ] + } const onData = vi.fn<(event: LLMChatStreamResp) => void>() - const call = method === 'chat' ? service.chat(req, invoke(method)) : service.chatStream(req, { onData }, invoke(method)) - const pending = call.then(value => ({ status: 'fulfilled' as const, value }), (reason: unknown) => ({ status: 'rejected' as const, reason })) + const call = + method === 'chat' + ? service.chat(req, invoke(method)) + : service.chatStream(req, { onData }, invoke(method)) + const pending = call.then( + (value) => ({ status: 'fulfilled' as const, value }), + (reason: unknown) => ({ status: 'rejected' as const, reason }) + ) await vi.waitFor(() => expect(policy.listPendingTerminalApprovals()).toHaveLength(1)) const approval = policy.listPendingTerminalApprovals()[0] expect(approval.request.request.input).toEqual(args) expect(await fs.readFile(file, 'utf8')).toBe(before) - policy.resolvePendingTerminalApproval({ approvalId: approval.approvalId, expectedRevision: approval.revision, approved: true }) + policy.resolvePendingTerminalApproval({ + approvalId: approval.approvalId, + expectedRevision: approval.revision, + approved: true + }) const outcome = await pending // The model may explain a failed operation, never turn it into a success. expect(chat).toHaveBeenCalledTimes(2) @@ -510,34 +1327,96 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and expect(policy.listPendingTerminalApprovals()).toEqual([]) if (method === 'chat') { expect(outcome.status).toBe('rejected') - if (outcome.status === 'rejected') expect(outcome.reason).toMatchObject({ code: 'MAGIC_AGENT_FILES_EDIT_FAILED', message: expect.stringContaining(explanation), payload: { kind: 'agent-tool-failure/v1', toolHistory: [expect.objectContaining({ status: 'failed', toolName: 'files.edit' })] } }) + if (outcome.status === 'rejected') + expect(outcome.reason).toMatchObject({ + code: 'MAGIC_AGENT_FILES_EDIT_FAILED', + message: expect.stringContaining(explanation), + payload: { + kind: 'agent-tool-failure/v1', + toolHistory: [expect.objectContaining({ status: 'failed', toolName: 'files.edit' })] + } + }) } else { expect(outcome.status).toBe('fulfilled') - expect(onData.mock.calls.filter(([event]) => event.type === 'tool-status').map(([event]) => event.toolStatus?.status)).toEqual(['running', 'failed']) - const terminals = onData.mock.calls.map(([event]) => event).filter(event => event.type === 'error' || event.type === 'done') - expect(terminals.map(event => event.type)).toEqual(['error', 'done']) - for (const event of terminals) expect(event).toMatchObject({ finishReason: 'error', error: expect.stringContaining(explanation), metadata: { toolHistory: [expect.objectContaining({ status: 'failed', toolName: 'files.edit' })] } }) - expect(terminals.find(event => event.type === 'done')?.usage).toEqual({ promptTokens: 32, completionTokens: 9, totalTokens: 41 }) + expect( + onData.mock.calls + .filter(([event]) => event.type === 'tool-status') + .map(([event]) => event.toolStatus?.status) + ).toEqual(['running', 'failed']) + const terminals = onData.mock.calls + .map(([event]) => event) + .filter((event) => event.type === 'error' || event.type === 'done') + expect(terminals.map((event) => event.type)).toEqual(['error', 'done']) + for (const event of terminals) + expect(event).toMatchObject({ + finishReason: 'error', + error: expect.stringContaining(explanation), + metadata: { + toolHistory: [expect.objectContaining({ status: 'failed', toolName: 'files.edit' })] + } + }) + expect(terminals.find((event) => event.type === 'done')?.usage).toEqual({ + promptTokens: 32, + completionTokens: 9, + totalTokens: 41 + }) } const session = await store.getSession(route) - const results = (session?.eventLog ?? []).map(event => event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined).filter(action => action?.type === 'tool.result') + const results = (session?.eventLog ?? []) + .map( + (event) => + event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined + ) + .filter((action) => action?.type === 'tool.result') expect(results).toHaveLength(1) const result = results[0]! - expect(result.payload).toMatchObject({ ok: false, error: { code: 'MAGIC_AGENT_FILES_EDIT_FAILED' }, metadata: { report: expectedReport } }) + expect(result.payload).toMatchObject({ + ok: false, + error: { code: 'MAGIC_AGENT_FILES_EDIT_FAILED' }, + metadata: { report: expectedReport } + }) const receipt = JSON.parse(result.payload.content!) expect(receipt).toEqual(result.payload.metadata) expect(receipt.error.message).not.toContain(explanation) if (mode === 'strict') expect(receipt).not.toHaveProperty('mutation') else { - expect(receipt.mutation).toMatchObject({ beforeSha256: hash(before), afterSha256: hash(after) }) - expect(await fs.readFile(path.join(root, '.magicpot', 'tool-host', 'snapshots', receipt.mutation.snapshotId, 'content'), 'utf8')).toBe(before) + expect(receipt.mutation).toMatchObject({ + beforeSha256: hash(before), + afterSha256: hash(after) + }) + expect( + await fs.readFile( + path.join( + root, + '.magicpot', + 'tool-host', + 'snapshots', + receipt.mutation.snapshotId, + 'content' + ), + 'utf8' + ) + ).toBe(before) } expect(await fs.readFile(file, 'utf8')).toBe(after) expect(h.fetch).not.toHaveBeenCalled() await store.flush() const reopenedStore = new AssistantSessionStore(path.join(h.data, 'sessions.json')) - const reopenedRuntime = new AssistantRuntime({ sessionStore: reopenedStore, configProvider: getConfig, chatService: { chat: vi.fn() } }) - await expect(reopenedRuntime.callTool(route, 'files.edit', args, { runId: result.correlationId, toolCallId: result.payload.toolCallId, allowedToolNames: ['files.edit'] })).rejects.toMatchObject({ code: 'TOOL_EXECUTION_ALREADY_SETTLED', toolResult: { content: result.payload.content, metadata: receipt } }) + const reopenedRuntime = new AssistantRuntime({ + sessionStore: reopenedStore, + configProvider: getConfig, + chatService: { chat: vi.fn() } + }) + await expect( + reopenedRuntime.callTool(route, 'files.edit', args, { + runId: result.correlationId, + toolCallId: result.payload.toolCallId, + allowedToolNames: ['files.edit'] + }) + ).rejects.toMatchObject({ + code: 'TOOL_EXECUTION_ALREADY_SETTLED', + toolResult: { content: result.payload.content, metadata: receipt } + }) expect((await reopenedStore.getSession(route))?.eventLog).toEqual(session!.eventLog) expect(await fs.readFile(file, 'utf8')).toBe(after) expect(policy.listPendingTerminalApprovals()).toEqual([]) @@ -545,31 +1424,77 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and } ) - it.each((['chat', 'chatStream'] as const).flatMap(method => (['native-same', 'native-new', 'legacy', 'explicit', 'image', 'attachment', 'hosted', 'empty', 'too-large', 'length', 'provider-error', 'native-unsupported', 'stop-after-status', 'navigate-after-status', 'stop-in-model', 'navigate-in-model', 'document-url-changed', 'persist-failed', 'persist-after-write', 'audit-failed', 'multibatch', 'non-native', 'no-isolation', 'transcript-limit'] as const).map(kind => [method, kind] as const)))( - 'bounded failed-edit feedback refuses unsafe next step via %s kind=%s', async (method, kind) => { - const before = 'original\n', file = path.join(root, 'feedback-guard.txt') + it.each( + (['chat', 'chatStream'] as const).flatMap((method) => + ( + [ + 'native-same', + 'native-new', + 'legacy', + 'explicit', + 'image', + 'attachment', + 'hosted', + 'empty', + 'too-large', + 'length', + 'provider-error', + 'native-unsupported', + 'stop-after-status', + 'navigate-after-status', + 'stop-in-model', + 'navigate-in-model', + 'document-url-changed', + 'persist-failed', + 'persist-after-write', + 'audit-failed', + 'multibatch', + 'non-native', + 'no-isolation', + 'transcript-limit' + ] as const + ).map((kind) => [method, kind] as const) + ) + )( + 'bounded failed-edit feedback refuses unsafe next step via %s kind=%s', + async (method, kind) => { + const before = 'original\n', + file = path.join(root, 'feedback-guard.txt') await fs.writeFile(file, before) - const args = { path: 'feedback-guard.txt', expectedSha256: hash(before), replacements: [{ old: 'absent', new: 'never', expectedOccurrences: 1 }] } - const policy = getAssistantTerminalPolicyRuntime(), runtimeCalls = vi.spyOn(h.runtime!, 'callTool') + const args = { + path: 'feedback-guard.txt', + expectedSha256: hash(before), + replacements: [{ old: 'absent', new: 'never', expectedOccurrences: 1 }] + } + const policy = getAssistantTerminalPolicyRuntime(), + runtimeCalls = vi.spyOn(h.runtime!, 'callTool') if (kind === 'audit-failed') { const appendAudit = policy.eventStore.appendBatch.bind(policy.eventStore) vi.spyOn(policy.eventStore, 'appendBatch').mockImplementation((events, options) => { - if (events.some(event => event.streamId === TOOL_AUDIT_STREAM_ID)) throw Error('injected host failure audit rejection') + if (events.some((event) => event.streamId === TOOL_AUDIT_STREAM_ID)) + throw Error('injected host failure audit rejection') return appendAudit(events, options) }) } const originalAppend = store.appendEvents.bind(store) const append = vi.spyOn(store, 'appendEvents').mockImplementation(async (...input) => { - const hasFailure = input[1].some(event => { - const action = event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined + const hasFailure = input[1].some((event) => { + const action = event.metadata?.agentAction as + import('@shared/agent').ToolResultAction | undefined return action?.type === 'tool.result' && !action.payload.ok }) - if (hasFailure && kind === 'persist-failed') throw Error('injected failure journal write rejection') + if (hasFailure && kind === 'persist-failed') + throw Error('injected failure journal write rejection') const result = await originalAppend(...input) - if (hasFailure && kind === 'persist-after-write') throw Error('injected ambiguous failure journal publication') + if (hasFailure && kind === 'persist-after-write') + throw Error('injected ambiguous failure journal publication') if (hasFailure && kind === 'stop-after-status' && method === 'chat') - await service.cancelConversation({ conversationId: scope.conversationId }, invoke('cancelConversation')) - if (hasFailure && kind === 'navigate-after-status' && method === 'chat') sender.emit('did-start-navigation') + await service.cancelConversation( + { conversationId: scope.conversationId }, + invoke('cancelConversation') + ) + if (hasFailure && kind === 'navigate-after-status' && method === 'chat') + sender.emit('did-start-navigation') return result }) const originalCallId = 'feedback-guard-call' @@ -577,12 +1502,26 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and const chat = vi.fn(async (input: LLMChatParams): Promise => { if (chat.mock.calls.length === 1) { if (kind === 'non-native') return JSON.stringify({ toolName: 'files.edit', args }) - const index = input.tools!.findIndex(tool => tool.name === 'files.edit') + const index = input.tools!.findIndex((tool) => tool.name === 'files.edit') expect(index).toBeGreaterThanOrEqual(0) failedWire = `mp_tool_${index}` - const call = { id: originalCallId, name: 'files.edit', wireName: failedWire, arguments: JSON.stringify(args) } - return { content: '', toolCalls: kind === 'multibatch' ? [call, { ...call, id: 'must-not-start' }] : [call], - ...(kind === 'transcript-limit' ? { toolResponseItems: [{ type: 'reasoning', encrypted_content: 'x'.repeat(8 * 1024 * 1024) }] } : {}) } + const call = { + id: originalCallId, + name: 'files.edit', + wireName: failedWire, + arguments: JSON.stringify(args) + } + return { + content: '', + toolCalls: kind === 'multibatch' ? [call, { ...call, id: 'must-not-start' }] : [call], + ...(kind === 'transcript-limit' + ? { + toolResponseItems: [ + { type: 'reasoning', encrypted_content: 'x'.repeat(8 * 1024 * 1024) } + ] + } + : {}) + } } expect(chat).toHaveBeenCalledTimes(2) expect(input.tools).toBeUndefined() @@ -595,40 +1534,107 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and expect(input.imageGenerationOptions).toEqual({ enabled: false }) expect(input.imageRequest).toBeUndefined() expect(input.videoGenerationOptions).toBeUndefined() - expect(JSON.parse(input.toolTurns!.at(-1)!.results[0].output)).toMatchObject({ error: { code: 'MAGIC_AGENT_FILES_EDIT_FAILED' }, report: { writeStatus: 'not-written', fileChanged: false } }) - if (kind === 'stop-in-model') await service.cancelConversation({ conversationId: scope.conversationId }, invoke('cancelConversation')) + expect(JSON.parse(input.toolTurns!.at(-1)!.results[0].output)).toMatchObject({ + error: { code: 'MAGIC_AGENT_FILES_EDIT_FAILED' }, + report: { writeStatus: 'not-written', fileChanged: false } + }) + if (kind === 'stop-in-model') + await service.cancelConversation( + { conversationId: scope.conversationId }, + invoke('cancelConversation') + ) if (kind === 'navigate-in-model') sender.emit('did-start-navigation') - if (kind === 'document-url-changed') Object.assign(sender, { getURL: () => 'file:///D:/owned/app/index.html#/canvas?id=different-feedback-project' }) + if (kind === 'document-url-changed') + Object.assign(sender, { + getURL: () => 'file:///D:/owned/app/index.html#/canvas?id=different-feedback-project' + }) if (kind === 'provider-error') throw Error('injected final explanation provider rejection') - if (kind === 'native-unsupported') throw Error('Native tools are not supported by this endpoint') - if (kind === 'native-same' || kind === 'native-new') return { content: '', toolCalls: [{ id: kind === 'native-same' ? originalCallId : 'new-retry-id', name: 'files.edit', wireName: failedWire, arguments: JSON.stringify(args) }] } + if (kind === 'native-unsupported') + throw Error('Native tools are not supported by this endpoint') + if (kind === 'native-same' || kind === 'native-new') + return { + content: '', + toolCalls: [ + { + id: kind === 'native-same' ? originalCallId : 'new-retry-id', + name: 'files.edit', + wireName: failedWire, + arguments: JSON.stringify(args) + } + ] + } if (kind === 'legacy') return { content: JSON.stringify({ toolName: 'files.edit', args }) } if (kind === 'explicit') return { content: `/tool files.edit ${JSON.stringify(args)}` } - if (kind === 'image') return { content: 'Do not publish this as a safe explanation.', imageUrl: 'https://never.invalid/image.png' } - if (kind === 'attachment') return { content: 'Do not publish this as a safe explanation.', attachments: [{ type: 'video', url: 'https://never.invalid/video.mp4' }] } - if (kind === 'hosted') return { content: 'Do not publish this as a safe explanation.', toolResponseItems: [{ type: 'web_search_call' }] } + if (kind === 'image') + return { + content: 'Do not publish this as a safe explanation.', + imageUrl: 'https://never.invalid/image.png' + } + if (kind === 'attachment') + return { + content: 'Do not publish this as a safe explanation.', + attachments: [{ type: 'video', url: 'https://never.invalid/video.mp4' }] + } + if (kind === 'hosted') + return { + content: 'Do not publish this as a safe explanation.', + toolResponseItems: [{ type: 'web_search_call' }] + } if (kind === 'empty') return { content: '' } if (kind === 'too-large') return { content: '你'.repeat(5462) } - if (kind === 'length') return { content: 'Do not publish this incomplete explanation.', finishReason: 'length' } + if (kind === 'length') + return { content: 'Do not publish this incomplete explanation.', finishReason: 'length' } return { content: 'Late explanation must not be published after request ownership ends.' } }) - vi.mocked(cliFromProfile).mockReturnValue({ chat, supportsNativeTools: kind !== 'non-native', supportsIsolatedReadOnlyTurns: kind !== 'no-isolation' } as never) - const onData = vi.fn<(event: LLMChatStreamResp) => void>(event => { + vi.mocked(cliFromProfile).mockReturnValue({ + chat, + supportsNativeTools: kind !== 'non-native', + supportsIsolatedReadOnlyTurns: kind !== 'no-isolation' + } as never) + const onData = vi.fn<(event: LLMChatStreamResp) => void>((event) => { if (event.type === 'tool-status' && event.toolStatus?.status === 'failed') { - if (kind === 'stop-after-status') void service.cancelConversation({ conversationId: scope.conversationId }, invoke('cancelConversation')) + if (kind === 'stop-after-status') + void service.cancelConversation( + { conversationId: scope.conversationId }, + invoke('cancelConversation') + ) if (kind === 'navigate-after-status') sender.emit('did-start-navigation') } }) - const req: LLMChatReq = { ...scope, profileId: 'agent-profile', messages: [{ role: 'user', content: 'Apply only the reviewed operation once.' }] } - const call = method === 'chat' ? service.chat(req, invoke(method)) : service.chatStream(req, { onData }, invoke(method)) - const pending = call.then(value => ({ status: 'fulfilled' as const, value }), (reason: unknown) => ({ status: 'rejected' as const, reason })) + const req: LLMChatReq = { + ...scope, + profileId: 'agent-profile', + messages: [{ role: 'user', content: 'Apply only the reviewed operation once.' }] + } + const call = + method === 'chat' + ? service.chat(req, invoke(method)) + : service.chatStream(req, { onData }, invoke(method)) + const pending = call.then( + (value) => ({ status: 'fulfilled' as const, value }), + (reason: unknown) => ({ status: 'rejected' as const, reason }) + ) await vi.waitFor(() => expect(policy.listPendingTerminalApprovals()).toHaveLength(1)) const approval = policy.listPendingTerminalApprovals()[0] expect(approval.request.request.input).toEqual(args) expect(await fs.readFile(file, 'utf8')).toBe(before) - policy.resolvePendingTerminalApproval({ approvalId: approval.approvalId, expectedRevision: approval.revision, approved: true }) + policy.resolvePendingTerminalApproval({ + approvalId: approval.approvalId, + expectedRevision: approval.revision, + approved: true + }) const outcome = await pending - const noNextModel = ['stop-after-status', 'navigate-after-status', 'persist-failed', 'persist-after-write', 'audit-failed', 'multibatch', 'non-native', 'no-isolation', 'transcript-limit'].includes(kind) + const noNextModel = [ + 'stop-after-status', + 'navigate-after-status', + 'persist-failed', + 'persist-after-write', + 'audit-failed', + 'multibatch', + 'non-native', + 'no-isolation', + 'transcript-limit' + ].includes(kind) expect(chat).toHaveBeenCalledTimes(noNextModel ? 1 : 2) expect(runtimeCalls).toHaveBeenCalledOnce() expect(policy.listPendingTerminalApprovals()).toEqual([]) @@ -637,37 +1643,70 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and expect(h.fetch).not.toHaveBeenCalled() const cancelled = kind.startsWith('stop-') || kind.startsWith('navigate-') const session = await store.getSession(route) - const actions = (session?.eventLog ?? []).map(event => event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined).filter(action => action?.type === 'tool.result') + const actions = (session?.eventLog ?? []) + .map( + (event) => + event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined + ) + .filter((action) => action?.type === 'tool.result') expect(actions).toHaveLength(kind === 'persist-failed' ? 0 : 1) if (actions[0]) { if (kind === 'audit-failed') { - expect(actions[0].payload).toMatchObject({ ok: false, error: { message: 'injected host failure audit rejection' } }) + expect(actions[0].payload).toMatchObject({ + ok: false, + error: { message: 'injected host failure audit rejection' } + }) expect(actions[0].payload).not.toHaveProperty('content') expect(actions[0].payload).not.toHaveProperty('metadata') } else { - expect(actions[0].payload).toMatchObject({ ok: false, error: { code: 'MAGIC_AGENT_FILES_EDIT_FAILED' }, metadata: { report: { failed: 1, writeStatus: 'not-written' } } }) + expect(actions[0].payload).toMatchObject({ + ok: false, + error: { code: 'MAGIC_AGENT_FILES_EDIT_FAILED' }, + metadata: { report: { failed: 1, writeStatus: 'not-written' } } + }) expect(actions[0].payload.metadata).not.toHaveProperty('mutation') } } if (method === 'chat') { expect(outcome.status).toBe('rejected') if (outcome.status === 'rejected' && !cancelled && kind !== 'document-url-changed') { - if (kind === 'audit-failed') expect(outcome.reason).toMatchObject({ message: 'injected host failure audit rejection' }) - else expect(outcome.reason).toMatchObject({ code: 'MAGIC_AGENT_FILES_EDIT_FAILED', payload: { kind: 'agent-tool-failure/v1', toolHistory: [expect.objectContaining({ status: 'failed' })] } }) + if (kind === 'audit-failed') + expect(outcome.reason).toMatchObject({ + message: 'injected host failure audit rejection' + }) + else + expect(outcome.reason).toMatchObject({ + code: 'MAGIC_AGENT_FILES_EDIT_FAILED', + payload: { + kind: 'agent-tool-failure/v1', + toolHistory: [expect.objectContaining({ status: 'failed' })] + } + }) } } else { expect(outcome.status).toBe('fulfilled') const events = onData.mock.calls.map(([event]) => event) - expect(events.filter(event => event.type === 'text-delta' || event.type === 'attachment')).toEqual([]) - const terminals = events.filter(event => event.type === 'error' || event.type === 'done') - if (kind.startsWith('navigate-') || kind === 'document-url-changed') expect(terminals).toEqual([]) - else if (kind.startsWith('stop-')) expect(terminals).toEqual([expect.objectContaining({ type: 'done', finishReason: 'cancelled' })]) + expect( + events.filter((event) => event.type === 'text-delta' || event.type === 'attachment') + ).toEqual([]) + const terminals = events.filter((event) => event.type === 'error' || event.type === 'done') + if (kind.startsWith('navigate-') || kind === 'document-url-changed') + expect(terminals).toEqual([]) + else if (kind.startsWith('stop-')) + expect(terminals).toEqual([ + expect.objectContaining({ type: 'done', finishReason: 'cancelled' }) + ]) else { - expect(terminals.map(event => event.type)).toEqual(['error', 'done']) + expect(terminals.map((event) => event.type)).toEqual(['error', 'done']) for (const event of terminals) { expect(event.finishReason).toBe('error') - if (kind === 'audit-failed') { expect(event.error).toBe('injected host failure audit rejection'); expect(event).not.toHaveProperty('metadata') } - else expect(event).toMatchObject({ metadata: { toolHistory: [expect.objectContaining({ status: 'failed' })] } }) + if (kind === 'audit-failed') { + expect(event.error).toBe('injected host failure audit rejection') + expect(event).not.toHaveProperty('metadata') + } else + expect(event).toMatchObject({ + metadata: { toolHistory: [expect.objectContaining({ status: 'failed' })] } + }) } expect(JSON.stringify(terminals)).not.toContain('Untrusted model explanation') } @@ -678,47 +1717,131 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and ) it('rechecks the current document between explanation error and done frames', async () => { - const before = 'original\n', file = path.join(root, 'feedback-terminal.txt') + const before = 'original\n', + file = path.join(root, 'feedback-terminal.txt') await fs.writeFile(file, before) - const args = { path: 'feedback-terminal.txt', expectedSha256: hash(before), replacements: [{ old: 'absent', new: 'never', expectedOccurrences: 1 }] } + const args = { + path: 'feedback-terminal.txt', + expectedSha256: hash(before), + replacements: [{ old: 'absent', new: 'never', expectedOccurrences: 1 }] + } const chat = vi.fn(async (input: LLMChatParams): Promise => { - if (chat.mock.calls.length === 1) return { content: '', toolCalls: [{ id: 'failed-terminal', name: 'files.edit', wireName: `mp_tool_${input.tools!.findIndex(tool => tool.name === 'files.edit')}`, arguments: JSON.stringify(args) }] } + if (chat.mock.calls.length === 1) + return { + content: '', + toolCalls: [ + { + id: 'failed-terminal', + name: 'files.edit', + wireName: `mp_tool_${input.tools!.findIndex((tool) => tool.name === 'files.edit')}`, + arguments: JSON.stringify(args) + } + ] + } return { content: 'The approved edit failed and was not retried.', finishReason: 'stop' } }) - vi.mocked(cliFromProfile).mockReturnValue({ chat, supportsNativeTools: true, supportsIsolatedReadOnlyTurns: true } as never) - const events: LLMChatStreamResp[] = [], policy = getAssistantTerminalPolicyRuntime() - const call = service.chatStream({ ...scope, profileId: 'agent-profile', messages: [{ role: 'user', content: 'Apply this reviewed edit once.' }] }, { onData: event => { - events.push(event) - if (event.type === 'error') Object.assign(sender, { getURL: () => 'file:///D:/owned/app/index.html#/canvas?id=other-project' }) - } }, invoke('chatStream')) + vi.mocked(cliFromProfile).mockReturnValue({ + chat, + supportsNativeTools: true, + supportsIsolatedReadOnlyTurns: true + } as never) + const events: LLMChatStreamResp[] = [], + policy = getAssistantTerminalPolicyRuntime() + const call = service.chatStream( + { + ...scope, + profileId: 'agent-profile', + messages: [{ role: 'user', content: 'Apply this reviewed edit once.' }] + }, + { + onData: (event) => { + events.push(event) + if (event.type === 'error') + Object.assign(sender, { + getURL: () => 'file:///D:/owned/app/index.html#/canvas?id=other-project' + }) + } + }, + invoke('chatStream') + ) await vi.waitFor(() => expect(policy.listPendingTerminalApprovals()).toHaveLength(1)) const approval = policy.listPendingTerminalApprovals()[0] - policy.resolvePendingTerminalApproval({ approvalId: approval.approvalId, expectedRevision: approval.revision, approved: true }) + policy.resolvePendingTerminalApproval({ + approvalId: approval.approvalId, + expectedRevision: approval.revision, + approved: true + }) await call expect(chat).toHaveBeenCalledTimes(2) - expect(events.filter(event => event.type === 'error' || event.type === 'done').map(event => event.type)).toEqual(['error']) - expect(events.find(event => event.type === 'error')).toMatchObject({ finishReason: 'error', error: expect.stringContaining('The approved edit failed and was not retried.') }) + expect( + events + .filter((event) => event.type === 'error' || event.type === 'done') + .map((event) => event.type) + ).toEqual(['error']) + expect(events.find((event) => event.type === 'error')).toMatchObject({ + finishReason: 'error', + error: expect.stringContaining('The approved edit failed and was not retried.') + }) expect(await fs.readFile(file, 'utf8')).toBe(before) expect(sender.listenerCount('did-start-navigation')).toBe(0) }) - it.each(([['chat', false], ['chat', true], ['chatStream', false], ['chatStream', true]] as const) - .flatMap(([method, native]) => [false, true].flatMap(rollbackFails => (method === 'chat' ? ['main', 'ipc'] as const : ['main'] as const).map(transport => [method, native, rollbackFails, transport] as const))))( - 'retains actual batch rollback failure via %s native=%s rollbackFails=%s transport=%s', async (method, native, rollbackFails, transport) => { + it.each( + ( + [ + ['chat', false], + ['chat', true], + ['chatStream', false], + ['chatStream', true] + ] as const + ).flatMap(([method, native]) => + [false, true].flatMap((rollbackFails) => + (method === 'chat' ? (['main', 'ipc'] as const) : (['main'] as const)).map( + (transport) => [method, native, rollbackFails, transport] as const + ) + ) + ) + )( + 'retains actual batch rollback failure via %s native=%s rollbackFails=%s transport=%s', + async (method, native, rollbackFails, transport) => { await fs.writeFile(path.join(root, 'a.txt'), 'a') await fs.writeFile(path.join(root, 'b.txt'), 'b') - const args = { edits: [ - { path: 'a.txt', expectedSha256: hash('a'), replacements: [{ old: 'a', new: 'A', expectedOccurrences: 1 }] }, - { path: 'b.txt', expectedSha256: hash('b'), replacements: [{ old: 'b', new: 'B', expectedOccurrences: 1 }] } - ] } + const args = { + edits: [ + { + path: 'a.txt', + expectedSha256: hash('a'), + replacements: [{ old: 'a', new: 'A', expectedOccurrences: 1 }] + }, + { + path: 'b.txt', + expectedSha256: hash('b'), + replacements: [{ old: 'b', new: 'B', expectedOccurrences: 1 }] + } + ] + } const chat = vi.fn(async (input: { tools: Array<{ name: string }> }) => { - const name = 'files.multi-edit', index = input.tools?.findIndex(tool => tool.name === name) + const name = 'files.multi-edit', + index = input.tools?.findIndex((tool) => tool.name === name) if (!native) return JSON.stringify({ toolName: name, args }) expect(index).toBeGreaterThanOrEqual(0) - return { content: '', toolCalls: [ - { id: 'failed-batch', name, wireName: `mp_tool_${index}`, arguments: JSON.stringify(args) }, - { id: 'unstarted-batch', name, wireName: `mp_tool_${index}`, arguments: JSON.stringify(args) } - ] } + return { + content: '', + toolCalls: [ + { + id: 'failed-batch', + name, + wireName: `mp_tool_${index}`, + arguments: JSON.stringify(args) + }, + { + id: 'unstarted-batch', + name, + wireName: `mp_tool_${index}`, + arguments: JSON.stringify(args) + } + ] + } }) vi.mocked(cliFromProfile).mockReturnValue({ chat, supportsNativeTools: native } as never) const originalRename = fs.rename.bind(fs) @@ -734,8 +1857,13 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and }) const appendEvents = vi.spyOn(store, 'appendEvents') const runtimeCalls = vi.spyOn(h.runtime!, 'callTool') - const onData = vi.fn<(event: LLMChatStreamResp) => void>(), policy = getAssistantTerminalPolicyRuntime() - const req = { ...scope, profileId: 'agent-profile', messages: [{ role: 'user' as const, content: 'Apply the reviewed batch once.' }] } + const onData = vi.fn<(event: LLMChatStreamResp) => void>(), + policy = getAssistantTerminalPolicyRuntime() + const req = { + ...scope, + profileId: 'agent-profile', + messages: [{ role: 'user' as const, content: 'Apply the reviewed batch once.' }] + } let call: Promise if (transport === 'ipc') { type Api = { svcLLMProxy: { chat(req: LLMChatReq): Promise } } @@ -744,24 +1872,62 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and const handler = h.handle.mock.calls.find(([name]) => name === 'svcLLMProxy.chat')![1] h.invoke.mockImplementation(async (name, request) => { expect(name).toBe('svcLLMProxy.chat') - try { return structuredClone(await handler({ sender, senderFrame: { url, parent: null } }, structuredClone(request))) } - catch (error) { throw new Error(error instanceof Error ? error.message : 'IPC handler failed') } + try { + return structuredClone( + await handler( + { sender, senderFrame: { url, parent: null } }, + structuredClone(request) + ) + ) + } catch (error) { + throw new Error(error instanceof Error ? error.message : 'IPC handler failed') + } }) call = createIpcClient(definition).svcLLMProxy.chat(req) - } else call = method === 'chat' ? service.chat(req, invoke(method)) : service.chatStream(req, { onData }, invoke(method)) - const pending = call.then(value => ({ status: 'fulfilled' as const, value }), (reason: unknown) => ({ status: 'rejected' as const, reason })) + } else + call = + method === 'chat' + ? service.chat(req, invoke(method)) + : service.chatStream(req, { onData }, invoke(method)) + const pending = call.then( + (value) => ({ status: 'fulfilled' as const, value }), + (reason: unknown) => ({ status: 'rejected' as const, reason }) + ) await vi.waitFor(() => expect(policy.listPendingTerminalApprovals()).toHaveLength(1)) expect(await fs.readFile(path.join(root, 'a.txt'), 'utf8')).toBe('a') expect(targetRenames).toBe(0) const approval = policy.listPendingTerminalApprovals()[0] expect(approval.request.request.input).toEqual({ ...args, path: '.' }) - policy.resolvePendingTerminalApproval({ approvalId: approval.approvalId, expectedRevision: approval.revision, approved: true }) + policy.resolvePendingTerminalApproval({ + approvalId: approval.approvalId, + expectedRevision: approval.revision, + approved: true + }) const outcome = await pending rename.mockRestore() expect(targetRenames).toBe(3) - const rollback = { attempted: true, succeeded: !rollbackFails, restoredPaths: rollbackFails ? [] : ['a.txt'], failedPaths: rollbackFails ? ['a.txt'] : [] } - const receipt = { error: { message: 'Multi-file commit failed: injected second commit failure', code: 'MAGIC_AGENT_FILES_MUTATION' }, rollback } - const expectedHistory = [expect.objectContaining({ toolName: 'files.multi-edit', status: 'failed', content: JSON.stringify(receipt, null, 2), metadata: expect.objectContaining(receipt), error: receipt.error.message })] + const rollback = { + attempted: true, + succeeded: !rollbackFails, + restoredPaths: rollbackFails ? [] : ['a.txt'], + failedPaths: rollbackFails ? ['a.txt'] : [] + } + const receipt = { + error: { + message: 'Multi-file commit failed: injected second commit failure', + code: 'MAGIC_AGENT_FILES_MUTATION' + }, + rollback + } + const expectedHistory = [ + expect.objectContaining({ + toolName: 'files.multi-edit', + status: 'failed', + content: JSON.stringify(receipt, null, 2), + metadata: expect.objectContaining(receipt), + error: receipt.error.message + }) + ] expect(policy.listPendingTerminalApprovals()).toEqual([]) if (method === 'chat') { expect(outcome.status).toBe('rejected') @@ -771,15 +1937,35 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and expect(outcome.reason).not.toBeInstanceOf(Error) expect(h.invoke).toHaveBeenCalledOnce() } - expect(outcome.reason).toMatchObject({ code: receipt.error.code, message: receipt.error.message, payload: { kind: 'agent-tool-failure/v1', toolResult: { content: JSON.stringify(receipt, null, 2), metadata: receipt }, toolHistory: expectedHistory } }) + expect(outcome.reason).toMatchObject({ + code: receipt.error.code, + message: receipt.error.message, + payload: { + kind: 'agent-tool-failure/v1', + toolResult: { content: JSON.stringify(receipt, null, 2), metadata: receipt }, + toolHistory: expectedHistory + } + }) } } else { expect(outcome.status).toBe('fulfilled') const events = onData.mock.calls.map(([event]) => event) - expect(events.filter(event => event.type === 'tool-status').map(event => event.toolStatus?.status)).toEqual(['running', 'failed']) - expect(events.filter(event => event.type === 'done' || event.type === 'error')).toEqual([ - expect.objectContaining({ type: 'error', finishReason: 'error', metadata: expect.objectContaining({ toolHistory: expectedHistory }) }), - expect.objectContaining({ type: 'done', finishReason: 'error', metadata: expect.objectContaining({ toolHistory: expectedHistory }) }) + expect( + events + .filter((event) => event.type === 'tool-status') + .map((event) => event.toolStatus?.status) + ).toEqual(['running', 'failed']) + expect(events.filter((event) => event.type === 'done' || event.type === 'error')).toEqual([ + expect.objectContaining({ + type: 'error', + finishReason: 'error', + metadata: expect.objectContaining({ toolHistory: expectedHistory }) + }), + expect.objectContaining({ + type: 'done', + finishReason: 'error', + metadata: expect.objectContaining({ toolHistory: expectedHistory }) + }) ]) } expect(chat).toHaveBeenCalledOnce() @@ -788,95 +1974,213 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and const snapshots = path.join(root, '.magicpot', 'tool-host', 'snapshots') const snapshotIds = await fs.readdir(snapshots) expect(snapshotIds).toHaveLength(2) - const oldContents = await Promise.all(snapshotIds.map(id => fs.readFile(path.join(snapshots, id, 'content'), 'utf8'))) + const oldContents = await Promise.all( + snapshotIds.map((id) => fs.readFile(path.join(snapshots, id, 'content'), 'utf8')) + ) expect(oldContents.sort()).toEqual(['a', 'b']) const session = await store.getSession(route) - const actions = (session?.eventLog ?? []).map(event => event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined).filter(action => action?.type === 'tool.result') + const actions = (session?.eventLog ?? []) + .map( + (event) => + event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined + ) + .filter((action) => action?.type === 'tool.result') expect(runtimeCalls).toHaveBeenCalledOnce() expect(appendEvents).toHaveBeenCalledTimes(2) expect(actions).toHaveLength(1) - expect(actions[0]?.payload).toMatchObject({ ok: false, content: JSON.stringify(receipt, null, 2), metadata: receipt, error: receipt.error }) + expect(actions[0]?.payload).toMatchObject({ + ok: false, + content: JSON.stringify(receipt, null, 2), + metadata: receipt, + error: receipt.error + }) // Reload actual persisted events using a new store/adapter, not an in-memory // receipt substitute. A failed call is replayed as failure, never dispatched. await store.flush() const reopenedStore = new AssistantSessionStore(path.join(h.data, 'sessions.json')) - const reopenedRuntime = new AssistantRuntime({ sessionStore: reopenedStore, configProvider: getConfig, chatService: { chat: vi.fn() } }) + const reopenedRuntime = new AssistantRuntime({ + sessionStore: reopenedStore, + configProvider: getConfig, + chatService: { chat: vi.fn() } + }) const resultAction = actions[0]! - await expect(reopenedRuntime.callTool(route, 'files.multi-edit', args, { - runId: resultAction.correlationId, toolCallId: resultAction.payload.toolCallId, allowedToolNames: ['files.multi-edit'] - })).rejects.toMatchObject({ code: 'TOOL_EXECUTION_ALREADY_SETTLED', toolResult: { content: JSON.stringify(receipt, null, 2), metadata: receipt } }) + await expect( + reopenedRuntime.callTool(route, 'files.multi-edit', args, { + runId: resultAction.correlationId, + toolCallId: resultAction.payload.toolCallId, + allowedToolNames: ['files.multi-edit'] + }) + ).rejects.toMatchObject({ + code: 'TOOL_EXECUTION_ALREADY_SETTLED', + toolResult: { content: JSON.stringify(receipt, null, 2), metadata: receipt } + }) expect((await reopenedStore.getSession(route))?.eventLog).toEqual(session!.eventLog) expect(policy.listPendingTerminalApprovals()).toEqual([]) expect(await fs.readFile(path.join(root, 'a.txt'), 'utf8')).toBe(rollbackFails ? 'A' : 'a') await reopenedRuntime.flush() - expect(() => policy.resolvePendingTerminalApproval({ approvalId: approval.approvalId, expectedRevision: approval.revision, approved: true })).toThrow('not found') + expect(() => + policy.resolvePendingTerminalApproval({ + approvalId: approval.approvalId, + expectedRevision: approval.revision, + approved: true + }) + ).toThrow('not found') expect(h.fetch).not.toHaveBeenCalled() expect(sender.listenerCount('did-start-navigation')).toBe(0) } ) - it.each((['chat', 'chatStream'] as const).flatMap(method => [false, true].flatMap(native => (['marker', 'content', 'cas'] as const).map(failure => [method, native, failure] as const))))( - 'EOF patch via %s native=%s rejects %s without mutation or same-identity redispatch', async (method, native, failure) => { - const before = 'old', file = path.join(root, 'failed-patch.txt') + it.each( + (['chat', 'chatStream'] as const).flatMap((method) => + [false, true].flatMap((native) => + (['marker', 'content', 'cas'] as const).map((failure) => [method, native, failure] as const) + ) + ) + )( + 'EOF patch via %s native=%s rejects %s without mutation or same-identity redispatch', + async (method, native, failure) => { + const before = 'old', + file = path.join(root, 'failed-patch.txt') await fs.writeFile(file, before) - const args = { path: 'failed-patch.txt', expectedSha256: hash(failure === 'cas' ? 'stale' : before), patch: ['--- a/failed-patch.txt', '+++ b/failed-patch.txt', '@@ -1,1 +1,1 @@', ...(failure === 'marker' ? ['\\ No newline at end of file'] : []), failure === 'content' ? '-wrong' : '-old', '\\ No newline at end of file', '+new', ''].join('\n') } - const expectedError = failure === 'marker' ? 'Patch newline marker is orphaned, duplicated, or describes an empty line.' : failure === 'cas' ? 'expectedSha256 is stale.' : 'Patch hunk does not match the complete current file.' - const chat = vi.fn().mockImplementation(async input => { + const args = { + path: 'failed-patch.txt', + expectedSha256: hash(failure === 'cas' ? 'stale' : before), + patch: [ + '--- a/failed-patch.txt', + '+++ b/failed-patch.txt', + '@@ -1,1 +1,1 @@', + ...(failure === 'marker' ? ['\\ No newline at end of file'] : []), + failure === 'content' ? '-wrong' : '-old', + '\\ No newline at end of file', + '+new', + '' + ].join('\n') + } + const expectedError = + failure === 'marker' + ? 'Patch newline marker is orphaned, duplicated, or describes an empty line.' + : failure === 'cas' + ? 'expectedSha256 is stale.' + : 'Patch hunk does not match the complete current file.' + const chat = vi.fn().mockImplementation(async (input) => { expect(chat).toHaveBeenCalledOnce() if (!native) return JSON.stringify({ toolName: 'files.patch', args }) const index = input.tools.findIndex((tool: { name: string }) => tool.name === 'files.patch') expect(index).toBeGreaterThanOrEqual(0) - return { content: '', toolCalls: [ - { id: 'failed-eof-patch', name: 'files.patch', wireName: `mp_tool_${index}`, arguments: JSON.stringify(args) }, - { id: 'unstarted-eof-patch', name: 'files.patch', wireName: `mp_tool_${index}`, arguments: JSON.stringify(args) } - ] } + return { + content: '', + toolCalls: [ + { + id: 'failed-eof-patch', + name: 'files.patch', + wireName: `mp_tool_${index}`, + arguments: JSON.stringify(args) + }, + { + id: 'unstarted-eof-patch', + name: 'files.patch', + wireName: `mp_tool_${index}`, + arguments: JSON.stringify(args) + } + ] + } }) vi.mocked(cliFromProfile).mockReturnValue({ chat, supportsNativeTools: native } as never) - const req = { ...scope, profileId: 'agent-profile', messages: [{ role: 'user' as const, content: 'Apply only the approved patch once.' }] } - const onData = vi.fn<(event: LLMChatStreamResp) => void>(), policy = getAssistantTerminalPolicyRuntime() - const pending = (method === 'chat' ? service.chat(req, invoke(method)) : service.chatStream(req, { onData }, invoke(method))) - .then(value => ({ status: 'fulfilled' as const, value }), (reason: unknown) => ({ status: 'rejected' as const, reason })) + const req = { + ...scope, + profileId: 'agent-profile', + messages: [{ role: 'user' as const, content: 'Apply only the approved patch once.' }] + } + const onData = vi.fn<(event: LLMChatStreamResp) => void>(), + policy = getAssistantTerminalPolicyRuntime() + const pending = ( + method === 'chat' + ? service.chat(req, invoke(method)) + : service.chatStream(req, { onData }, invoke(method)) + ).then( + (value) => ({ status: 'fulfilled' as const, value }), + (reason: unknown) => ({ status: 'rejected' as const, reason }) + ) await vi.waitFor(() => expect(policy.listPendingTerminalApprovals()).toHaveLength(1)) expect(await fs.readFile(file, 'utf8')).toBe(before) const approval = policy.listPendingTerminalApprovals()[0] expect(approval.request.request.target.id).toBe('files.patch') expect(approval.request.request.input).toEqual(args) - policy.resolvePendingTerminalApproval({ approvalId: approval.approvalId, expectedRevision: approval.revision, approved: true }) + policy.resolvePendingTerminalApproval({ + approvalId: approval.approvalId, + expectedRevision: approval.revision, + approved: true + }) const outcome = await pending if (method === 'chat') { expect(outcome.status).toBe('rejected') if (outcome.status === 'rejected') { - expect(outcome.reason).toMatchObject({ code: 'MAGIC_AGENT_FILES_VALIDATION', message: expectedError }) + expect(outcome.reason).toMatchObject({ + code: 'MAGIC_AGENT_FILES_VALIDATION', + message: expectedError + }) expect(outcome.reason).not.toHaveProperty('toolResult') expect(outcome.reason).not.toHaveProperty('mutation') } } else { expect(outcome).toEqual({ status: 'fulfilled', value: undefined }) - const terminals = onData.mock.calls.map(([event]) => event).filter(event => event.type === 'done' || event.type === 'error') - expect(terminals.map(event => event.type)).toEqual(['error', 'done']) + const terminals = onData.mock.calls + .map(([event]) => event) + .filter((event) => event.type === 'done' || event.type === 'error') + expect(terminals.map((event) => event.type)).toEqual(['error', 'done']) for (const event of terminals) { expect(event).toMatchObject({ finishReason: 'error', error: expectedError, content: '' }) expect(event).not.toHaveProperty('metadata') } - expect(onData.mock.calls.map(([event]) => event).filter(event => event.type === 'tool-status').map(event => event.toolStatus?.status)).toEqual(['running', 'failed']) + expect( + onData.mock.calls + .map(([event]) => event) + .filter((event) => event.type === 'tool-status') + .map((event) => event.toolStatus?.status) + ).toEqual(['running', 'failed']) } expect(chat).toHaveBeenCalledOnce() expect(await fs.readFile(file, 'utf8')).toBe(before) await expect(fs.stat(path.join(root, '.magicpot'))).rejects.toMatchObject({ code: 'ENOENT' }) const session = await store.getSession(route) - const actions = (session?.eventLog ?? []).map(event => event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined).filter(action => action?.type === 'tool.result') + const actions = (session?.eventLog ?? []) + .map( + (event) => + event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined + ) + .filter((action) => action?.type === 'tool.result') expect(actions).toHaveLength(1) const resultAction = actions[0]! - expect(resultAction.payload).toMatchObject({ ok: false, toolName: 'files.patch', error: { code: 'MAGIC_AGENT_FILES_VALIDATION', message: expectedError } }) + expect(resultAction.payload).toMatchObject({ + ok: false, + toolName: 'files.patch', + error: { code: 'MAGIC_AGENT_FILES_VALIDATION', message: expectedError } + }) expect(resultAction.payload).not.toHaveProperty('content') expect(resultAction.payload).not.toHaveProperty('metadata') await store.flush() const reopenedStore = new AssistantSessionStore(path.join(h.data, 'sessions.json')) - const reopenedRuntime = new AssistantRuntime({ sessionStore: reopenedStore, configProvider: getConfig, chatService: { chat: vi.fn() } }) - await expect(reopenedRuntime.callTool(route, 'files.patch', args, { runId: resultAction.correlationId, toolCallId: resultAction.payload.toolCallId, allowedToolNames: ['files.patch'] })).rejects.toMatchObject({ code: 'TOOL_EXECUTION_ALREADY_SETTLED', message: expectedError }) + const reopenedRuntime = new AssistantRuntime({ + sessionStore: reopenedStore, + configProvider: getConfig, + chatService: { chat: vi.fn() } + }) + await expect( + reopenedRuntime.callTool(route, 'files.patch', args, { + runId: resultAction.correlationId, + toolCallId: resultAction.payload.toolCallId, + allowedToolNames: ['files.patch'] + }) + ).rejects.toMatchObject({ code: 'TOOL_EXECUTION_ALREADY_SETTLED', message: expectedError }) expect((await reopenedStore.getSession(route))?.eventLog).toEqual(session!.eventLog) expect(policy.listPendingTerminalApprovals()).toEqual([]) - expect(() => policy.resolvePendingTerminalApproval({ approvalId: approval.approvalId, expectedRevision: approval.revision, approved: true })).toThrow('not found') + expect(() => + policy.resolvePendingTerminalApproval({ + approvalId: approval.approvalId, + expectedRevision: approval.revision, + approved: true + }) + ).toThrow('not found') expect(await fs.readFile(file, 'utf8')).toBe(before) expect(h.fetch).not.toHaveBeenCalled() expect(sender.listenerCount('did-start-navigation')).toBe(0) @@ -884,40 +2188,109 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and } ) - it.each(([['chat', false], ['chat', true], ['chatStream', false], ['chatStream', true]] as const) - .flatMap(([method, native]) => (['default', 'partial', 'best_effort', 'patch'] as const).flatMap(mode => (['approve', 'deny', 'navigation', 'stop'] as const).map(ending => [method, native, ending, mode] as const))))( - 'captures an exact edit or EOF patch via %s native=%s ending=%s mode=%s', async (method, native, ending, mode) => { + it.each( + ( + [ + ['chat', false], + ['chat', true], + ['chatStream', false], + ['chatStream', true] + ] as const + ).flatMap(([method, native]) => + (['default', 'partial', 'best_effort', 'patch'] as const).flatMap((mode) => + (['approve', 'deny', 'navigation', 'stop'] as const).map( + (ending) => [method, native, ending, mode] as const + ) + ) + ) + )( + 'captures an exact edit or EOF patch via %s native=%s ending=%s mode=%s', + async (method, native, ending, mode) => { const name = mode === 'patch' ? 'files.patch' : 'files.edit' - const before = mode === 'patch' ? 'old' : 'old old\n', after = mode === 'patch' ? 'approved\n' : 'approved approved\n', file = path.join(root, 'edit.txt') + const before = mode === 'patch' ? 'old' : 'old old\n', + after = mode === 'patch' ? 'approved\n' : 'approved approved\n', + file = path.join(root, 'edit.txt') await fs.writeFile(file, before) - const args = mode === 'patch' ? { path: 'edit.txt', expectedSha256: hash(before), patch: '--- a/edit.txt\n+++ b/edit.txt\n@@ -1,1 +1,1 @@\n-old\n\\ No newline at end of file\n+approved\n' } : { path: 'edit.txt', expectedSha256: hash(before), ...(mode === 'default' ? {} : { mode }), replacements: [ - { old: 'old', new: 'middle', expectedOccurrences: 2 }, - { old: 'middle', new: 'approved', expectedOccurrences: 2 } - ] } - const expectedDiff = mode === 'patch' ? '--- a/edit.txt\n+++ b/edit.txt\n@@ -1,1 +1,1 @@\n-old\n\\ No newline at end of file\n+approved\n' : '--- a/edit.txt\n+++ b/edit.txt\n@@ -1,1 +1,1 @@\n-old old\n+approved approved\n' - const expectedReceipt = { beforeSha256: hash(before), afterSha256: hash(after), diff: expectedDiff, diffBytes: Buffer.byteLength(expectedDiff), additions: 1, deletions: 1 } - const chat = vi.fn().mockImplementation(async input => { + const args = + mode === 'patch' + ? { + path: 'edit.txt', + expectedSha256: hash(before), + patch: + '--- a/edit.txt\n+++ b/edit.txt\n@@ -1,1 +1,1 @@\n-old\n\\ No newline at end of file\n+approved\n' + } + : { + path: 'edit.txt', + expectedSha256: hash(before), + ...(mode === 'default' ? {} : { mode }), + replacements: [ + { old: 'old', new: 'middle', expectedOccurrences: 2 }, + { old: 'middle', new: 'approved', expectedOccurrences: 2 } + ] + } + const expectedDiff = + mode === 'patch' + ? '--- a/edit.txt\n+++ b/edit.txt\n@@ -1,1 +1,1 @@\n-old\n\\ No newline at end of file\n+approved\n' + : '--- a/edit.txt\n+++ b/edit.txt\n@@ -1,1 +1,1 @@\n-old old\n+approved approved\n' + const expectedReceipt = { + beforeSha256: hash(before), + afterSha256: hash(after), + diff: expectedDiff, + diffBytes: Buffer.byteLength(expectedDiff), + additions: 1, + deletions: 1 + } + const chat = vi.fn().mockImplementation(async (input) => { if (chat.mock.calls.length > 1) { expect(JSON.stringify(native ? input.toolTurns : input.messages)).toContain(hash(after)) const outputs: string[] = native - ? input.toolTurns.flatMap((turn: { results: Array<{ output: string }> }) => turn.results.map(result => result.output)) + ? input.toolTurns.flatMap((turn: { results: Array<{ output: string }> }) => + turn.results.map((result) => result.output) + ) : input.messages.map((message: { content: string }) => message.content) // These raw result strings already contain JSON-escaped diff fields; // stringifying the whole transcript again would double-escape them. - expect(outputs.some(output => output.includes(JSON.stringify(expectedDiff)))).toBe(true) + expect(outputs.some((output) => output.includes(JSON.stringify(expectedDiff)))).toBe(true) return 'The approved edit returned its actual SHA and snapshot.' } if (!native) return JSON.stringify({ toolName: name, args }) const index = input.tools.findIndex((tool: { name: string }) => tool.name === name) expect(index).toBeGreaterThanOrEqual(0) - return { content: '', toolCalls: [{ id: 'approved-file-edit', name, wireName: `mp_tool_${index}`, arguments: JSON.stringify(args) }] } + return { + content: '', + toolCalls: [ + { + id: 'approved-file-edit', + name, + wireName: `mp_tool_${index}`, + arguments: JSON.stringify(args) + } + ] + } }) vi.mocked(cliFromProfile).mockReturnValue({ chat, supportsNativeTools: native } as never) - const req = { ...scope, profileId: 'agent-profile', messages: [{ role: 'user' as const, content: 'Apply only the reviewed edit.' }] } - const onData = vi.fn<(event: LLMChatStreamResp) => void>(), policy = getAssistantTerminalPolicyRuntime() + const req = { + ...scope, + profileId: 'agent-profile', + messages: [{ role: 'user' as const, content: 'Apply only the reviewed edit.' }] + } + const onData = vi.fn<(event: LLMChatStreamResp) => void>(), + policy = getAssistantTerminalPolicyRuntime() let settled = false - const pending = (method === 'chat' ? service.chat(req, invoke(method)) : service.chatStream(req, { onData }, invoke(method))) - .then(value => { settled = true; return { status: 'fulfilled' as const, value } }, (reason: unknown) => { settled = true; return { status: 'rejected' as const, reason } }) + const pending = ( + method === 'chat' + ? service.chat(req, invoke(method)) + : service.chatStream(req, { onData }, invoke(method)) + ).then( + (value) => { + settled = true + return { status: 'fulfilled' as const, value } + }, + (reason: unknown) => { + settled = true + return { status: 'rejected' as const, reason } + } + ) await vi.waitFor(() => { expect(settled, 'The call must wait for the actual approval coordinator.').toBe(false) expect(policy.listPendingTerminalApprovals()).toHaveLength(1) @@ -932,38 +2305,94 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and expect(policy.listPendingTerminalApprovals()).toHaveLength(1) expect(settled).toBe(false) if (ending === 'navigation') sender.emit('did-start-navigation') - else if (ending === 'stop') await service.cancelConversation({ conversationId: scope.conversationId }, invoke('cancelConversation')) - else policy.resolvePendingTerminalApproval({ approvalId: approval.approvalId, expectedRevision: approval.revision, approved: ending === 'approve' }) + else if (ending === 'stop') + await service.cancelConversation( + { conversationId: scope.conversationId }, + invoke('cancelConversation') + ) + else + policy.resolvePendingTerminalApproval({ + approvalId: approval.approvalId, + expectedRevision: approval.revision, + approved: ending === 'approve' + }) const outcome = await pending expect(policy.listPendingTerminalApprovals()).toEqual([]) - expect(() => policy.resolvePendingTerminalApproval({ approvalId: approval.approvalId, expectedRevision: approval.revision, approved: true })).toThrow('not found') + expect(() => + policy.resolvePendingTerminalApproval({ + approvalId: approval.approvalId, + expectedRevision: approval.revision, + approved: true + }) + ).toThrow('not found') if (ending === 'approve') { expect(outcome.status).toBe('fulfilled') if (outcome.status !== 'fulfilled') throw outcome.reason const result = outcome.value - if (method === 'chat') expect(result).toMatchObject({ content: 'The approved edit returned its actual SHA and snapshot.', metadata: { toolHistory: [expect.objectContaining({ toolName: name, status: 'completed' })] } }) - else expect(onData).toHaveBeenCalledWith(expect.objectContaining({ type: 'done', content: 'The approved edit returned its actual SHA and snapshot.' })) + if (method === 'chat') + expect(result).toMatchObject({ + content: 'The approved edit returned its actual SHA and snapshot.', + metadata: { + toolHistory: [expect.objectContaining({ toolName: name, status: 'completed' })] + } + }) + else + expect(onData).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'done', + content: 'The approved edit returned its actual SHA and snapshot.' + }) + ) expect(chat).toHaveBeenCalledTimes(2) const session = await store.getSession(route) - const results = (session?.eventLog ?? []).map(event => event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined).filter(action => action?.type === 'tool.result') + const results = (session?.eventLog ?? []) + .map( + (event) => + event.metadata?.agentAction as import('@shared/agent').ToolResultAction | undefined + ) + .filter((action) => action?.type === 'tool.result') expect(results).toHaveLength(1) - expect(results[0]!.payload).toMatchObject({ ok: true, toolName: name, metadata: expectedReceipt }) + expect(results[0]!.payload).toMatchObject({ + ok: true, + toolName: name, + metadata: expectedReceipt + }) expect(JSON.parse(results[0]!.payload.content!)).toMatchObject(expectedReceipt) - const history = method === 'chat' ? (result as LLMChatResp).metadata?.toolHistory : onData.mock.calls.find(([event]) => event.type === 'done')?.[0].metadata?.toolHistory - expect(history).toEqual([expect.objectContaining({ toolName: name, status: 'completed', metadata: expect.objectContaining(expectedReceipt) })]) + const history = + method === 'chat' + ? (result as LLMChatResp).metadata?.toolHistory + : onData.mock.calls.find(([event]) => event.type === 'done')?.[0].metadata?.toolHistory + expect(history).toEqual([ + expect.objectContaining({ + toolName: name, + status: 'completed', + metadata: expect.objectContaining(expectedReceipt) + }) + ]) await store.flush() const reopened = new AssistantSessionStore(path.join(h.data, 'sessions.json')) expect((await reopened.getSession(route))?.eventLog).toEqual(session!.eventLog) expect(await fs.readFile(file, 'utf8')).toBe(after) const snapshots = await fs.readdir(path.join(root, '.magicpot', 'tool-host', 'snapshots')) expect(snapshots).toHaveLength(1) - expect(await fs.readFile(path.join(root, '.magicpot', 'tool-host', 'snapshots', snapshots[0], 'content'), 'utf8')).toBe(before) + expect( + await fs.readFile( + path.join(root, '.magicpot', 'tool-host', 'snapshots', snapshots[0], 'content'), + 'utf8' + ) + ).toBe(before) } else { expect(chat).toHaveBeenCalledOnce() expect(await fs.readFile(file, 'utf8')).toBe(before) - await expect(fs.stat(path.join(root, '.magicpot'))).rejects.toMatchObject({ code: 'ENOENT' }) - const expectedError = ending === 'deny' ? 'Terminal execution was denied by the user.' - : ending === 'stop' ? 'Conversation cancelled by the user.' : 'Agent thread document or request ended.' + await expect(fs.stat(path.join(root, '.magicpot'))).rejects.toMatchObject({ + code: 'ENOENT' + }) + const expectedError = + ending === 'deny' + ? 'Terminal execution was denied by the user.' + : ending === 'stop' + ? 'Conversation cancelled by the user.' + : 'Agent thread document or request ended.' if (method === 'chat') { expect(outcome.status).toBe('rejected') if (outcome.status === 'rejected') { @@ -974,15 +2403,41 @@ describe('file edit via existing thread, actual runtime/kernel/registry/host and } else { expect(outcome.status).toBe('fulfilled') // Streaming reports errors via frames, not a thrown promise. if (outcome.status === 'fulfilled') expect(outcome.value).toBeUndefined() - const terminal = onData.mock.calls.map(([event]) => event).filter(event => event.type === 'done' || event.type === 'error') - expect(terminal.filter(event => event.type === 'done' && !['error', 'cancelled'].includes(event.finishReason ?? ''))).toEqual([]) - if (ending === 'deny') expect(terminal).toEqual([ - expect.objectContaining({ type: 'error', done: false, finishReason: 'error', error: expectedError, content: '' }), - expect.objectContaining({ type: 'done', done: true, finishReason: 'error', error: expectedError, content: '' }) - ]) - else if (ending === 'stop') expect(terminal).toEqual([ - expect.objectContaining({ type: 'done', done: true, finishReason: 'cancelled', content: '' }) - ]) + const terminal = onData.mock.calls + .map(([event]) => event) + .filter((event) => event.type === 'done' || event.type === 'error') + expect( + terminal.filter( + (event) => + event.type === 'done' && !['error', 'cancelled'].includes(event.finishReason ?? '') + ) + ).toEqual([]) + if (ending === 'deny') + expect(terminal).toEqual([ + expect.objectContaining({ + type: 'error', + done: false, + finishReason: 'error', + error: expectedError, + content: '' + }), + expect.objectContaining({ + type: 'done', + done: true, + finishReason: 'error', + error: expectedError, + content: '' + }) + ]) + else if (ending === 'stop') + expect(terminal).toEqual([ + expect.objectContaining({ + type: 'done', + done: true, + finishReason: 'cancelled', + content: '' + }) + ]) else expect(terminal).toEqual([]) // No terminal frame may target the replaced document. } } diff --git a/packages/app/src/main/api/agentThreadInteractions.test.ts b/packages/app/src/main/api/agentThreadInteractions.test.ts index baac69e00..f7ec14871 100644 --- a/packages/app/src/main/api/agentThreadInteractions.test.ts +++ b/packages/app/src/main/api/agentThreadInteractions.test.ts @@ -1,24 +1,59 @@ import { EventEmitter } from 'node:events' import type { LLMChatReq } from '@shared/api/svcLLMProxy' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentThreadInteractions, type AgentThreadInteractionChannel } from './agentThreadInteractions' -import { registerMagicAgentTrustedRouteBinding, clearMagicAgentTrustedRouteBindingsForTest } from '../magicAgentRuntime/trustedRouteBinding' +import { + AgentThreadInteractions, + type AgentThreadInteractionChannel +} from './agentThreadInteractions' +import { + registerMagicAgentTrustedRouteBinding, + clearMagicAgentTrustedRouteBindingsForTest +} from '../magicAgentRuntime/trustedRouteBinding' import { watchSenderDocument } from '@shared/api/createServer/senderDocumentWatch' const electron = vi.hoisted(() => ({ fromId: vi.fn(), parent: vi.fn() })) vi.mock('./agentThreadArchive', () => ({ agentThreadArchive: { search: async () => undefined } })) // A fake confined memory session: only the member End test below opens one. -const memoryHost = vi.hoisted(() => ({ callTool: vi.fn(async () => ({ content: '{"path":"./memory/facts.md"}' })) })) -vi.mock('./agentThreadMemoryFileHost', () => ({ createMemoryFileSession: () => ({ - listTools: () => ['memory.files.tree', 'memory.files.read', 'memory.files.grep'].map(name => ({ name, description: 'Memory namespace only.', inputSchema: { type: 'object', additionalProperties: false, required: ['path'], properties: { path: { type: 'string' } } } })), - callTool: memoryHost.callTool, close: () => undefined -}) })) +const memoryHost = vi.hoisted(() => ({ + callTool: vi.fn(async () => ({ content: '{"path":"./memory/facts.md"}' })) +})) +vi.mock('./agentThreadMemoryFileHost', () => ({ + createMemoryFileSession: () => ({ + listTools: () => + ['memory.files.tree', 'memory.files.read', 'memory.files.grep'].map((name) => ({ + name, + description: 'Memory namespace only.', + inputSchema: { + type: 'object', + additionalProperties: false, + required: ['path'], + properties: { path: { type: 'string' } } + } + })), + callTool: memoryHost.callTool, + close: () => undefined + }) +})) vi.mock('./agentThreadMemoryFileApproval', () => ({ approveMemoryFileWrite: vi.fn() })) -vi.mock('electron', () => ({ webContents: { fromId: electron.fromId }, BrowserWindow: { fromWebContents: electron.parent } })) -const route = { channel: 'canvas', scopeType: 'thread', scopeId: 'project', threadId: 'pane' } as const +vi.mock('electron', () => ({ + webContents: { fromId: electron.fromId }, + BrowserWindow: { fromWebContents: electron.parent } +})) +const route = { + channel: 'canvas', + scopeType: 'thread', + scopeId: 'project', + threadId: 'pane' +} as const const scope = { route, conversationId: 'conversation' } const url = 'file:///D:/app/index.html#/canvas?id=project' -const invocation = (method = 'chat') => ({ methodName: `svcLLMProxy.${method}`, senderId: 71, isMainFrame: true, senderUrl: url, frameUrl: url }) +const invocation = (method = 'chat') => ({ + methodName: `svcLLMProxy.${method}`, + senderId: 71, + isMainFrame: true, + senderUrl: url, + frameUrl: url +}) const question = { kind: 'ask_user', question: 'Which colour?' } as const let manager: AgentThreadInteractions let channel: AgentThreadInteractionChannel @@ -26,735 +61,2093 @@ let sender: EventEmitter & { id: number; isDestroyed: () => boolean; getURL: () beforeEach(() => { vi.useFakeTimers() manager = new AgentThreadInteractions() - sender = Object.assign(new EventEmitter(), { id: 71, isDestroyed: () => false, getURL: () => url }) + sender = Object.assign(new EventEmitter(), { + id: 71, + isDestroyed: () => false, + getURL: () => url + }) electron.fromId.mockReturnValue(sender) electron.parent.mockReturnValue({ isDestroyed: () => false, webContents: sender }) registerMagicAgentTrustedRouteBinding(71, route, { trustedUrl: url, trustedWebContents: sender }) channel = manager.create({ ...scope, messages: [] }, invocation())! }) -afterEach(() => { channel.dispose(); clearMagicAgentTrustedRouteBindingsForTest(); vi.useRealTimers(); vi.clearAllMocks() }) +afterEach(() => { + channel.dispose() + clearMagicAgentTrustedRouteBindingsForTest() + vi.useRealTimers() + vi.clearAllMocks() +}) const pending = () => manager.list(scope, invocation('listAgentInteractions')) -const respond = (interactionId: string, answer: Parameters[0]['answer']) => manager.resolve({ ...scope, interactionId, answer }, invocation('resolveAgentInteraction')) +const respond = ( + interactionId: string, + answer: Parameters[0]['answer'] +) => manager.resolve({ ...scope, interactionId, answer }, invocation('resolveAgentInteraction')) describe('local Agent thread interactions', () => { it('rejects original nonprimitive/oversize icons before JSON hooks, pending input or timers and validates the entire icon-only prompt', async () => { - const base = { kind: 'show_card' as const, title: 'Direct icon', actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] }, toJSON = vi.fn(() => '✓'), toString = vi.fn(() => '✓') - for (const icon of [null, false, 1, [], {}, ['✓'], Object('✓'), { toJSON, toString }, Object.assign(Object('✓'), { toJSON, toString }), 'x'.repeat(65), '😀'.repeat(33)]) { - const result = channel.request({ ...base, icon } as never, 17).then(() => 'resolved', () => 'rejected') - await Promise.resolve(); expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0); expect(await result).toBe('rejected') + const base = { + kind: 'show_card' as const, + title: 'Direct icon', + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + }, + toJSON = vi.fn(() => '✓'), + toString = vi.fn(() => '✓') + for (const icon of [ + null, + false, + 1, + [], + {}, + ['✓'], + Object('✓'), + { toJSON, toString }, + Object.assign(Object('✓'), { toJSON, toString }), + 'x'.repeat(65), + '😀'.repeat(33) + ]) { + const result = channel.request({ ...base, icon } as never, 17).then( + () => 'resolved', + () => 'rejected' + ) + await Promise.resolve() + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + expect(await result).toBe('rejected') } - expect(toJSON).not.toHaveBeenCalled(); expect(toString).not.toHaveBeenCalled() - for (const patch of [{ title: '😀'.repeat(101) }, { body: '😀'.repeat(2001) }, { subtitle: '😀'.repeat(101) }, { footer: '😀'.repeat(101) }, { fields: null }, { accent: 'error' }, { actions: [] }, { actions: [{ ...base.actions[0], label: '😀'.repeat(101) }, base.actions[1]] }, { actions: [base.actions[0], base.actions[0]] }, { actions: [{ ...base.actions[0], url: 'https://external.invalid' }] }, { actions: [{ ...base.actions[0], style: 'link' }] }, { actions: [{ ...base.actions[0], icon: '✓' }] }, { approved: true }, { ['__proto__']: { approved: true } }]) { - await expect(channel.request({ ...base, icon: '', ...patch } as never, 17)).rejects.toThrow('Invalid bounded') - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + expect(toJSON).not.toHaveBeenCalled() + expect(toString).not.toHaveBeenCalled() + for (const patch of [ + { title: '😀'.repeat(101) }, + { body: '😀'.repeat(2001) }, + { subtitle: '😀'.repeat(101) }, + { footer: '😀'.repeat(101) }, + { fields: null }, + { accent: 'error' }, + { actions: [] }, + { actions: [{ ...base.actions[0], label: '😀'.repeat(101) }, base.actions[1]] }, + { actions: [base.actions[0], base.actions[0]] }, + { actions: [{ ...base.actions[0], url: 'https://external.invalid' }] }, + { actions: [{ ...base.actions[0], style: 'link' }] }, + { actions: [{ ...base.actions[0], icon: '✓' }] }, + { approved: true }, + { ['__proto__']: { approved: true } } + ]) { + await expect(channel.request({ ...base, icon: '', ...patch } as never, 17)).rejects.toThrow( + 'Invalid bounded' + ) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) } }) it('keeps original raw icon context detached and ownundefined/inherited legacy omission separate from supplied-icon strict validation', async () => { for (const count of [1, 2, 4]) { - const base = { kind: 'show_card' as const, title: count === 1 ? 'Single already strict' : '😀'.repeat(101), actions: Array.from({ length: count }, (_, i) => ({ id: `a${i}`, label: 'A' })) } - for (const source of [{ ...base }, { ...base, icon: undefined }, Object.assign(Object.create({ icon: { toJSON: () => '✓' } }), base)]) { - const result = channel.request(source, 17), [item] = pending() - expect(item.prompt).toEqual(count > 1 && Object.hasOwn(source, 'icon') ? { ...base, icon: undefined } : base) + const base = { + kind: 'show_card' as const, + title: count === 1 ? 'Single already strict' : '😀'.repeat(101), + actions: Array.from({ length: count }, (_, i) => ({ id: `a${i}`, label: 'A' })) + } + for (const source of [ + { ...base }, + { ...base, icon: undefined }, + Object.assign(Object.create({ icon: { toJSON: () => '✓' } }), base) + ]) { + const result = channel.request(source, 17), + [item] = pending() + expect(item.prompt).toEqual( + count > 1 && Object.hasOwn(source, 'icon') ? { ...base, icon: undefined } : base + ) expect(Object.hasOwn(item.prompt, 'icon')).toBe(count > 1 && Object.hasOwn(source, 'icon')) - respond(item.id, { status: 'dismissed' }); expect(await result).toEqual({ status: 'dismissed' }); expect(vi.getTimerCount()).toBe(0) + respond(item.id, { status: 'dismissed' }) + expect(await result).toEqual({ status: 'dismissed' }) + expect(vi.getTimerCount()).toBe(0) } - if (count > 1) { await expect(channel.request({ ...base, icon: '' }, 17)).rejects.toThrow('Invalid bounded'); expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) } + if (count > 1) { + await expect(channel.request({ ...base, icon: '' }, 17)).rejects.toThrow('Invalid bounded') + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + } + } + const source = { + kind: 'show_card' as const, + title: 'Raw context not rewritten', + icon: '\u0001👩🏽‍💻\u202e', + subtitle: '', + footer: ' ', + accent: 'success' as const, + fields: [{ label: 'Status', value: 'Not approval' }], + actions: [ + { id: 'approve', label: 'Explicit feedback', style: 'primary' as const }, + { id: 'no', label: 'Other', style: 'secondary' as const } + ] + } + const expected = structuredClone(source), + result = channel.request(source, 17), + [item] = pending() + expect(item.prompt).toEqual(expected) + source.icon = 'source changed' + source.fields[0].value = 'source changed' + if (item.prompt.kind === 'show_card') { + item.prompt.icon = 'view changed' + item.prompt.actions[0].id = 'view changed' } - const source = { kind: 'show_card' as const, title: 'Raw context not rewritten', icon: '\u0001👩🏽‍💻\u202e', subtitle: '', footer: ' ', accent: 'success' as const, fields: [{ label: 'Status', value: 'Not approval' }], actions: [{ id: 'approve', label: 'Explicit feedback', style: 'primary' as const }, { id: 'no', label: 'Other', style: 'secondary' as const }] } - const expected = structuredClone(source), result = channel.request(source, 17), [item] = pending(); expect(item.prompt).toEqual(expected) - source.icon = 'source changed'; source.fields[0].value = 'source changed' - if (item.prompt.kind === 'show_card') { item.prompt.icon = 'view changed'; item.prompt.actions[0].id = 'view changed' } expect(pending()[0].prompt).toEqual(expected) - for (const answer of [{ status: 'answered', actionId: 'approve', icon: '✓' }, { status: 'dismissed', icon: '' }, { status: 'answered', actionId: 'approve', approved: true }, { status: 'answered', actionId: 'approve', style: 'primary' }, { status: 'answered', actionId: 'approve', values: {} }]) expect(() => respond(item.id, answer as never)).toThrow('Invalid') - respond(item.id, { status: 'answered', actionId: 'approve' }); expect(await result).toEqual({ status: 'answered', actionId: 'approve' }); expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + for (const answer of [ + { status: 'answered', actionId: 'approve', icon: '✓' }, + { status: 'dismissed', icon: '' }, + { status: 'answered', actionId: 'approve', approved: true }, + { status: 'answered', actionId: 'approve', style: 'primary' }, + { status: 'answered', actionId: 'approve', values: {} } + ]) + expect(() => respond(item.id, answer as never)).toThrow('Invalid') + respond(item.id, { status: 'answered', actionId: 'approve' }) + expect(await result).toEqual({ status: 'answered', actionId: 'approve' }) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) }) it('counts decorative icon, all contexts and styles in exact MAIN unit AND byte caps before pending/timer allocation', async () => { - const fields = [{ label: '', value: '\u0001'.repeat(1000) }, { label: '', value: '' }, { label: '', value: '' }] - const prompt = { kind: 'show_card' as const, title: 'Caps', icon: '\u0001'.repeat(64), subtitle: '\u0001'.repeat(200), footer: '\u0001'.repeat(200), accent: 'success' as const, body: '\u0001'.repeat(3700), fields, actions: [{ id: 'a', label: 'A', style: 'primary' as const }, { id: 'b', label: 'B', style: 'danger' as const }] }, remaining = 32768 - Buffer.byteLength(JSON.stringify(prompt), 'utf8') - expect(remaining).toBeGreaterThan(1000); expect(remaining).toBeLessThan(2000); fields[1].value = 'x'.repeat(1000); fields[2].value = 'x'.repeat(remaining - 1000) - expect(JSON.stringify(prompt).length).toBe(32768); const result = channel.request(prompt, 17), [item] = pending(); expect(item.prompt).toEqual(prompt) - respond(item.id, { status: 'dismissed' }); expect(await result).toEqual({ status: 'dismissed' }); fields[2].value += 'x' - await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded'); fields[2].value = fields[2].value.slice(2) + '漢' - expect(JSON.stringify(prompt).length).toBe(32768); expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32770); await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) - }) - it.each(['', '✓', '👩🏽‍💻'])('retains an owned detached icon-only choice and accepts only explicit offeredID, not icon authority %#', async icon => { - const source = { kind: 'show_card' as const, title: 'Decorative icon only', icon, actions: [{ id: 'approve', label: 'Feedback not approval' }] } - let settled = false - const result = channel.request(source, 17).then(value => { settled = true; return value }, () => 'rejected') - await Promise.resolve(); expect(settled).toBe(false) - const [item] = pending(); expect(item?.prompt).toEqual(source) - source.icon = 'changed-source'; expect(pending()[0].prompt).toMatchObject({ icon }) - expect(() => respond(item.id, { status: 'answered', actionId: 'approve', icon } as never)).toThrow('Invalid') - expect(pending()).toHaveLength(1) - respond(item.id, { status: 'answered', actionId: 'approve' }); expect(await result).toEqual({ status: 'answered', actionId: 'approve' }) - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + const fields = [ + { label: '', value: '\u0001'.repeat(1000) }, + { label: '', value: '' }, + { label: '', value: '' } + ] + const prompt = { + kind: 'show_card' as const, + title: 'Caps', + icon: '\u0001'.repeat(64), + subtitle: '\u0001'.repeat(200), + footer: '\u0001'.repeat(200), + accent: 'success' as const, + body: '\u0001'.repeat(3700), + fields, + actions: [ + { id: 'a', label: 'A', style: 'primary' as const }, + { id: 'b', label: 'B', style: 'danger' as const } + ] + }, + remaining = 32768 - Buffer.byteLength(JSON.stringify(prompt), 'utf8') + expect(remaining).toBeGreaterThan(1000) + expect(remaining).toBeLessThan(2000) + fields[1].value = 'x'.repeat(1000) + fields[2].value = 'x'.repeat(remaining - 1000) + expect(JSON.stringify(prompt).length).toBe(32768) + const result = channel.request(prompt, 17), + [item] = pending() + expect(item.prompt).toEqual(prompt) + respond(item.id, { status: 'dismissed' }) + expect(await result).toEqual({ status: 'dismissed' }) + fields[2].value += 'x' + await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') + fields[2].value = fields[2].value.slice(2) + '漢' + expect(JSON.stringify(prompt).length).toBe(32768) + expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32770) + await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) }) + it.each(['', '✓', '👩🏽‍💻'])( + 'retains an owned detached icon-only choice and accepts only explicit offeredID, not icon authority %#', + async (icon) => { + const source = { + kind: 'show_card' as const, + title: 'Decorative icon only', + icon, + actions: [{ id: 'approve', label: 'Feedback not approval' }] + } + let settled = false + const result = channel.request(source, 17).then( + (value) => { + settled = true + return value + }, + () => 'rejected' + ) + await Promise.resolve() + expect(settled).toBe(false) + const [item] = pending() + expect(item?.prompt).toEqual(source) + source.icon = 'changed-source' + expect(pending()[0].prompt).toMatchObject({ icon }) + expect(() => + respond(item.id, { status: 'answered', actionId: 'approve', icon } as never) + ).toThrow('Invalid') + expect(pending()).toHaveLength(1) + respond(item.id, { status: 'answered', actionId: 'approve' }) + expect(await result).toEqual({ status: 'answered', actionId: 'approve' }) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + } + ) it('rejects raw style coercion before JSON hooks, pending retention and timers while validating style-only whole prompts', async () => { - const base = { kind: 'show_card' as const, title: 'Literal only', actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] } - const toJSON = vi.fn(() => 'primary'), toString = vi.fn(() => 'primary') - for (const style of [null, 1, false, [], {}, ['primary'], Object('primary'), { toJSON, toString }, '', 'link', 'error', 'Primary', 'primary ', '#f00', 'url(https://external.invalid)', '__proto__', 'constructor']) { - const outcome = channel.request({ ...base, actions: [{ ...base.actions[0], style }, base.actions[1]] } as never, 17).then(value => value, () => 'rejected') - await Promise.resolve(); expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0); expect(await outcome).toBe('rejected') + const base = { + kind: 'show_card' as const, + title: 'Literal only', + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + } + const toJSON = vi.fn(() => 'primary'), + toString = vi.fn(() => 'primary') + for (const style of [ + null, + 1, + false, + [], + {}, + ['primary'], + Object('primary'), + { toJSON, toString }, + '', + 'link', + 'error', + 'Primary', + 'primary ', + '#f00', + 'url(https://external.invalid)', + '__proto__', + 'constructor' + ]) { + const outcome = channel + .request( + { ...base, actions: [{ ...base.actions[0], style }, base.actions[1]] } as never, + 17 + ) + .then( + (value) => value, + () => 'rejected' + ) + await Promise.resolve() + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + expect(await outcome).toBe('rejected') } - expect(toJSON).not.toHaveBeenCalled(); expect(toString).not.toHaveBeenCalled() + expect(toJSON).not.toHaveBeenCalled() + expect(toString).not.toHaveBeenCalled() const actions = [{ ...base.actions[0], style: 'secondary' }, base.actions[1]] - for (const patch of [{ title: '😀'.repeat(101) }, { body: '😀'.repeat(2001) }, { actions: [{ ...actions[0], label: '😀'.repeat(101) }, actions[1]] }, { actions: [actions[0], actions[0]] }, { actions: [{ ...actions[0], url: 'https://external.invalid' }] }, { actions: [{ ...actions[0], variant: 'contained' }] }, { style: 'primary' }, { approved: true }, { fields: null }, { subtitle: null }, { footer: null }, { accent: 'error' }]) { - await expect(channel.request({ ...base, actions, ...patch } as never, 17)).rejects.toThrow('Invalid bounded') - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + for (const patch of [ + { title: '😀'.repeat(101) }, + { body: '😀'.repeat(2001) }, + { actions: [{ ...actions[0], label: '😀'.repeat(101) }, actions[1]] }, + { actions: [actions[0], actions[0]] }, + { actions: [{ ...actions[0], url: 'https://external.invalid' }] }, + { actions: [{ ...actions[0], variant: 'contained' }] }, + { style: 'primary' }, + { approved: true }, + { fields: null }, + { subtitle: null }, + { footer: null }, + { accent: 'error' } + ]) { + await expect(channel.request({ ...base, actions, ...patch } as never, 17)).rejects.toThrow( + 'Invalid bounded' + ) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) } }) it('ignores nested inherited style and omits raw ownundefined without tightening old bare2–4 admission', async () => { - for (const count of [1, 2, 4]) for (const own of [false, true]) { - const actions = Array.from({ length: count }, (_, i) => Object.assign(Object.create(own ? null : { style: 'link' }), { id: `a${i}`, label: 'A' }, own ? { style: undefined } : {})) - const source = { kind: 'show_card' as const, title: count > 1 ? '😀'.repeat(101) : 'Single strict', actions } - const waiting = channel.request(source, 17), [item] = pending() - expect(item.prompt).toEqual({ ...source, actions: actions.map(({ id, label }) => ({ id, label })) }) - respond(item.id, { status: 'dismissed' }); expect(await waiting).toEqual({ status: 'dismissed' }); expect(vi.getTimerCount()).toBe(0) - } + for (const count of [1, 2, 4]) + for (const own of [false, true]) { + const actions = Array.from({ length: count }, (_, i) => + Object.assign( + Object.create(own ? null : { style: 'link' }), + { id: `a${i}`, label: 'A' }, + own ? { style: undefined } : {} + ) + ) + const source = { + kind: 'show_card' as const, + title: count > 1 ? '😀'.repeat(101) : 'Single strict', + actions + } + const waiting = channel.request(source, 17), + [item] = pending() + expect(item.prompt).toEqual({ + ...source, + actions: actions.map(({ id, label }) => ({ id, label })) + }) + respond(item.id, { status: 'dismissed' }) + expect(await waiting).toEqual({ status: 'dismissed' }) + expect(vi.getTimerCount()).toBe(0) + } }) it('includes nested styles plus all optional context in exact direct-MAIN unit AND UTF8 caps before a timer', async () => { - const fields = [{ label: '', value: '\u0001'.repeat(1000) }, { label: '', value: '' }, { label: '', value: '' }] - const prompt = { kind: 'show_card' as const, title: 'Caps', subtitle: '\u0001'.repeat(200), footer: '\u0001'.repeat(200), accent: 'success' as const, body: '\u0001'.repeat(3800), fields, actions: [{ id: 'a', label: 'A', style: 'primary' as const }, { id: 'b', label: 'B', style: 'danger' as const }] } + const fields = [ + { label: '', value: '\u0001'.repeat(1000) }, + { label: '', value: '' }, + { label: '', value: '' } + ] + const prompt = { + kind: 'show_card' as const, + title: 'Caps', + subtitle: '\u0001'.repeat(200), + footer: '\u0001'.repeat(200), + accent: 'success' as const, + body: '\u0001'.repeat(3800), + fields, + actions: [ + { id: 'a', label: 'A', style: 'primary' as const }, + { id: 'b', label: 'B', style: 'danger' as const } + ] + } const remaining = 32768 - Buffer.byteLength(JSON.stringify(prompt), 'utf8') - expect(remaining).toBeGreaterThan(1000); expect(remaining).toBeLessThan(2000) - fields[1].value = 'x'.repeat(1000); fields[2].value = 'x'.repeat(remaining - 1000) + expect(remaining).toBeGreaterThan(1000) + expect(remaining).toBeLessThan(2000) + fields[1].value = 'x'.repeat(1000) + fields[2].value = 'x'.repeat(remaining - 1000) expect(JSON.stringify(prompt).length).toBe(32768) - const waiting = channel.request(prompt, 17), [item] = pending(); expect(item.prompt).toEqual(prompt) - respond(item.id, { status: 'dismissed' }); expect(await waiting).toEqual({ status: 'dismissed' }) - fields[2].value += 'x'; await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') + const waiting = channel.request(prompt, 17), + [item] = pending() + expect(item.prompt).toEqual(prompt) + respond(item.id, { status: 'dismissed' }) + expect(await waiting).toEqual({ status: 'dismissed' }) + fields[2].value += 'x' + await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') fields[2].value = fields[2].value.slice(2) + '漢' - expect(JSON.stringify(prompt).length).toBe(32768); expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32770) - await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded'); expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) - }) - it.each(['primary', 'secondary', 'danger'])('validates and retains a detached styled action without approval or autoanswer style=%s', async style => { - const prompt = { kind: 'show_card' as const, title: 'Explicit feedback only', actions: [{ id: 'approve', label: 'Feedback', style }] } - let settled = false - const waiting = channel.request(prompt as never, 17).then(value => { settled = true; return value }, () => 'rejected') - await Promise.resolve(); expect(settled).toBe(false) - const [item] = pending(); expect(item?.prompt).toEqual(prompt) - prompt.actions[0].style = 'changed-source' - expect(pending()[0].prompt).toMatchObject({ actions: [{ id: 'approve', label: 'Feedback', style }] }) - expect(() => respond(item.id, { status: 'answered', actionId: 'approve', style } as never)).toThrow('Invalid') - expect(pending()).toHaveLength(1) - respond(item.id, { status: 'answered', actionId: 'approve' }); expect(await waiting).toEqual({ status: 'answered', actionId: 'approve' }) - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + expect(JSON.stringify(prompt).length).toBe(32768) + expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32770) + await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) }) + it.each(['primary', 'secondary', 'danger'])( + 'validates and retains a detached styled action without approval or autoanswer style=%s', + async (style) => { + const prompt = { + kind: 'show_card' as const, + title: 'Explicit feedback only', + actions: [{ id: 'approve', label: 'Feedback', style }] + } + let settled = false + const waiting = channel.request(prompt as never, 17).then( + (value) => { + settled = true + return value + }, + () => 'rejected' + ) + await Promise.resolve() + expect(settled).toBe(false) + const [item] = pending() + expect(item?.prompt).toEqual(prompt) + prompt.actions[0].style = 'changed-source' + expect(pending()[0].prompt).toMatchObject({ + actions: [{ id: 'approve', label: 'Feedback', style }] + }) + expect(() => + respond(item.id, { status: 'answered', actionId: 'approve', style } as never) + ).toThrow('Invalid') + expect(pending()).toHaveLength(1) + respond(item.id, { status: 'answered', actionId: 'approve' }) + expect(await waiting).toEqual({ status: 'answered', actionId: 'approve' }) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + } + ) it('rejects raw accent JSON coercion without invoking user hooks or retaining timers', async () => { - const toJSON = vi.fn(() => 'primary'), toString = vi.fn(() => 'primary') - const accent = { toJSON, toString }, prompt = { kind: 'show_card', title: 'No coercion', accent, actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] } + const toJSON = vi.fn(() => 'primary'), + toString = vi.fn(() => 'primary') + const accent = { toJSON, toString }, + prompt = { + kind: 'show_card', + title: 'No coercion', + accent, + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + } await expect(channel.request(prompt as never, 17)).rejects.toThrow('Invalid bounded') - expect(toJSON).not.toHaveBeenCalled(); expect(toString).not.toHaveBeenCalled() - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + expect(toJSON).not.toHaveBeenCalled() + expect(toString).not.toHaveBeenCalled() + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) }) it('validates direct-MAIN accent-only context before retaining a prompt/timer, preserving deliberate legacy no-context handling', async () => { - const base = { kind: 'show_card' as const, title: 'Visual only', actions: [{ id: 'approve', label: 'Feedback' }, { id: 'no', label: 'Other' }] } - for (const accent of [null, false, 1, [], {}, ['primary'], Object('primary'), { toJSON: () => 'primary' }, { toString: () => 'primary' }, '', 'error', 'Primary', '#f00', 'url(https://external.invalid)', '__proto__', 'constructor', 'toString']) { - const outcome = channel.request({ ...base, accent } as never, 17).then(value => value, () => 'rejected') + const base = { + kind: 'show_card' as const, + title: 'Visual only', + actions: [ + { id: 'approve', label: 'Feedback' }, + { id: 'no', label: 'Other' } + ] + } + for (const accent of [ + null, + false, + 1, + [], + {}, + ['primary'], + Object('primary'), + { toJSON: () => 'primary' }, + { toString: () => 'primary' }, + '', + 'error', + 'Primary', + '#f00', + 'url(https://external.invalid)', + '__proto__', + 'constructor', + 'toString' + ]) { + const outcome = channel.request({ ...base, accent } as never, 17).then( + (value) => value, + () => 'rejected' + ) await Promise.resolve() - expect(pending(), `Invalid raw accent type=${typeof accent}`).toEqual([]); expect(vi.getTimerCount()).toBe(0) + expect(pending(), `Invalid raw accent type=${typeof accent}`).toEqual([]) + expect(vi.getTimerCount()).toBe(0) expect(await outcome).toBe('rejected') } - for (const patch of [{ title: '😀'.repeat(101) }, { body: '😀'.repeat(2001) }, { subtitle: null }, { footer: null }, { fields: null }, { actions: [] }, { actions: [{ id: 'approve', label: '😀'.repeat(101) }, base.actions[1]] }, { actions: [base.actions[0], base.actions[0]] }, { actions: [{ ...base.actions[0], style: { color: 'red' } }, base.actions[1]] }, { approved: true }, { style: { color: 'red' } }, { className: 'accent-primary' }, { ['__proto__']: { approved: true } }]) { - await expect(channel.request({ ...base, accent: 'neutral', ...patch } as never, 17)).rejects.toThrow('Invalid bounded') - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + for (const patch of [ + { title: '😀'.repeat(101) }, + { body: '😀'.repeat(2001) }, + { subtitle: null }, + { footer: null }, + { fields: null }, + { actions: [] }, + { actions: [{ id: 'approve', label: '😀'.repeat(101) }, base.actions[1]] }, + { actions: [base.actions[0], base.actions[0]] }, + { actions: [{ ...base.actions[0], style: { color: 'red' } }, base.actions[1]] }, + { approved: true }, + { style: { color: 'red' } }, + { className: 'accent-primary' }, + { ['__proto__']: { approved: true } } + ]) { + await expect( + channel.request({ ...base, accent: 'neutral', ...patch } as never, 17) + ).rejects.toThrow('Invalid bounded') + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) } - for (const source of [{ ...base, accent: undefined }, Object.assign(Object.create({ accent: 'error' }), base), { ...base, title: '😀'.repeat(101), accent: undefined }]) { - const waiting = channel.request(source, 17), [item] = pending() + for (const source of [ + { ...base, accent: undefined }, + Object.assign(Object.create({ accent: 'error' }), base), + { ...base, title: '😀'.repeat(101), accent: undefined } + ]) { + const waiting = channel.request(source, 17), + [item] = pending() expect(Object.hasOwn(item.prompt, 'accent')).toBe(Object.hasOwn(source, 'accent')) - respond(item.id, { status: 'dismissed' }); expect(await waiting).toEqual({ status: 'dismissed' }) - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + respond(item.id, { status: 'dismissed' }) + expect(await waiting).toEqual({ status: 'dismissed' }) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) } }) it('includes all context plus accent in exact direct-MAIN JSON unit/byte caps without creating timers on overflow', async () => { - const fields = [{ label: '', value: '\u0001'.repeat(1000) }, { label: '', value: '' }, { label: '', value: '' }] - const prompt = { kind: 'show_card' as const, title: 'Caps', accent: 'warning' as const, subtitle: '\u0001'.repeat(200), footer: '\u0001'.repeat(200), body: '\u0001'.repeat(3800), fields, actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] } + const fields = [ + { label: '', value: '\u0001'.repeat(1000) }, + { label: '', value: '' }, + { label: '', value: '' } + ] + const prompt = { + kind: 'show_card' as const, + title: 'Caps', + accent: 'warning' as const, + subtitle: '\u0001'.repeat(200), + footer: '\u0001'.repeat(200), + body: '\u0001'.repeat(3800), + fields, + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + } const remaining = 32768 - Buffer.byteLength(JSON.stringify(prompt), 'utf8') - fields[1].value = 'x'.repeat(1000); fields[2].value = 'x'.repeat(remaining - 1000) - expect(JSON.stringify(prompt).length).toBe(32768); expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32768) - const waiting = channel.request(prompt, 17), [item] = pending(); expect(item.prompt).toEqual(prompt) - respond(item.id, { status: 'dismissed' }); expect(await waiting).toEqual({ status: 'dismissed' }) - fields[2].value += 'x'; await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') + fields[1].value = 'x'.repeat(1000) + fields[2].value = 'x'.repeat(remaining - 1000) + expect(JSON.stringify(prompt).length).toBe(32768) + expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32768) + const waiting = channel.request(prompt, 17), + [item] = pending() + expect(item.prompt).toEqual(prompt) + respond(item.id, { status: 'dismissed' }) + expect(await waiting).toEqual({ status: 'dismissed' }) + fields[2].value += 'x' + await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') fields[2].value = fields[2].value.slice(2) + '漢' - expect(JSON.stringify(prompt).length).toBe(32768); expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32770) + expect(JSON.stringify(prompt).length).toBe(32768) + expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32770) await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) - }) - it.each([false, true])('keeps accent as detached untrusted provider context until owned explicit feedback, not approval othercontext=%s', async withContext => { - const { createAgentThreadToolProvider } = await import('./agentThreadTools') - const provider = createAgentThreadToolProvider({ route, messages: [], assertInvocation: vi.fn(), listVisibleTools: () => [], interactions: channel }) - const actions = [{ id: 'approve', label: 'Feedback only' }, { id: 'no', label: 'Other' }] - const args = { title: 'Visual only', accent: 'success', actions, ...(withContext ? { subtitle: '', footer: 'No approval', fields: [{ label: 'State', value: 'No grant' }] } : {}) } - let settled = false - const result = provider.callTool('show_card', args, { route, runId: 'accent-wait' }).then(value => { settled = true; return value }) - await Promise.resolve(); expect(settled).toBe(false) - const [item] = pending(); expect(item.prompt).toEqual({ kind: 'show_card', ...args }) - args.accent = 'changed-source'; actions[0].id = 'changed-source' - Reflect.set(item.prompt, 'accent', 'changed-view'); if (item.prompt.kind === 'show_card') item.prompt.actions[0].id = 'changed-view' - expect(pending()[0].prompt).toMatchObject({ accent: 'success', actions: [{ id: 'approve' }, { id: 'no' }] }) - for (const answer of [{ status: 'answered', actionId: 'approve', accent: 'success' }, { status: 'answered', actionId: 'approve', approved: true }, { status: 'answered', actionId: 'approve', values: {} }, { status: 'dismissed', accent: 'neutral' }, { status: 'answered', actionId: 'changed-source' }]) expect(() => respond(item.id, answer as never)).toThrow('Invalid') - expect(pending()).toHaveLength(1); expect(settled).toBe(false) - respond(item.id, { status: 'answered', actionId: 'approve' }); expect(JSON.parse((await result).content)).toEqual({ status: 'answered', actionId: 'approve' }) - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) - expect(() => respond(item.id, { status: 'answered', actionId: 'approve' })).toThrow('not active') - }) - it.each([1, 2])('treats a supplied accent as strict direct-MAIN prompt context before pending/timer, never an answer actions=%s', async count => { - const actions = [{ id: 'approve', label: 'Feedback only' }, { id: 'no', label: 'Other feedback' }].slice(0, count) - const source = { kind: 'show_card' as const, title: 'Visual context', accent: 'success', actions } - const waiting = channel.request(source as never, 17).then(value => value, () => 'rejected'), [item] = pending() - expect(item.prompt).toEqual(source); source.accent = 'changed-source' - if (item.prompt.kind === 'show_card') Reflect.set(item.prompt, 'accent', 'changed-view') - expect(pending()[0].prompt).toMatchObject({ accent: 'success' }) - expect(() => respond(item.id, { status: 'answered', actionId: 'approve', ...{ accent: 'success' } })).toThrow('Invalid') - respond(item.id, { status: 'dismissed' }); expect(await waiting).toEqual({ status: 'dismissed' }) - const invalid = channel.request({ kind: 'show_card', title: 'Visual context', ...{ accent: 'error' }, actions } as never, 17).then(() => 'resolved', () => 'rejected') - await Promise.resolve() - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) - expect(await invalid).toBe('rejected') - }) - it.each([false, true])('retains a detached owned footer with optional context and rejects footer/values/approval answers fields=%s', async withContext => { - const { createAgentThreadToolProvider } = await import('./agentThreadTools') - const provider = createAgentThreadToolProvider({ route, messages: [], assertInvocation: vi.fn(), listVisibleTools: () => [], interactions: channel }) - const actions = [{ id: 'approve', label: 'Feedback only' }, { id: 'no', label: 'Other feedback' }] - const args = { title: 'Owned footer', footer: 'Closing context, not authorization', actions, ...(withContext ? { subtitle: 'Smaller context', fields: [{ label: 'Status', value: 'Read only' }] } : {}) } - const result = provider.callTool('show_card', args, { route, runId: 'footer-wait' }) - const [item] = pending(); expect(item.prompt).toEqual({ kind: 'show_card', ...args }) - args.footer = 'MUTATED SOURCE'; actions[0].id = 'changed-source' - if (item.prompt.kind === 'show_card') { item.prompt.footer = 'MUTATED VIEW'; item.prompt.actions[0].id = 'changed-view' } - expect(pending()[0].prompt).toMatchObject({ footer: 'Closing context, not authorization', actions: [{ id: 'approve' }, { id: 'no' }] }) - for (const answer of [{ status: 'answered', actionId: 'approve', footer: 'Extra context' }, { status: 'answered', actionId: 'approve', approved: true }, { status: 'answered', actionId: 'approve', values: {} }, { status: 'answered', actionId: 'changed-source' }, { status: 'dismissed', footer: '' }]) expect(() => respond(item.id, answer as never)).toThrow('Invalid') - expect(pending()).toHaveLength(1) - respond(item.id, { status: 'answered', actionId: 'approve' }) - expect(JSON.parse((await result).content)).toEqual({ status: 'answered', actionId: 'approve' }) - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) }) + it.each([false, true])( + 'keeps accent as detached untrusted provider context until owned explicit feedback, not approval othercontext=%s', + async (withContext) => { + const { createAgentThreadToolProvider } = await import('./agentThreadTools') + const provider = createAgentThreadToolProvider({ + route, + messages: [], + assertInvocation: vi.fn(), + listVisibleTools: () => [], + interactions: channel + }) + const actions = [ + { id: 'approve', label: 'Feedback only' }, + { id: 'no', label: 'Other' } + ] + const args = { + title: 'Visual only', + accent: 'success', + actions, + ...(withContext + ? { subtitle: '', footer: 'No approval', fields: [{ label: 'State', value: 'No grant' }] } + : {}) + } + let settled = false + const result = provider + .callTool('show_card', args, { route, runId: 'accent-wait' }) + .then((value) => { + settled = true + return value + }) + await Promise.resolve() + expect(settled).toBe(false) + const [item] = pending() + expect(item.prompt).toEqual({ kind: 'show_card', ...args }) + args.accent = 'changed-source' + actions[0].id = 'changed-source' + Reflect.set(item.prompt, 'accent', 'changed-view') + if (item.prompt.kind === 'show_card') item.prompt.actions[0].id = 'changed-view' + expect(pending()[0].prompt).toMatchObject({ + accent: 'success', + actions: [{ id: 'approve' }, { id: 'no' }] + }) + for (const answer of [ + { status: 'answered', actionId: 'approve', accent: 'success' }, + { status: 'answered', actionId: 'approve', approved: true }, + { status: 'answered', actionId: 'approve', values: {} }, + { status: 'dismissed', accent: 'neutral' }, + { status: 'answered', actionId: 'changed-source' } + ]) + expect(() => respond(item.id, answer as never)).toThrow('Invalid') + expect(pending()).toHaveLength(1) + expect(settled).toBe(false) + respond(item.id, { status: 'answered', actionId: 'approve' }) + expect(JSON.parse((await result).content)).toEqual({ + status: 'answered', + actionId: 'approve' + }) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + expect(() => respond(item.id, { status: 'answered', actionId: 'approve' })).toThrow( + 'not active' + ) + } + ) + it.each([1, 2])( + 'treats a supplied accent as strict direct-MAIN prompt context before pending/timer, never an answer actions=%s', + async (count) => { + const actions = [ + { id: 'approve', label: 'Feedback only' }, + { id: 'no', label: 'Other feedback' } + ].slice(0, count) + const source = { + kind: 'show_card' as const, + title: 'Visual context', + accent: 'success', + actions + } + const waiting = channel.request(source as never, 17).then( + (value) => value, + () => 'rejected' + ), + [item] = pending() + expect(item.prompt).toEqual(source) + source.accent = 'changed-source' + if (item.prompt.kind === 'show_card') Reflect.set(item.prompt, 'accent', 'changed-view') + expect(pending()[0].prompt).toMatchObject({ accent: 'success' }) + expect(() => + respond(item.id, { status: 'answered', actionId: 'approve', ...{ accent: 'success' } }) + ).toThrow('Invalid') + respond(item.id, { status: 'dismissed' }) + expect(await waiting).toEqual({ status: 'dismissed' }) + const invalid = channel + .request( + { kind: 'show_card', title: 'Visual context', ...{ accent: 'error' }, actions } as never, + 17 + ) + .then( + () => 'resolved', + () => 'rejected' + ) + await Promise.resolve() + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + expect(await invalid).toBe('rejected') + } + ) + it.each([false, true])( + 'retains a detached owned footer with optional context and rejects footer/values/approval answers fields=%s', + async (withContext) => { + const { createAgentThreadToolProvider } = await import('./agentThreadTools') + const provider = createAgentThreadToolProvider({ + route, + messages: [], + assertInvocation: vi.fn(), + listVisibleTools: () => [], + interactions: channel + }) + const actions = [ + { id: 'approve', label: 'Feedback only' }, + { id: 'no', label: 'Other feedback' } + ] + const args = { + title: 'Owned footer', + footer: 'Closing context, not authorization', + actions, + ...(withContext + ? { subtitle: 'Smaller context', fields: [{ label: 'Status', value: 'Read only' }] } + : {}) + } + const result = provider.callTool('show_card', args, { route, runId: 'footer-wait' }) + const [item] = pending() + expect(item.prompt).toEqual({ kind: 'show_card', ...args }) + args.footer = 'MUTATED SOURCE' + actions[0].id = 'changed-source' + if (item.prompt.kind === 'show_card') { + item.prompt.footer = 'MUTATED VIEW' + item.prompt.actions[0].id = 'changed-view' + } + expect(pending()[0].prompt).toMatchObject({ + footer: 'Closing context, not authorization', + actions: [{ id: 'approve' }, { id: 'no' }] + }) + for (const answer of [ + { status: 'answered', actionId: 'approve', footer: 'Extra context' }, + { status: 'answered', actionId: 'approve', approved: true }, + { status: 'answered', actionId: 'approve', values: {} }, + { status: 'answered', actionId: 'changed-source' }, + { status: 'dismissed', footer: '' } + ]) + expect(() => respond(item.id, answer as never)).toThrow('Invalid') + expect(pending()).toHaveLength(1) + respond(item.id, { status: 'answered', actionId: 'approve' }) + expect(JSON.parse((await result).content)).toEqual({ + status: 'answered', + actionId: 'approve' + }) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + } + ) it('validates direct MAIN footer-only context before retention/timer, keeping absent/undefined/inherited compatibility', async () => { - const base = { kind: 'show_card' as const, title: 'Direct footer', actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] } - for (const patch of [{ footer: null }, { footer: false }, { footer: 1 }, { footer: {} }, { footer: [] }, { footer: ['text'] }, { footer: 'x'.repeat(201) }, { footer: '😀'.repeat(101) }, { footer: '', title: '😀'.repeat(101) }, { footer: '', body: '😀'.repeat(2001) }, { footer: '', actions: [] }, { footer: '', actions: [{ id: 'a', label: '😀'.repeat(101) }, base.actions[1]] }, { footer: '', approved: true }, { footer: '', fields: null }, { footer: '', actions: [{ ...base.actions[0], style: 'link', url: 'https://external.invalid' }, base.actions[1]] }, { footer: '', ['__proto__']: { approved: true } }]) { - await expect(channel.request({ ...base, ...patch } as never, 17)).rejects.toThrow('Invalid bounded') - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) - } - for (const prompt of [{ ...base, footer: '' }, { ...base, footer: ' ' }, { ...base, footer: '😀'.repeat(100) }, { ...base, footer: undefined }, Object.assign(Object.create({ footer: 'INHERITED_IGNORE' }), base)]) { - const result = channel.request(prompt, 17), [item] = pending() - if (Object.hasOwn(prompt, 'footer') && prompt.footer !== undefined) expect(item.prompt).toMatchObject({ footer: prompt.footer }) + const base = { + kind: 'show_card' as const, + title: 'Direct footer', + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + } + for (const patch of [ + { footer: null }, + { footer: false }, + { footer: 1 }, + { footer: {} }, + { footer: [] }, + { footer: ['text'] }, + { footer: 'x'.repeat(201) }, + { footer: '😀'.repeat(101) }, + { footer: '', title: '😀'.repeat(101) }, + { footer: '', body: '😀'.repeat(2001) }, + { footer: '', actions: [] }, + { footer: '', actions: [{ id: 'a', label: '😀'.repeat(101) }, base.actions[1]] }, + { footer: '', approved: true }, + { footer: '', fields: null }, + { + footer: '', + actions: [ + { ...base.actions[0], style: 'link', url: 'https://external.invalid' }, + base.actions[1] + ] + }, + { footer: '', ['__proto__']: { approved: true } } + ]) { + await expect(channel.request({ ...base, ...patch } as never, 17)).rejects.toThrow( + 'Invalid bounded' + ) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + } + for (const prompt of [ + { ...base, footer: '' }, + { ...base, footer: ' ' }, + { ...base, footer: '😀'.repeat(100) }, + { ...base, footer: undefined }, + Object.assign(Object.create({ footer: 'INHERITED_IGNORE' }), base) + ]) { + const result = channel.request(prompt, 17), + [item] = pending() + if (Object.hasOwn(prompt, 'footer') && prompt.footer !== undefined) + expect(item.prompt).toMatchObject({ footer: prompt.footer }) else expect(Object.hasOwn(item.prompt, 'footer')).toBe(Object.hasOwn(prompt, 'footer')) - respond(item.id, { status: 'dismissed' }); expect(await result).toEqual({ status: 'dismissed' }) - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + respond(item.id, { status: 'dismissed' }) + expect(await result).toEqual({ status: 'dismissed' }) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) } }) it('includes footer plus subtitle in exact direct-MAIN serialized units/bytes before creating a timer', async () => { - const fields = [{ label: '', value: '\u0001'.repeat(1000) }, { label: '', value: '' }, { label: '', value: '' }] - const prompt = { kind: 'show_card' as const, title: 'Footer', subtitle: '\u0001'.repeat(200), footer: '\u0001'.repeat(200), body: '\u0001'.repeat(3800), fields, actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] } + const fields = [ + { label: '', value: '\u0001'.repeat(1000) }, + { label: '', value: '' }, + { label: '', value: '' } + ] + const prompt = { + kind: 'show_card' as const, + title: 'Footer', + subtitle: '\u0001'.repeat(200), + footer: '\u0001'.repeat(200), + body: '\u0001'.repeat(3800), + fields, + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + } const remaining = 32768 - Buffer.byteLength(JSON.stringify(prompt), 'utf8') - fields[1].value = 'x'.repeat(1000); fields[2].value = 'x'.repeat(remaining - 1000) + fields[1].value = 'x'.repeat(1000) + fields[2].value = 'x'.repeat(remaining - 1000) expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32768) - const result = channel.request(prompt, 17), [item] = pending(); expect(item.prompt).toEqual(prompt) - respond(item.id, { status: 'dismissed' }); expect(await result).toEqual({ status: 'dismissed' }) - fields[2].value += 'x'; await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') + const result = channel.request(prompt, 17), + [item] = pending() + expect(item.prompt).toEqual(prompt) + respond(item.id, { status: 'dismissed' }) + expect(await result).toEqual({ status: 'dismissed' }) + fields[2].value += 'x' + await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') fields[2].value = fields[2].value.slice(2) + '漢' - expect(JSON.stringify(prompt).length).toBe(32768); expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32770) + expect(JSON.stringify(prompt).length).toBe(32768) + expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32770) await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) - }) - it.each(['bare', 'fields', 'subtitle', 'both'] as const)('keeps a lone choice pending until its owned exact ID and detaches all context=%s', async variant => { - const { createAgentThreadToolProvider } = await import('./agentThreadTools') - const provider = createAgentThreadToolProvider({ route, messages: [], assertInvocation: vi.fn(), listVisibleTools: () => [], interactions: channel }) - const actions = [{ id: 'approve', label: 'Conversation only' }] - const args = { title: 'Explicit lone button', actions, - ...(['fields', 'both'].includes(variant) ? { fields: [{ label: 'Status', value: 'Read only' }] } : {}), - ...(['subtitle', 'both'].includes(variant) ? { subtitle: 'Not execution permission' } : {}) } - let settled = false - const outcome = provider.callTool('show_card', args, { route, runId: 'single-wait' }).then(value => { settled = true; return value }) - await Promise.resolve() - expect(settled).toBe(false); expect(vi.getTimerCount()).toBe(1) - const [item] = pending(); expect(item.prompt).toEqual({ kind: 'show_card', ...args }) - actions[0].id = 'changed-source' - if (item.prompt.kind === 'show_card') { item.prompt.actions[0].id = 'changed-view'; if (item.prompt.fields) item.prompt.fields[0].value = 'changed-field' } - expect(pending()[0].prompt).toMatchObject({ actions: [{ id: 'approve', label: 'Conversation only' }] }) - for (const answer of [{ status: 'answered', actionId: 'changed-source' }, { status: 'answered', actionId: 'approve', approved: true }, { status: 'answered', actionId: 'approve', values: {} }, { status: 'answered', actionId: 'approve', subtitle: 'Not an answer' }, { status: 'answered', text: 'approve' }]) expect(() => respond(item.id, answer as never)).toThrow('Invalid') - expect(pending()).toHaveLength(1); expect(settled).toBe(false) - respond(item.id, { status: 'answered', actionId: 'approve' }) - expect(JSON.parse((await outcome).content)).toEqual({ status: 'answered', actionId: 'approve' }) - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) - expect(() => respond(item.id, { status: 'answered', actionId: 'approve' })).toThrow('not active') + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) }) + it.each(['bare', 'fields', 'subtitle', 'both'] as const)( + 'keeps a lone choice pending until its owned exact ID and detaches all context=%s', + async (variant) => { + const { createAgentThreadToolProvider } = await import('./agentThreadTools') + const provider = createAgentThreadToolProvider({ + route, + messages: [], + assertInvocation: vi.fn(), + listVisibleTools: () => [], + interactions: channel + }) + const actions = [{ id: 'approve', label: 'Conversation only' }] + const args = { + title: 'Explicit lone button', + actions, + ...(['fields', 'both'].includes(variant) + ? { fields: [{ label: 'Status', value: 'Read only' }] } + : {}), + ...(['subtitle', 'both'].includes(variant) ? { subtitle: 'Not execution permission' } : {}) + } + let settled = false + const outcome = provider + .callTool('show_card', args, { route, runId: 'single-wait' }) + .then((value) => { + settled = true + return value + }) + await Promise.resolve() + expect(settled).toBe(false) + expect(vi.getTimerCount()).toBe(1) + const [item] = pending() + expect(item.prompt).toEqual({ kind: 'show_card', ...args }) + actions[0].id = 'changed-source' + if (item.prompt.kind === 'show_card') { + item.prompt.actions[0].id = 'changed-view' + if (item.prompt.fields) item.prompt.fields[0].value = 'changed-field' + } + expect(pending()[0].prompt).toMatchObject({ + actions: [{ id: 'approve', label: 'Conversation only' }] + }) + for (const answer of [ + { status: 'answered', actionId: 'changed-source' }, + { status: 'answered', actionId: 'approve', approved: true }, + { status: 'answered', actionId: 'approve', values: {} }, + { status: 'answered', actionId: 'approve', subtitle: 'Not an answer' }, + { status: 'answered', text: 'approve' } + ]) + expect(() => respond(item.id, answer as never)).toThrow('Invalid') + expect(pending()).toHaveLength(1) + expect(settled).toBe(false) + respond(item.id, { status: 'answered', actionId: 'approve' }) + expect(JSON.parse((await outcome).content)).toEqual({ + status: 'answered', + actionId: 'approve' + }) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + expect(() => respond(item.id, { status: 'answered', actionId: 'approve' })).toThrow( + 'not active' + ) + } + ) it('rejects malformed single-action direct MAIN prompts even without context before retention or a timer', async () => { - const base = { kind: 'show_card' as const, title: 'Direct one', actions: [{ id: 'a', label: 'A' }] } - for (const patch of [{ title: '😀'.repeat(101) }, { body: '😀'.repeat(2001) }, { approved: true }, { actions: [{ id: '', label: 'A' }] }, { actions: [{ id: 'a'.repeat(65), label: 'A' }] }, { actions: [{ id: 'bad id', label: 'A' }] }, { actions: [{ id: 'a', label: '😀'.repeat(101) }] }, { actions: [{ id: 'a', label: ' ' }] }, { actions: [null] }, { actions: [{}] }, { actions: [{ id: 'a', label: 'A', style: 'link' }] }, { actions: [{ id: 'a', label: 'A', url: 'https://external.invalid' }] }, { fields: null }, { subtitle: null }, { answer: { actionId: 'a' } }, { ['__proto__']: { approved: true } }]) { - await expect(channel.request({ ...base, ...patch } as never, 1)).rejects.toThrow('Invalid bounded') - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + const base = { + kind: 'show_card' as const, + title: 'Direct one', + actions: [{ id: 'a', label: 'A' }] + } + for (const patch of [ + { title: '😀'.repeat(101) }, + { body: '😀'.repeat(2001) }, + { approved: true }, + { actions: [{ id: '', label: 'A' }] }, + { actions: [{ id: 'a'.repeat(65), label: 'A' }] }, + { actions: [{ id: 'bad id', label: 'A' }] }, + { actions: [{ id: 'a', label: '😀'.repeat(101) }] }, + { actions: [{ id: 'a', label: ' ' }] }, + { actions: [null] }, + { actions: [{}] }, + { actions: [{ id: 'a', label: 'A', style: 'link' }] }, + { actions: [{ id: 'a', label: 'A', url: 'https://external.invalid' }] }, + { fields: null }, + { subtitle: null }, + { answer: { actionId: 'a' } }, + { ['__proto__']: { approved: true } } + ]) { + await expect(channel.request({ ...base, ...patch } as never, 1)).rejects.toThrow( + 'Invalid bounded' + ) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) } - for (const prompt of [{ ...base, fields: undefined, subtitle: undefined }, Object.assign(Object.create({ fields: [null], subtitle: 'INHERITED_IGNORE' }), base)]) { - const outcome = channel.request(prompt, 1), [item] = pending() + for (const prompt of [ + { ...base, fields: undefined, subtitle: undefined }, + Object.assign(Object.create({ fields: [null], subtitle: 'INHERITED_IGNORE' }), base) + ]) { + const outcome = channel.request(prompt, 1), + [item] = pending() expect(item.prompt).toEqual(base) - respond(item.id, { status: 'dismissed' }); expect(await outcome).toEqual({ status: 'dismissed' }) + respond(item.id, { status: 'dismissed' }) + expect(await outcome).toEqual({ status: 'dismissed' }) expect(vi.getTimerCount()).toBe(0) } }) it('enforces exact serialized single-action MAIN caps before pending/timer creation', async () => { - const fields = [{ label: '', value: '\u0001'.repeat(1000) }, { label: '', value: '' }, { label: '', value: '' }] - const prompt = { kind: 'show_card' as const, title: 'One', subtitle: '\u0001'.repeat(200), body: '\u0001'.repeat(4000), fields, actions: [{ id: 'a', label: 'A' }] } + const fields = [ + { label: '', value: '\u0001'.repeat(1000) }, + { label: '', value: '' }, + { label: '', value: '' } + ] + const prompt = { + kind: 'show_card' as const, + title: 'One', + subtitle: '\u0001'.repeat(200), + body: '\u0001'.repeat(4000), + fields, + actions: [{ id: 'a', label: 'A' }] + } const remaining = 32768 - Buffer.byteLength(JSON.stringify(prompt), 'utf8') - fields[1].value = 'x'.repeat(1000); fields[2].value = 'x'.repeat(remaining - 1000) + fields[1].value = 'x'.repeat(1000) + fields[2].value = 'x'.repeat(remaining - 1000) expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32768) - const outcome = channel.request(prompt, 1), [item] = pending() + const outcome = channel.request(prompt, 1), + [item] = pending() expect(item.prompt).toEqual(prompt) - respond(item.id, { status: 'dismissed' }); expect(await outcome).toEqual({ status: 'dismissed' }) - fields[2].value += 'x'; await expect(channel.request(prompt, 1)).rejects.toThrow('Invalid bounded') + respond(item.id, { status: 'dismissed' }) + expect(await outcome).toEqual({ status: 'dismissed' }) + fields[2].value += 'x' + await expect(channel.request(prompt, 1)).rejects.toThrow('Invalid bounded') fields[2].value = fields[2].value.slice(2) + '漢' - expect(JSON.stringify(prompt).length).toBe(32768); expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32770) + expect(JSON.stringify(prompt).length).toBe(32768) + expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32770) await expect(channel.request(prompt, 1)).rejects.toThrow('Invalid bounded') - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) - }) - it.each([false, true])('retains a detached subtitle in owned choice state and accepts only the offered action ID fields=%s', async withFields => { - const { createAgentThreadToolProvider } = await import('./agentThreadTools') - const provider = createAgentThreadToolProvider({ route, messages: [], assertInvocation: vi.fn(), listVisibleTools: () => [], interactions: channel }) - const actions = [{ id: 'approve', label: 'Feedback only' }, { id: 'no', label: 'Other feedback' }] - const args = { title: 'Owned subtitle', subtitle: 'Context is not execution approval', actions, ...(withFields ? { fields: [{ label: 'Status', value: 'Read only' }] } : {}) } - const result = provider.callTool('show_card', args, { route, runId: 'subtitle-wait' }) - const [item] = pending() - expect(item.prompt).toEqual({ kind: 'show_card', ...args }) - args.subtitle = 'MUTATED SOURCE'; actions[0].id = 'source-mutated' - if (item.prompt.kind === 'show_card') { item.prompt.subtitle = 'MUTATED VIEW'; item.prompt.actions[0].id = 'view-mutated' } - expect(pending()[0].prompt).toMatchObject({ subtitle: 'Context is not execution approval', actions: [{ id: 'approve' }, { id: 'no' }] }) - for (const answer of [{ status: 'answered', actionId: 'approve', subtitle: 'Return extra' }, { status: 'answered', actionId: 'approve', approved: true }, { status: 'answered', actionId: 'approve', values: {} }, { status: 'answered', actionId: 'source-mutated' }]) expect(() => respond(item.id, answer as never)).toThrow('Invalid') - expect(pending()).toHaveLength(1) - respond(item.id, { status: 'answered', actionId: 'approve' }) - expect(JSON.parse((await result).content)).toEqual({ status: 'answered', actionId: 'approve' }) - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) }) + it.each([false, true])( + 'retains a detached subtitle in owned choice state and accepts only the offered action ID fields=%s', + async (withFields) => { + const { createAgentThreadToolProvider } = await import('./agentThreadTools') + const provider = createAgentThreadToolProvider({ + route, + messages: [], + assertInvocation: vi.fn(), + listVisibleTools: () => [], + interactions: channel + }) + const actions = [ + { id: 'approve', label: 'Feedback only' }, + { id: 'no', label: 'Other feedback' } + ] + const args = { + title: 'Owned subtitle', + subtitle: 'Context is not execution approval', + actions, + ...(withFields ? { fields: [{ label: 'Status', value: 'Read only' }] } : {}) + } + const result = provider.callTool('show_card', args, { route, runId: 'subtitle-wait' }) + const [item] = pending() + expect(item.prompt).toEqual({ kind: 'show_card', ...args }) + args.subtitle = 'MUTATED SOURCE' + actions[0].id = 'source-mutated' + if (item.prompt.kind === 'show_card') { + item.prompt.subtitle = 'MUTATED VIEW' + item.prompt.actions[0].id = 'view-mutated' + } + expect(pending()[0].prompt).toMatchObject({ + subtitle: 'Context is not execution approval', + actions: [{ id: 'approve' }, { id: 'no' }] + }) + for (const answer of [ + { status: 'answered', actionId: 'approve', subtitle: 'Return extra' }, + { status: 'answered', actionId: 'approve', approved: true }, + { status: 'answered', actionId: 'approve', values: {} }, + { status: 'answered', actionId: 'source-mutated' } + ]) + expect(() => respond(item.id, answer as never)).toThrow('Invalid') + expect(pending()).toHaveLength(1) + respond(item.id, { status: 'answered', actionId: 'approve' }) + expect(JSON.parse((await result).content)).toEqual({ + status: 'answered', + actionId: 'approve' + }) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + } + ) it('validates direct MAIN subtitle-only prompts before retention/timers, preserving omitted/own-undefined/inherited optional behavior', async () => { - const base = { kind: 'show_card' as const, title: 'Direct subtitle', actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] } - for (const patch of [{ subtitle: null }, { subtitle: false }, { subtitle: 1 }, { subtitle: {} }, { subtitle: [] }, { subtitle: 'x'.repeat(201) }, { subtitle: '😀'.repeat(101) }, { subtitle: '', title: '😀'.repeat(101) }, { subtitle: '', body: '😀'.repeat(2001) }, { subtitle: '', actions: [] }, { subtitle: '', actions: [{ id: 'a', label: '😀'.repeat(101) }, base.actions[1]] }, { subtitle: '', approved: true }, { subtitle: '', fields: null }, { subtitle: '', actions: [{ ...base.actions[0], url: 'https://external.invalid' }, base.actions[1]] }]) { - await expect(channel.request({ ...base, ...patch } as never, 17)).rejects.toThrow('Invalid bounded') - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + const base = { + kind: 'show_card' as const, + title: 'Direct subtitle', + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] } - for (const prompt of [{ ...base, subtitle: '' }, { ...base, subtitle: '😀'.repeat(100) }, { ...base, subtitle: undefined }, Object.assign(Object.create({ subtitle: 'INHERITED_IGNORE' }), base)]) { + for (const patch of [ + { subtitle: null }, + { subtitle: false }, + { subtitle: 1 }, + { subtitle: {} }, + { subtitle: [] }, + { subtitle: 'x'.repeat(201) }, + { subtitle: '😀'.repeat(101) }, + { subtitle: '', title: '😀'.repeat(101) }, + { subtitle: '', body: '😀'.repeat(2001) }, + { subtitle: '', actions: [] }, + { subtitle: '', actions: [{ id: 'a', label: '😀'.repeat(101) }, base.actions[1]] }, + { subtitle: '', approved: true }, + { subtitle: '', fields: null }, + { + subtitle: '', + actions: [{ ...base.actions[0], url: 'https://external.invalid' }, base.actions[1]] + } + ]) { + await expect(channel.request({ ...base, ...patch } as never, 17)).rejects.toThrow( + 'Invalid bounded' + ) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + } + for (const prompt of [ + { ...base, subtitle: '' }, + { ...base, subtitle: '😀'.repeat(100) }, + { ...base, subtitle: undefined }, + Object.assign(Object.create({ subtitle: 'INHERITED_IGNORE' }), base) + ]) { const result = channel.request(prompt, 17) const [item] = pending() - if (Object.hasOwn(prompt, 'subtitle') && prompt.subtitle !== undefined) expect(item.prompt).toMatchObject({ subtitle: prompt.subtitle }) + if (Object.hasOwn(prompt, 'subtitle') && prompt.subtitle !== undefined) + expect(item.prompt).toMatchObject({ subtitle: prompt.subtitle }) else expect(Object.hasOwn(item.prompt, 'subtitle')).toBe(Object.hasOwn(prompt, 'subtitle')) - respond(item.id, { status: 'dismissed' }); expect(await result).toEqual({ status: 'dismissed' }) - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + respond(item.id, { status: 'dismissed' }) + expect(await result).toEqual({ status: 'dismissed' }) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) } }) it('includes subtitle in the direct MAIN exact JSON cap before starting a timer', async () => { - const fields = [{ label: '', value: '\u0001'.repeat(1000) }, { label: '', value: '' }, { label: '', value: '' }] - const prompt = { kind: 'show_card' as const, title: 'B', subtitle: '\u0001'.repeat(200), body: '\u0001'.repeat(4000), fields, actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] } + const fields = [ + { label: '', value: '\u0001'.repeat(1000) }, + { label: '', value: '' }, + { label: '', value: '' } + ] + const prompt = { + kind: 'show_card' as const, + title: 'B', + subtitle: '\u0001'.repeat(200), + body: '\u0001'.repeat(4000), + fields, + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + } const remaining = 32768 - Buffer.byteLength(JSON.stringify(prompt), 'utf8') - fields[1].value = 'x'.repeat(1000); fields[2].value = 'x'.repeat(remaining - 1000) + fields[1].value = 'x'.repeat(1000) + fields[2].value = 'x'.repeat(remaining - 1000) expect(Buffer.byteLength(JSON.stringify(prompt), 'utf8')).toBe(32768) - const result = channel.request(prompt, 17), [item] = pending() + const result = channel.request(prompt, 17), + [item] = pending() expect(item.prompt).toEqual(prompt) - respond(item.id, { status: 'dismissed' }); expect(await result).toEqual({ status: 'dismissed' }) + respond(item.id, { status: 'dismissed' }) + expect(await result).toEqual({ status: 'dismissed' }) fields[2].value += 'x' await expect(channel.request(prompt, 17)).rejects.toThrow('Invalid bounded') - expect(pending()).toEqual([]); expect(vi.getTimerCount()).toBe(0) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) }) it('carries bounded read-only fields through the real choice wait, detaches views and accepts only the offered ID', async () => { const { createAgentThreadToolProvider } = await import('./agentThreadTools') - const provider = createAgentThreadToolProvider({ route, messages: [], assertInvocation: vi.fn(), listVisibleTools: () => [], interactions: channel }) - const fields = [{ label: 'Status', value: '', inline: true }, { label: 'Next', value: 'Choice is not edit authorization', inline: false }] - const actions = [{ id: 'approve', label: 'Feedback only' }, { id: 'no', label: 'Other feedback' }] - const result = provider.callTool('show_card', { title: 'Choice fields', fields, actions, timeout_s: 17 }, { route, runId: 'choice-fields', toolCallId: 'choice-fields-call' }) - const outcome = result.then(value => ({ value }), error => ({ error })) + const provider = createAgentThreadToolProvider({ + route, + messages: [], + assertInvocation: vi.fn(), + listVisibleTools: () => [], + interactions: channel + }) + const fields = [ + { label: 'Status', value: '', inline: true }, + { label: 'Next', value: 'Choice is not edit authorization', inline: false } + ] + const actions = [ + { id: 'approve', label: 'Feedback only' }, + { id: 'no', label: 'Other feedback' } + ] + const result = provider.callTool( + 'show_card', + { title: 'Choice fields', fields, actions, timeout_s: 17 }, + { route, runId: 'choice-fields', toolCallId: 'choice-fields-call' } + ) + const outcome = result.then( + (value) => ({ value }), + (error) => ({ error }) + ) const [item] = pending() expect(item?.prompt).toEqual({ kind: 'show_card', title: 'Choice fields', fields, actions }) expect(item.expiresAt).toBe(Date.now() + 17000) - fields[0].value = 'Changed source'; actions[0].id = 'changed' + fields[0].value = 'Changed source' + actions[0].id = 'changed' expect(item.prompt.kind).toBe('show_card') if (item.prompt.kind === 'show_card') { item.prompt.actions[0].id = 'changed view' item.prompt.fields![0].value = 'Changed view' } - expect(pending()[0].prompt).toMatchObject({ fields: [{ value: '' }, { value: 'Choice is not edit authorization' }], actions: [{ id: 'approve' }, { id: 'no' }] }) + expect(pending()[0].prompt).toMatchObject({ + fields: [ + { value: '' }, + { value: 'Choice is not edit authorization' } + ], + actions: [{ id: 'approve' }, { id: 'no' }] + }) expect(() => respond(item.id, { status: 'answered', actionId: 'changed' })).toThrow('Invalid') respond(item.id, { status: 'answered', actionId: 'approve' }) const settled = await outcome - expect(settled).toMatchObject({ value: { content: JSON.stringify({ status: 'answered', actionId: 'approve' }) } }) + expect(settled).toMatchObject({ + value: { content: JSON.stringify({ status: 'answered', actionId: 'approve' }) } + }) expect(pending()).toEqual([]) expect(vi.getTimerCount()).toBe(0) }) it('validates explicit choice fields before retaining input or starting a timer, including direct MAIN channel calls', async () => { - const actions = [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] + const actions = [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] const base = { kind: 'show_card' as const, title: 'Choice', actions } for (const patch of [ - { fields: null }, { fields: [null] }, { fields: [{ label: 'x', value: 1 }] }, - { fields: [{ label: 'x', value: 'x', approved: true }] }, { fields: [{ label: '😀'.repeat(101), value: '' }] }, - { fields: [{ label: '', value: '😀'.repeat(501) }] }, { fields: [{ ['__proto__']: { label: 'Inherited' }, value: '' }] }, + { fields: null }, + { fields: [null] }, + { fields: [{ label: 'x', value: 1 }] }, + { fields: [{ label: 'x', value: 'x', approved: true }] }, + { fields: [{ label: '😀'.repeat(101), value: '' }] }, + { fields: [{ label: '', value: '😀'.repeat(501) }] }, + { fields: [{ ['__proto__']: { label: 'Inherited' }, value: '' }] }, { fields: Array.from({ length: 9 }, () => ({ label: '', value: '' })) }, - { fields: Array.from({ length: 4 }, () => ({ label: 'x'.repeat(200), value: 'x'.repeat(1000) })) }, + { + fields: Array.from({ length: 4 }, () => ({ + label: 'x'.repeat(200), + value: 'x'.repeat(1000) + })) + }, { fields: [], actions: [] }, - { fields: [], actions: [{ id: 'a', label: 'A', url: 'https://external.invalid' }, actions[1]] }, - { fields: [], grantsPermission: true }, { fields: [], title: '😀'.repeat(101) }, + { + fields: [], + actions: [{ id: 'a', label: 'A', url: 'https://external.invalid' }, actions[1]] + }, + { fields: [], grantsPermission: true }, + { fields: [], title: '😀'.repeat(101) }, { fields: [], body: '😀'.repeat(2001) }, - { fields: Array.from({ length: 4 }, () => ({ label: '', value: '\u0001'.repeat(1000) })), body: '\u0001'.repeat(4000) } + { + fields: Array.from({ length: 4 }, () => ({ label: '', value: '\u0001'.repeat(1000) })), + body: '\u0001'.repeat(4000) + } ]) { - await expect(channel.request({ ...base, ...patch } as never, 17)).rejects.toThrow('Invalid bounded') + await expect(channel.request({ ...base, ...patch } as never, 17)).rejects.toThrow( + 'Invalid bounded' + ) expect(pending()).toEqual([]) expect(vi.getTimerCount()).toBe(0) } const result = channel.request({ ...base, fields: [] }, 17) const [item] = pending() expect(item.prompt).toMatchObject({ kind: 'show_card', fields: [] }) - respond(item.id, { status: 'dismissed' }); expect(await result).toEqual({ status: 'dismissed' }) + respond(item.id, { status: 'dismissed' }) + expect(await result).toEqual({ status: 'dismissed' }) expect(vi.getTimerCount()).toBe(0) }) - it.each((['answer', 'dismiss', 'expiry', 'stale-expiry', 'abort', 'navigation', 'crash', 'destroyed'] as const).flatMap(kind => [1, 2].flatMap(count => [false, true].flatMap(withFooter => [false, true].flatMap(withAccent => [false, true].flatMap(withStyle => [false, true].flatMap(withIcon => [false, true].map(withBody => [kind, count, withFooter, withAccent, withStyle, withIcon, withBody] as const))))))))('keeps subtitle/fielded choice ownership, one-shot answers and timer cleanup on %s actions=%s footer=%s accent=%s actionStyle=%s icon=%s body=%s', async (kind, count, withFooter, withAccent, withStyle, withIcon, withBody) => { - const { createAgentThreadToolProvider } = await import('./agentThreadTools') - const provider = createAgentThreadToolProvider({ route, messages: [], assertInvocation: vi.fn(), listVisibleTools: () => [], interactions: channel }) - const controller = new AbortController() - const body = '**Context only**\n\nBearer a**RAW_SUFFIX**\n\n[No authority](https://external.invalid/no-open)\n\n- [x] Not consent' - const result = provider.callTool('show_card', { title: 'Field context only', ...(withBody ? { body } : {}), ...(withIcon ? { icon: '✓👩🏽‍💻' } : {}), ...(withAccent ? { accent: 'danger' } : {}), subtitle: 'Read-only subtitle, not permission', ...(withFooter ? { footer: 'Read-only closing context, never permission' } : {}), fields: [{ label: 'Status', value: 'Not execution permission' }], actions: [{ id: 'approve', label: 'Feedback only', ...(withStyle ? { style: 'primary' } : {}) }, { id: 'no', label: 'Other feedback', ...(withStyle ? { style: 'danger' } : {}) }].slice(0, count), timeout_s: 1 }, { route, runId: 'choice-lifetime', signal: controller.signal }).then(value => JSON.parse(value.content), () => 'cancelled') - const [item] = pending() - if (withBody) { - expect(item.prompt).toMatchObject({ body }) - if (item.prompt.kind === 'show_card') item.prompt.body = 'Changed display copy' - expect(pending()[0].prompt).toMatchObject({ body }) - expect(() => respond(item.id, { status: 'answered', actionId: 'approve', body } as never)).toThrow('Invalid') - } - if (withIcon) expect(item.prompt).toMatchObject({ icon: '✓👩🏽‍💻' }) - if (withStyle) expect(item.prompt).toMatchObject({ actions: count === 1 ? [{ id: 'approve', style: 'primary' }] : [{ id: 'approve', style: 'primary' }, { id: 'no', style: 'danger' }] }) - if (withAccent) expect(item.prompt).toMatchObject({ accent: 'danger' }) - if (withFooter) expect(item.prompt).toMatchObject({ footer: 'Read-only closing context, never permission' }) - expect(vi.getTimerCount()).toBe(1) - for (const other of [{ ...scope, conversationId: 'other' }, { ...scope, route: { ...route, threadId: 'other' } }]) { - expect(manager.list(other, invocation('listAgentInteractions'))).toEqual([]) - expect(() => manager.resolve({ ...other, interactionId: item.id, answer: { status: 'answered', actionId: 'approve' } }, invocation('resolveAgentInteraction'))).toThrow('not active') + it.each( + ( + [ + 'answer', + 'dismiss', + 'expiry', + 'stale-expiry', + 'abort', + 'navigation', + 'crash', + 'destroyed' + ] as const + ).flatMap((kind) => + [1, 2].flatMap((count) => + [false, true].flatMap((withFooter) => + [false, true].flatMap((withAccent) => + [false, true].flatMap((withStyle) => + [false, true].flatMap((withIcon) => + [false, true].map( + (withBody) => + [kind, count, withFooter, withAccent, withStyle, withIcon, withBody] as const + ) + ) + ) + ) + ) + ) + ) + )( + 'keeps subtitle/fielded choice ownership, one-shot answers and timer cleanup on %s actions=%s footer=%s accent=%s actionStyle=%s icon=%s body=%s', + async (kind, count, withFooter, withAccent, withStyle, withIcon, withBody) => { + const { createAgentThreadToolProvider } = await import('./agentThreadTools') + const provider = createAgentThreadToolProvider({ + route, + messages: [], + assertInvocation: vi.fn(), + listVisibleTools: () => [], + interactions: channel + }) + const controller = new AbortController() + const body = + '**Context only**\n\nBearer a**RAW_SUFFIX**\n\n[No authority](https://external.invalid/no-open)\n\n- [x] Not consent' + const result = provider + .callTool( + 'show_card', + { + title: 'Field context only', + ...(withBody ? { body } : {}), + ...(withIcon ? { icon: '✓👩🏽‍💻' } : {}), + ...(withAccent ? { accent: 'danger' } : {}), + subtitle: 'Read-only subtitle, not permission', + ...(withFooter ? { footer: 'Read-only closing context, never permission' } : {}), + fields: [{ label: 'Status', value: 'Not execution permission' }], + actions: [ + { id: 'approve', label: 'Feedback only', ...(withStyle ? { style: 'primary' } : {}) }, + { id: 'no', label: 'Other feedback', ...(withStyle ? { style: 'danger' } : {}) } + ].slice(0, count), + timeout_s: 1 + }, + { route, runId: 'choice-lifetime', signal: controller.signal } + ) + .then( + (value) => JSON.parse(value.content), + () => 'cancelled' + ) + const [item] = pending() + if (withBody) { + expect(item.prompt).toMatchObject({ body }) + if (item.prompt.kind === 'show_card') item.prompt.body = 'Changed display copy' + expect(pending()[0].prompt).toMatchObject({ body }) + expect(() => + respond(item.id, { status: 'answered', actionId: 'approve', body } as never) + ).toThrow('Invalid') + } + if (withIcon) expect(item.prompt).toMatchObject({ icon: '✓👩🏽‍💻' }) + if (withStyle) + expect(item.prompt).toMatchObject({ + actions: + count === 1 + ? [{ id: 'approve', style: 'primary' }] + : [ + { id: 'approve', style: 'primary' }, + { id: 'no', style: 'danger' } + ] + }) + if (withAccent) expect(item.prompt).toMatchObject({ accent: 'danger' }) + if (withFooter) + expect(item.prompt).toMatchObject({ footer: 'Read-only closing context, never permission' }) + expect(vi.getTimerCount()).toBe(1) + for (const other of [ + { ...scope, conversationId: 'other' }, + { ...scope, route: { ...route, threadId: 'other' } } + ]) { + expect(manager.list(other, invocation('listAgentInteractions'))).toEqual([]) + expect(() => + manager.resolve( + { + ...other, + interactionId: item.id, + answer: { status: 'answered', actionId: 'approve' } + }, + invocation('resolveAgentInteraction') + ) + ).toThrow('not active') + } + expect(() => + manager.list(scope, { ...invocation('listAgentInteractions'), senderId: 72 }) + ).toThrow() + for (const answer of [ + { status: 'answered', actionId: 'not-offered' }, + { status: 'answered', values: { Status: 'changed' } }, + { status: 'answered', actionId: 'approve', values: {} }, + { status: 'answered', actionId: 'approve', approved: true }, + { status: 'answered', text: 'approve' }, + { status: 'dismissed', approved: true }, + { status: 'answered', actionId: 'approve', footer: '' }, + { status: 'answered', actionId: 'approve', accent: 'success' }, + { status: 'answered', actionId: 'approve', style: 'primary' }, + { status: 'answered', actionId: 'approve', icon: '✓' } + ]) + expect(() => respond(item.id, answer as never)).toThrow('Invalid') + expect(pending()).toHaveLength(1) + if (kind === 'answer') respond(item.id, { status: 'answered', actionId: 'approve' }) + else if (kind === 'dismiss') respond(item.id, { status: 'dismissed' }) + else if (kind === 'expiry') { + await vi.advanceTimersByTimeAsync(999) + expect(pending()).toHaveLength(1) + await vi.advanceTimersByTimeAsync(1) + } else if (kind === 'stale-expiry') { + vi.setSystemTime(Date.now() + 1000) + expect(() => respond(item.id, { status: 'answered', actionId: 'approve' })).toThrow( + 'expired' + ) + } else if (kind === 'abort') controller.abort() + else + sender.emit( + kind === 'navigation' + ? 'did-start-navigation' + : kind === 'crash' + ? 'render-process-gone' + : 'destroyed' + ) + expect(await result).toEqual( + kind === 'answer' + ? { status: 'answered', actionId: 'approve' } + : kind === 'dismiss' + ? { status: 'dismissed' } + : ['expiry', 'stale-expiry'].includes(kind) + ? { status: 'timeout' } + : 'cancelled' + ) + expect(pending()).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + expect(() => respond(item.id, { status: 'answered', actionId: 'approve' })).toThrow( + 'not active' + ) } - expect(() => manager.list(scope, { ...invocation('listAgentInteractions'), senderId: 72 })).toThrow() - for (const answer of [ - { status: 'answered', actionId: 'not-offered' }, { status: 'answered', values: { Status: 'changed' } }, - { status: 'answered', actionId: 'approve', values: {} }, { status: 'answered', actionId: 'approve', approved: true }, - { status: 'answered', text: 'approve' }, { status: 'dismissed', approved: true }, { status: 'answered', actionId: 'approve', footer: '' }, { status: 'answered', actionId: 'approve', accent: 'success' }, { status: 'answered', actionId: 'approve', style: 'primary' }, { status: 'answered', actionId: 'approve', icon: '✓' } - ]) expect(() => respond(item.id, answer as never)).toThrow('Invalid') - expect(pending()).toHaveLength(1) - if (kind === 'answer') respond(item.id, { status: 'answered', actionId: 'approve' }) - else if (kind === 'dismiss') respond(item.id, { status: 'dismissed' }) - else if (kind === 'expiry') { - await vi.advanceTimersByTimeAsync(999); expect(pending()).toHaveLength(1) - await vi.advanceTimersByTimeAsync(1) - } else if (kind === 'stale-expiry') { - vi.setSystemTime(Date.now() + 1000) - expect(() => respond(item.id, { status: 'answered', actionId: 'approve' })).toThrow('expired') - } else if (kind === 'abort') controller.abort() - else sender.emit(kind === 'navigation' ? 'did-start-navigation' : kind === 'crash' ? 'render-process-gone' : 'destroyed') - expect(await result).toEqual(kind === 'answer' ? { status: 'answered', actionId: 'approve' } : kind === 'dismiss' ? { status: 'dismissed' } : ['expiry', 'stale-expiry'].includes(kind) ? { status: 'timeout' } : 'cancelled') - expect(pending()).toEqual([]) - expect(vi.getTimerCount()).toBe(0) - expect(() => respond(item.id, { status: 'answered', actionId: 'approve' })).toThrow('not active') - }) + ) it('hands the member End check to its sub-agent and memory helper, which start no read after End', async () => { const { prepareCanvasAgentTools } = await import('./canvasAgentTools') - const source = { scope: 'team-scope', thread: route.threadId, lead: 'leader', member: scope.conversationId } + const source = { + scope: 'team-scope', + thread: route.threadId, + lead: 'leader', + member: scope.conversationId + } const req: LLMChatReq = { ...scope, messages: [], teamMember: source } let ended = false - const assertTeamActive = vi.fn(() => { if (ended) throw new Error('Team has ended.') }) + const assertTeamActive = vi.fn(() => { + if (ended) throw new Error('Team has ended.') + }) // Each helper's model step asks for one read; End is recorded while that step is in flight. - const subagentChat = vi.fn(async () => { ended = true; return { content: '{"toolName":"files.read","args":{"path":"notes.md"}}' } }) - const memoryChat = vi.fn(async () => { ended = true; return { content: '{"toolName":"memory.files.read","args":{"path":"./memory/facts.md"}}' } }) - const readTool = { name: 'files.read', description: 'Read text', inputSchema: { type: 'object', additionalProperties: false, required: ['path'], properties: { path: { type: 'string' } } } } + const subagentChat = vi.fn(async () => { + ended = true + return { content: '{"toolName":"files.read","args":{"path":"notes.md"}}' } + }) + const memoryChat = vi.fn(async () => { + ended = true + return { content: '{"toolName":"memory.files.read","args":{"path":"./memory/facts.md"}}' } + }) + const readTool = { + name: 'files.read', + description: 'Read text', + inputSchema: { + type: 'object', + additionalProperties: false, + required: ['path'], + properties: { path: { type: 'string' } } + } + } const callSubagentReadTool = vi.fn(async () => ({ content: 'notes' })) const settings = { - local: true, terminalEnabled: false, listTools: () => [readTool], callSubagentReadTool, - createSubagentClient: async () => ({ chat: subagentChat, supportsIsolatedReadOnlyTurns: true }), + local: true, + terminalEnabled: false, + listTools: () => [readTool], + callSubagentReadTool, + createSubagentClient: async () => ({ + chat: subagentChat, + supportsIsolatedReadOnlyTurns: true + }), createMemoryClient: async () => ({ chat: memoryChat, supportsIsolatedMainToolTurns: true }), commitMemoryFile: vi.fn(async () => ({ content: 'unused' })) } const member = prepareCanvasAgentTools(req, invocation(), { ...settings, assertTeamActive }) const ordinary = prepareCanvasAgentTools({ ...scope, messages: [] }, invocation(), settings) - const run = (prepared: typeof member, name: string) => prepared.admission!.run(name, undefined, () => prepared.toolProvider!.callTool(name, { task: 'Look it up' }, { route, runId: 'parent-run', toolCallId: `${name}-call` })) + const run = (prepared: typeof member, name: string) => + prepared.admission!.run(name, undefined, () => + prepared.toolProvider!.callTool( + name, + { task: 'Look it up' }, + { route, runId: 'parent-run', toolCallId: `${name}-call` } + ) + ) try { await expect(run(member, 'explore')).rejects.toThrow('Team has ended.') - expect(subagentChat).toHaveBeenCalledOnce(); expect(callSubagentReadTool).not.toHaveBeenCalled() + expect(subagentChat).toHaveBeenCalledOnce() + expect(callSubagentReadTool).not.toHaveBeenCalled() ended = false await expect(run(member, 'memory_read')).rejects.toThrow('Team has ended.') - expect(memoryChat).toHaveBeenCalledOnce(); expect(memoryHost.callTool).not.toHaveBeenCalled() + expect(memoryChat).toHaveBeenCalledOnce() + expect(memoryHost.callTool).not.toHaveBeenCalled() // Without the callback (a request without teamMember) the same helpers run their reads. - subagentChat.mockResolvedValueOnce({ content: '{"toolName":"files.read","args":{"path":"notes.md"}}' }).mockResolvedValueOnce({ content: 'Found it.' }) - memoryChat.mockResolvedValueOnce({ content: '{"toolName":"memory.files.read","args":{"path":"./memory/facts.md"}}' }).mockResolvedValueOnce({ content: 'Remembered.' }) - expect(JSON.parse((await run(ordinary, 'explore')).content)).toMatchObject({ status: 'completed', toolCalls: 1 }) - expect(JSON.parse((await run(ordinary, 'memory_read')).content)).toMatchObject({ status: 'completed', toolCalls: 1 }) - expect(callSubagentReadTool).toHaveBeenCalledOnce(); expect(memoryHost.callTool).toHaveBeenCalledOnce() + subagentChat + .mockResolvedValueOnce({ content: '{"toolName":"files.read","args":{"path":"notes.md"}}' }) + .mockResolvedValueOnce({ content: 'Found it.' }) + memoryChat + .mockResolvedValueOnce({ + content: '{"toolName":"memory.files.read","args":{"path":"./memory/facts.md"}}' + }) + .mockResolvedValueOnce({ content: 'Remembered.' }) + expect(JSON.parse((await run(ordinary, 'explore')).content)).toMatchObject({ + status: 'completed', + toolCalls: 1 + }) + expect(JSON.parse((await run(ordinary, 'memory_read')).content)).toMatchObject({ + status: 'completed', + toolCalls: 1 + }) + expect(callSubagentReadTool).toHaveBeenCalledOnce() + expect(memoryHost.callTool).toHaveBeenCalledOnce() expect(assertTeamActive).toHaveBeenCalledTimes(4) // each helper: its first step, then the refused read - } finally { member.dispose!(); ordinary.dispose!() } + } finally { + member.dispose!() + ordinary.dispose!() + } }) it('exposes team message tools only to matching local member turns and requires their live admission', async () => { const { prepareCanvasAgentTools } = await import('./canvasAgentTools') - const source = { scope: 'team-scope', thread: route.threadId, lead: 'leader', member: scope.conversationId } + const source = { + scope: 'team-scope', + thread: route.threadId, + lead: 'leader', + member: scope.conversationId + } const req: LLMChatReq = { ...scope, messages: [], teamMember: source } const enqueue = vi.fn(async () => ({ requestId: 'request-1' })) const assertNotEnded = vi.fn() - const settings = { local: true, terminalEnabled: false, teamMessages: { enqueue, assertNotEnded } } + const settings = { + local: true, + terminalEnabled: false, + teamMessages: { enqueue, assertNotEnded } + } const first = prepareCanvasAgentTools(req, invocation(), settings) const other = prepareCanvasAgentTools(req, invocation(), settings) try { - expect(first.toolProvider!.listTools().map(tool => tool.name)).toEqual(expect.arrayContaining(['send_message', 'send_channel'])) + expect(first.toolProvider!.listTools().map((tool) => tool.name)).toEqual( + expect.arrayContaining(['send_message', 'send_channel']) + ) expect(first.request.skillRuntime?.bindings?.[0]?.toolNames).toContain('send_message') - const args = { recipient: 'other', text: 'hello' }, context = { route, runId: 'test' } - const invoke = (prepared: typeof first, name: string, input: Record) => prepared.toolProvider!.callTool(name, input, context) - await expect(invoke(first, 'send_message', args)).rejects.toThrow('live Agent thread invocation') - await expect(other.admission!.run('send_message', undefined, () => invoke(first, 'send_message', args))).rejects.toThrow('live Agent thread invocation') - const result = await first.admission!.run('send_message', undefined, () => invoke(first, 'send_message', args)) + const args = { recipient: 'other', text: 'hello' }, + context = { route, runId: 'test' } + const invoke = (prepared: typeof first, name: string, input: Record) => + prepared.toolProvider!.callTool(name, input, context) + await expect(invoke(first, 'send_message', args)).rejects.toThrow( + 'live Agent thread invocation' + ) + await expect( + other.admission!.run('send_message', undefined, () => invoke(first, 'send_message', args)) + ).rejects.toThrow('live Agent thread invocation') + const result = await first.admission!.run('send_message', undefined, () => + invoke(first, 'send_message', args) + ) expect(JSON.parse(result.content)).toEqual({ status: 'queued', requestId: 'request-1' }) - expect(enqueue).toHaveBeenCalledWith({ source, kind: 'message', hop: 1, recipient: 'other', text: 'hello' }, expect.objectContaining({ assertLive: expect.any(Function) }), undefined) + expect(enqueue).toHaveBeenCalledWith( + { source, kind: 'message', hop: 1, recipient: 'other', text: 'hello' }, + expect.objectContaining({ assertLive: expect.any(Function) }), + undefined + ) expect(assertNotEnded).toHaveBeenCalledWith(source) - assertNotEnded.mockImplementationOnce(() => { throw Error('ended') }) - await expect(first.admission!.run('send_channel', undefined, () => first.toolProvider!.callTool('send_channel', { text: 'hi' }, context))).rejects.toThrow('ended') + assertNotEnded.mockImplementationOnce(() => { + throw Error('ended') + }) + await expect( + first.admission!.run('send_channel', undefined, () => + first.toolProvider!.callTool('send_channel', { text: 'hi' }, context) + ) + ).rejects.toThrow('ended') expect(enqueue).toHaveBeenCalledTimes(1) - const wrongMember = prepareCanvasAgentTools({ ...req, teamMember: { ...source, member: 'another' } }, invocation(), settings) + const wrongMember = prepareCanvasAgentTools( + { ...req, teamMember: { ...source, member: 'another' } }, + invocation(), + settings + ) const noMember = prepareCanvasAgentTools({ ...scope, messages: [] }, invocation(), settings) const relayed = prepareCanvasAgentTools({ ...req, teamMessageHop: 1 }, invocation(), settings) const lastHop = prepareCanvasAgentTools({ ...req, teamMessageHop: 2 }, invocation(), settings) - const invalidHop = prepareCanvasAgentTools({ ...req, teamMessageHop: 3 as 1 }, invocation(), settings) + const invalidHop = prepareCanvasAgentTools( + { ...req, teamMessageHop: 3 as 1 }, + invocation(), + settings + ) try { - expect(wrongMember.toolProvider!.listTools().map(tool => tool.name)).not.toContain('send_message') - expect(noMember.toolProvider!.listTools().map(tool => tool.name)).not.toContain('send_message') - expect(relayed.toolProvider!.listTools().map(tool => tool.name)).toEqual(expect.arrayContaining(['send_message', 'send_channel'])) - await relayed.admission!.run('send_message', undefined, () => invoke(relayed, 'send_message', args)) - expect(enqueue).toHaveBeenLastCalledWith({ source, kind: 'message', hop: 2, recipient: 'other', text: 'hello' }, expect.objectContaining({ assertLive: expect.any(Function) }), undefined) - expect(lastHop.toolProvider!.listTools().map(tool => tool.name)).not.toContain('send_message') - expect(lastHop.toolProvider!.listTools().map(tool => tool.name)).not.toContain('send_channel') - expect(invalidHop.toolProvider!.listTools().map(tool => tool.name)).not.toContain('send_message') - } finally { wrongMember.dispose!(); noMember.dispose!(); relayed.dispose!(); lastHop.dispose!(); invalidHop.dispose!() } - expect(prepareCanvasAgentTools(req, invocation(), { ...settings, local: false }).toolProvider).toBeUndefined() - expect(prepareCanvasAgentTools({ ...req, skillRuntime: { skillId: 'restricted' } }, invocation(), settings).toolProvider).toBeUndefined() - } finally { first.dispose!(); other.dispose!() } + expect(wrongMember.toolProvider!.listTools().map((tool) => tool.name)).not.toContain( + 'send_message' + ) + expect(noMember.toolProvider!.listTools().map((tool) => tool.name)).not.toContain( + 'send_message' + ) + expect(relayed.toolProvider!.listTools().map((tool) => tool.name)).toEqual( + expect.arrayContaining(['send_message', 'send_channel']) + ) + await relayed.admission!.run('send_message', undefined, () => + invoke(relayed, 'send_message', args) + ) + expect(enqueue).toHaveBeenLastCalledWith( + { source, kind: 'message', hop: 2, recipient: 'other', text: 'hello' }, + expect.objectContaining({ assertLive: expect.any(Function) }), + undefined + ) + expect(lastHop.toolProvider!.listTools().map((tool) => tool.name)).not.toContain( + 'send_message' + ) + expect(lastHop.toolProvider!.listTools().map((tool) => tool.name)).not.toContain( + 'send_channel' + ) + expect(invalidHop.toolProvider!.listTools().map((tool) => tool.name)).not.toContain( + 'send_message' + ) + } finally { + wrongMember.dispose!() + noMember.dispose!() + relayed.dispose!() + lastHop.dispose!() + invalidHop.dispose!() + } + expect( + prepareCanvasAgentTools(req, invocation(), { ...settings, local: false }).toolProvider + ).toBeUndefined() + expect( + prepareCanvasAgentTools( + { ...req, skillRuntime: { skillId: 'restricted' } }, + invocation(), + settings + ).toolProvider + ).toBeUndefined() + } finally { + first.dispose!() + other.dispose!() + } }) it('adds image_gen only to an eligible document and rejects inherited, cross-thread or model-supplied authority', async () => { const { prepareCanvasAgentTools } = await import('./canvasAgentTools') - const generator = { approval: { backend: 'codex-json-oauth' as const, endpoint: 'https://chatgpt.com/backend-api/codex', profileId: 'selected' }, assertCurrent: vi.fn(), generate: vi.fn() } + const generator = { + approval: { + backend: 'codex-json-oauth' as const, + endpoint: 'https://images.example.test/backend', + profileId: 'selected' + }, + assertCurrent: vi.fn(), + generate: vi.fn() + } const createImageGenerator = vi.fn(() => generator) const settings = { local: true, terminalEnabled: false, createImageGenerator } const req = { ...scope, messages: [] } - expect(prepareCanvasAgentTools(req, invocation(), { ...settings, local: false }).toolProvider).toBeUndefined() - expect(prepareCanvasAgentTools({ ...req, skillRuntime: { skillId: 'explicit' } }, invocation(), settings).toolProvider).toBeUndefined() + expect( + prepareCanvasAgentTools(req, invocation(), { ...settings, local: false }).toolProvider + ).toBeUndefined() + expect( + prepareCanvasAgentTools( + { ...req, skillRuntime: { skillId: 'explicit' } }, + invocation(), + settings + ).toolProvider + ).toBeUndefined() expect(createImageGenerator).not.toHaveBeenCalled() const first = prepareCanvasAgentTools(req, invocation(), settings) const second = prepareCanvasAgentTools(req, invocation(), settings) - const args = { prompt: 'fixture' }, context = { route, runId: 'image-authority' } + const args = { prompt: 'fixture' }, + context = { route, runId: 'image-authority' } try { - expect(first.toolProvider!.listTools().map(tool => tool.name)).toContain('image_gen') - await expect(first.toolProvider!.callTool('image_gen', args, context)).rejects.toThrow('live Agent thread invocation') - await expect(first.admission!.run('image_gen', undefined, () => first.toolProvider!.callTool('image_gen', args, { ...context, route: { ...route, threadId: 'foreign' } }))).rejects.toThrow('outside') - await expect(first.admission!.run('image_gen', undefined, () => second.toolProvider!.callTool('image_gen', args, context))).rejects.toThrow('live Agent thread invocation') - await expect(first.admission!.run('image_gen', undefined, () => first.toolProvider!.callTool('image_gen', { ...args, confirmed: true }, context))).rejects.toThrow('Invalid') + expect(first.toolProvider!.listTools().map((tool) => tool.name)).toContain('image_gen') + await expect(first.toolProvider!.callTool('image_gen', args, context)).rejects.toThrow( + 'live Agent thread invocation' + ) + await expect( + first.admission!.run('image_gen', undefined, () => + first.toolProvider!.callTool('image_gen', args, { + ...context, + route: { ...route, threadId: 'foreign' } + }) + ) + ).rejects.toThrow('outside') + await expect( + first.admission!.run('image_gen', undefined, () => + second.toolProvider!.callTool('image_gen', args, context) + ) + ).rejects.toThrow('live Agent thread invocation') + await expect( + first.admission!.run('image_gen', undefined, () => + first.toolProvider!.callTool('image_gen', { ...args, confirmed: true }, context) + ) + ).rejects.toThrow('Invalid') let release!: () => void let late!: Promise - await expect(first.admission!.run('image_gen', undefined, async () => { - late = new Promise(resolve => { release = resolve }).then(() => first.toolProvider!.callTool('image_gen', args, context)) - })).rejects.toMatchObject({ code: 'IMAGE_RESULT_RESTORE_FAILED' }) + await expect( + first.admission!.run('image_gen', undefined, async () => { + late = new Promise((resolve) => { + release = resolve + }).then(() => first.toolProvider!.callTool('image_gen', args, context)) + }) + ).rejects.toMatchObject({ code: 'IMAGE_RESULT_RESTORE_FAILED' }) release() await expect(late).rejects.toThrow('live Agent thread invocation') expect(generator.generate).not.toHaveBeenCalled() sender.emit('did-start-navigation') - await expect(first.admission!.run('image_gen', undefined, async () => ({ content: 'never' }))).rejects.toThrow('no longer active') - } finally { first.dispose!(); second.dispose!() } + await expect( + first.admission!.run('image_gen', undefined, async () => ({ content: 'never' })) + ).rejects.toThrow('no longer active') + } finally { + first.dispose!() + second.dispose!() + } }) - it.each([false, true])('GIF capability=%s is reflected in this request schema and guidance under existing owner guards', async gifEnabled => { - const { prepareCanvasAgentTools } = await import('./canvasAgentTools') - const generator = { gifEnabled, approval: { backend: 'codex-json-oauth' as const, endpoint: 'https://chatgpt.com/backend-api/codex', profileId: 'selected' }, assertCurrent: vi.fn(), generate: vi.fn() } - const request: LLMChatReq = { ...scope, messages: [] } - const options = { local: true, terminalEnabled: false, createImageGenerator: () => generator } - const first = prepareCanvasAgentTools(request, invocation(), options) - const other = prepareCanvasAgentTools(request, invocation(), options) - const input = { prompt: 'animated', gif: {} }, context = { route, runId: 'gif-owner' } - try { - const tool = first.toolProvider!.listTools().find(tool => tool.name === 'image_gen')! - if (gifEnabled) { - expect(tool.inputSchema).toHaveProperty('properties.gif') - expect(first.request.systemPrompt).toContain('explicitly enabled GIF OUTPUT') - } else { - expect(tool.inputSchema).not.toHaveProperty('properties.gif') - expect(first.request.systemPrompt).toContain('GIF output is disabled') + it.each([false, true])( + 'GIF capability=%s is reflected in this request schema and guidance under existing owner guards', + async (gifEnabled) => { + const { prepareCanvasAgentTools } = await import('./canvasAgentTools') + const generator = { + gifEnabled, + approval: { + backend: 'codex-json-oauth' as const, + endpoint: 'https://images.example.test/backend', + profileId: 'selected' + }, + assertCurrent: vi.fn(), + generate: vi.fn() } - expect(first.request.systemPrompt).toContain('GIF/animation inputs') - await expect(first.toolProvider!.callTool('image_gen', input, context)).rejects.toThrow('live Agent thread invocation') - await expect(first.admission!.run('image_gen', undefined, () => other.toolProvider!.callTool('image_gen', input, context))).rejects.toThrow('live Agent thread invocation') - await expect(first.admission!.run('image_gen', undefined, () => first.toolProvider!.callTool('image_gen', input, { ...context, route: { ...route, threadId: 'foreign' } }))).rejects.toThrow('outside') - sender.emit('did-start-navigation') - await expect(first.admission!.run('image_gen', undefined, () => first.toolProvider!.callTool('image_gen', input, context))).rejects.toThrow('no longer active') - expect(generator.generate).not.toHaveBeenCalled() - } finally { first.dispose!(); other.dispose!() } - }) + const request: LLMChatReq = { ...scope, messages: [] } + const options = { local: true, terminalEnabled: false, createImageGenerator: () => generator } + const first = prepareCanvasAgentTools(request, invocation(), options) + const other = prepareCanvasAgentTools(request, invocation(), options) + const input = { prompt: 'animated', gif: {} }, + context = { route, runId: 'gif-owner' } + try { + const tool = first.toolProvider!.listTools().find((tool) => tool.name === 'image_gen')! + if (gifEnabled) { + expect(tool.inputSchema).toHaveProperty('properties.gif') + expect(first.request.systemPrompt).toContain('explicitly enabled GIF OUTPUT') + } else { + expect(tool.inputSchema).not.toHaveProperty('properties.gif') + expect(first.request.systemPrompt).toContain('GIF output is disabled') + } + expect(first.request.systemPrompt).toContain('GIF/animation inputs') + await expect(first.toolProvider!.callTool('image_gen', input, context)).rejects.toThrow( + 'live Agent thread invocation' + ) + await expect( + first.admission!.run('image_gen', undefined, () => + other.toolProvider!.callTool('image_gen', input, context) + ) + ).rejects.toThrow('live Agent thread invocation') + await expect( + first.admission!.run('image_gen', undefined, () => + first.toolProvider!.callTool('image_gen', input, { + ...context, + route: { ...route, threadId: 'foreign' } + }) + ) + ).rejects.toThrow('outside') + sender.emit('did-start-navigation') + await expect( + first.admission!.run('image_gen', undefined, () => + first.toolProvider!.callTool('image_gen', input, context) + ) + ).rejects.toThrow('no longer active') + expect(generator.generate).not.toHaveBeenCalled() + } finally { + first.dispose!() + other.dispose!() + } + } + ) it('keeps recent-image edits under the same request owner, foreign route and navigation guards', async () => { const { prepareCanvasAgentTools } = await import('./canvasAgentTools') - const generator = { approval: { backend: 'codex-json-oauth' as const, endpoint: 'https://chatgpt.com/backend-api/codex', profileId: 'selected' }, assertCurrent: vi.fn(), generate: vi.fn(), edit: vi.fn() } + const generator = { + approval: { + backend: 'codex-json-oauth' as const, + endpoint: 'https://images.example.test/backend', + profileId: 'selected' + }, + assertCurrent: vi.fn(), + generate: vi.fn(), + edit: vi.fn() + } const settings = { local: true, terminalEnabled: false, createImageGenerator: () => generator } const request: LLMChatReq = { ...scope, messages: [] } const first = prepareCanvasAgentTools(request, invocation(), settings) const other = prepareCanvasAgentTools(request, invocation(), settings) - const input = { prompt: 'edit only owned image', num_last_images_to_include: 1 }, context = { route, runId: 'edit-owner' } + const input = { prompt: 'edit only owned image', num_last_images_to_include: 1 }, + context = { route, runId: 'edit-owner' } try { expect(first.request.systemPrompt).toContain('num_last_images_to_include') expect(first.request.systemPrompt).toContain('PNG/JPEG') - expect(first.request.systemPrompt).not.toContain('Local/recent reference edits and GIF are not admitted') - await expect(first.toolProvider!.callTool('image_gen', input, context)).rejects.toThrow('live Agent thread invocation') - await expect(first.admission!.run('image_gen', undefined, () => other.toolProvider!.callTool('image_gen', input, context))).rejects.toThrow('live Agent thread invocation') - await expect(first.admission!.run('image_gen', undefined, () => first.toolProvider!.callTool('image_gen', input, { ...context, route: { ...route, threadId: 'other' } }))).rejects.toThrow('outside') + expect(first.request.systemPrompt).not.toContain( + 'Local/recent reference edits and GIF are not admitted' + ) + await expect(first.toolProvider!.callTool('image_gen', input, context)).rejects.toThrow( + 'live Agent thread invocation' + ) + await expect( + first.admission!.run('image_gen', undefined, () => + other.toolProvider!.callTool('image_gen', input, context) + ) + ).rejects.toThrow('live Agent thread invocation') + await expect( + first.admission!.run('image_gen', undefined, () => + first.toolProvider!.callTool('image_gen', input, { + ...context, + route: { ...route, threadId: 'other' } + }) + ) + ).rejects.toThrow('outside') sender.emit('did-start-navigation') - await expect(first.admission!.run('image_gen', undefined, () => first.toolProvider!.callTool('image_gen', input, context))).rejects.toThrow('no longer active') + await expect( + first.admission!.run('image_gen', undefined, () => + first.toolProvider!.callTool('image_gen', input, context) + ) + ).rejects.toThrow('no longer active') expect(generator.edit).not.toHaveBeenCalled() expect(generator.generate).not.toHaveBeenCalled() - } finally { first.dispose!(); other.dispose!() } + } finally { + first.dispose!() + other.dispose!() + } }) it('adds HTML only under its independent local-thread opt-in and rechecks live request authority', async () => { const { prepareCanvasAgentTools } = await import('./canvasAgentTools') - const req = { ...scope, messages: [] }, args = { title: 'App', html: '

ok

' } + const req = { ...scope, messages: [] }, + args = { title: 'App', html: '

ok

' } let enabledFlag = true - const disabled = prepareCanvasAgentTools(req, invocation(), { local: true, terminalEnabled: true, scriptToolsEnabled: () => true, shellToolsEnabled: () => true }) - const enabled = prepareCanvasAgentTools(req, invocation(), { local: true, terminalEnabled: false, htmlAppsEnabled: () => enabledFlag }) + const disabled = prepareCanvasAgentTools(req, invocation(), { + local: true, + terminalEnabled: true, + scriptToolsEnabled: () => true, + shellToolsEnabled: () => true + }) + const enabled = prepareCanvasAgentTools(req, invocation(), { + local: true, + terminalEnabled: false, + htmlAppsEnabled: () => enabledFlag + }) try { - expect(JSON.stringify(disabled.toolProvider!.listTools().find(tool => tool.name === 'show_app')!.inputSchema)).not.toContain('wait_for') - expect(JSON.stringify(enabled.toolProvider!.listTools().find(tool => tool.name === 'show_app')!.inputSchema)).toContain('wait_for') - expect(prepareCanvasAgentTools(req, invocation(), { local: false, terminalEnabled: false, htmlAppsEnabled: () => true }).toolProvider).toBeUndefined() - expect(prepareCanvasAgentTools({ ...req, skillRuntime: { skillId: 'external' } }, invocation(), { local: true, terminalEnabled: false, htmlAppsEnabled: () => true }).toolProvider).toBeUndefined() - await expect(disabled.admission!.run('show_app', undefined, () => disabled.toolProvider!.callTool('show_app', args, { route, runId: 'disabled' }))).rejects.toThrow('Invalid arguments') - await expect(enabled.toolProvider!.callTool('show_app', args, { route, runId: 'outside' })).rejects.toThrow('live Agent thread invocation') + expect( + JSON.stringify( + disabled.toolProvider!.listTools().find((tool) => tool.name === 'show_app')!.inputSchema + ) + ).not.toContain('wait_for') + expect( + JSON.stringify( + enabled.toolProvider!.listTools().find((tool) => tool.name === 'show_app')!.inputSchema + ) + ).toContain('wait_for') + expect( + prepareCanvasAgentTools(req, invocation(), { + local: false, + terminalEnabled: false, + htmlAppsEnabled: () => true + }).toolProvider + ).toBeUndefined() + expect( + prepareCanvasAgentTools({ ...req, skillRuntime: { skillId: 'external' } }, invocation(), { + local: true, + terminalEnabled: false, + htmlAppsEnabled: () => true + }).toolProvider + ).toBeUndefined() + await expect( + disabled.admission!.run('show_app', undefined, () => + disabled.toolProvider!.callTool('show_app', args, { route, runId: 'disabled' }) + ) + ).rejects.toThrow('Invalid arguments') + await expect( + enabled.toolProvider!.callTool('show_app', args, { route, runId: 'outside' }) + ).rejects.toThrow('live Agent thread invocation') enabledFlag = false - await expect(enabled.admission!.run('show_app', undefined, () => enabled.toolProvider!.callTool('show_app', args, { route, runId: 'revoked' }))).rejects.toThrow('disabled') + await expect( + enabled.admission!.run('show_app', undefined, () => + enabled.toolProvider!.callTool('show_app', args, { route, runId: 'revoked' }) + ) + ).rejects.toThrow('disabled') sender.emit('did-start-navigation') - await expect(enabled.admission!.run('show_app', undefined, async () => ({ content: 'never' }))).rejects.toThrow('no longer active') - } finally { disabled.dispose!(); enabled.dispose!() } + await expect( + enabled.admission!.run('show_app', undefined, async () => ({ content: 'never' })) + ).rejects.toThrow('no longer active') + } finally { + disabled.dispose!() + enabled.dispose!() + } }) it('exposes general shell only under its independent flag and live document, not Python or terminal grants', async () => { const { prepareCanvasAgentTools } = await import('./canvasAgentTools') const req = { ...scope, messages: [] } - const readOnly = prepareCanvasAgentTools(req, invocation(), { local: true, terminalEnabled: true, scriptToolsEnabled: () => true }) - const enabled = prepareCanvasAgentTools(req, invocation(), { local: true, terminalEnabled: false, shellToolsEnabled: () => true }) + const readOnly = prepareCanvasAgentTools(req, invocation(), { + local: true, + terminalEnabled: true, + scriptToolsEnabled: () => true + }) + const enabled = prepareCanvasAgentTools(req, invocation(), { + local: true, + terminalEnabled: false, + shellToolsEnabled: () => true + }) try { - expect(readOnly.toolProvider!.listTools().map((tool) => tool.name)).not.toContain('shell.execute') + expect(readOnly.toolProvider!.listTools().map((tool) => tool.name)).not.toContain( + 'shell.execute' + ) expect(enabled.toolProvider!.listTools().map((tool) => tool.name)).toContain('shell.execute') - expect(prepareCanvasAgentTools(req, invocation(), { local: false, terminalEnabled: false, shellToolsEnabled: () => true }).toolProvider).toBeUndefined() - expect(prepareCanvasAgentTools({ ...req, skillRuntime: { skillId: 'external' } }, invocation(), { local: true, terminalEnabled: false, shellToolsEnabled: () => true }).toolProvider).toBeUndefined() - await expect(enabled.toolProvider!.callTool('shell.execute', { code: 'echo x' }, { route, runId: 'foreign', workspaceRootDir: 'C:/untrusted' })).rejects.toThrow('live Agent thread invocation') + expect( + prepareCanvasAgentTools(req, invocation(), { + local: false, + terminalEnabled: false, + shellToolsEnabled: () => true + }).toolProvider + ).toBeUndefined() + expect( + prepareCanvasAgentTools({ ...req, skillRuntime: { skillId: 'external' } }, invocation(), { + local: true, + terminalEnabled: false, + shellToolsEnabled: () => true + }).toolProvider + ).toBeUndefined() + await expect( + enabled.toolProvider!.callTool( + 'shell.execute', + { code: 'echo x' }, + { route, runId: 'foreign', workspaceRootDir: 'C:/untrusted' } + ) + ).rejects.toThrow('live Agent thread invocation') sender.emit('did-start-navigation') - await expect(enabled.admission!.run('shell.execute', undefined, async () => ({ content: 'never' }))).rejects.toThrow('no longer active') - } finally { enabled.dispose!(); readOnly.dispose!() } + await expect( + enabled.admission!.run('shell.execute', undefined, async () => ({ content: 'never' })) + ).rejects.toThrow('no longer active') + } finally { + enabled.dispose!() + readOnly.dispose!() + } }) it('keeps the first skill-context guard when a caller tries to prepare again under changed opt-ins', async () => { const { prepareCanvasAgentTools } = await import('./canvasAgentTools') const loadSkills = vi.fn(async () => ({ skills: [], truncated: false })) let enabled = true - const prepared = prepareCanvasAgentTools({ ...scope, messages: [] }, invocation(), { local: true, terminalEnabled: false, loadSkills, skillContextConfig: () => ({ index: enabled, paths: false, revision: 'same-registry' }) }) + const prepared = prepareCanvasAgentTools({ ...scope, messages: [] }, invocation(), { + local: true, + terminalEnabled: false, + loadSkills, + skillContextConfig: () => ({ index: enabled, paths: false, revision: 'same-registry' }) + }) try { const first = await prepared.prepareSkillContext!() - expect(JSON.parse(first).indexEnabled).toBe(true); expect(loadSkills).toHaveBeenCalledOnce() + expect(JSON.parse(first).indexEnabled).toBe(true) + expect(loadSkills).toHaveBeenCalledOnce() enabled = false await expect(prepared.prepareSkillContext!()).rejects.toThrow('settings changed') expect(() => prepared.assertSkillContext!()).toThrow('settings changed') expect(loadSkills).toHaveBeenCalledOnce() - } finally { prepared.dispose!() } + } finally { + prepared.dispose!() + } }) it('cancels pending procedural discovery on navigation without reusing it from another request', async () => { const { prepareCanvasAgentTools } = await import('./canvasAgentTools') let resolve!: (value: { skills: []; truncated: boolean }) => void - const loadSkills = vi.fn(() => new Promise<{ skills: []; truncated: boolean }>((r) => { resolve = r })) - const prepared = prepareCanvasAgentTools({ ...scope, messages: [] }, invocation(), { local: true, terminalEnabled: false, loadSkills }) + const loadSkills = vi.fn( + () => + new Promise<{ skills: []; truncated: boolean }>((r) => { + resolve = r + }) + ) + const prepared = prepareCanvasAgentTools({ ...scope, messages: [] }, invocation(), { + local: true, + terminalEnabled: false, + loadSkills + }) try { expect(prepared.toolProvider!.listTools().map((tool) => tool.name)).toContain('skill') - const pending = prepared.admission!.run('info', undefined, () => prepared.toolProvider!.callTool('info', { kind: 'skill' }, { route, runId: 'skills' })).catch((error) => error) + const pending = prepared + .admission!.run('info', undefined, () => + prepared.toolProvider!.callTool('info', { kind: 'skill' }, { route, runId: 'skills' }) + ) + .catch((error) => error) expect(loadSkills).toHaveBeenCalledOnce() sender.emit('did-start-navigation') expect(await pending).toBeInstanceOf(Error) - await expect(prepared.toolProvider!.callTool('skill', { name: 'x' }, { route, runId: 'new' })).rejects.toThrow() - resolve({ skills: [], truncated: false }); await Promise.resolve() - } finally { resolve?.({ skills: [], truncated: false }); prepared.dispose!() } + await expect( + prepared.toolProvider!.callTool('skill', { name: 'x' }, { route, runId: 'new' }) + ).rejects.toThrow() + resolve({ skills: [], truncated: false }) + await Promise.resolve() + } finally { + resolve?.({ skills: [], truncated: false }) + prepared.dispose!() + } }) it('binds per-service MCP tools to an eligible document, never to remote/explicit skills or an inherited late invocation', async () => { const { prepareCanvasAgentTools } = await import('./canvasAgentTools') const { DEFAULT_CONFIG } = await import('@shared/config/config') - const config = { ...DEFAULT_CONFIG, mcp_config: { ...DEFAULT_CONFIG.mcp_config, client: { servers: [{ id: 'allowed', enabled: true, transport: 'stdio' as const, command: 'configured-only', agentThreadAccess: 'call' as const, agentThreadManage: true }] } } } + const config = { + ...DEFAULT_CONFIG, + mcp_config: { + ...DEFAULT_CONFIG.mcp_config, + client: { + servers: [ + { + id: 'allowed', + enabled: true, + transport: 'stdio' as const, + command: 'configured-only', + agentThreadAccess: 'call' as const, + agentThreadManage: true + } + ] + } + } + } const opts = { local: true, terminalEnabled: false, mcpConfig: () => config } - const first = prepareCanvasAgentTools({ ...scope, messages: [] }, invocation(), opts) + const first = prepareCanvasAgentTools( + { ...scope, messages: [] }, + invocation(), + opts + ) try { - expect(first.request.skillRuntime?.bindings?.[0]?.toolNames).toEqual(expect.arrayContaining(['mcp_list', 'mcp_call', 'mcp_connect', 'mcp_disconnect'])) - expect(prepareCanvasAgentTools({ ...scope, messages: [] }, invocation(), { ...opts, local: false }).toolProvider).toBeUndefined() - expect(prepareCanvasAgentTools({ ...scope, messages: [], skillRuntime: { skillId: 'external' } }, invocation(), opts).toolProvider).toBeUndefined() - await expect(first.toolProvider!.callTool('mcp_list', {}, { route, runId: 'outside' })).rejects.toThrow('live Agent thread invocation') - await expect(first.toolProvider!.callTool('mcp_connect', { server: 'allowed' }, { route, runId: 'outside' })).rejects.toThrow('live Agent thread invocation') + expect(first.request.skillRuntime?.bindings?.[0]?.toolNames).toEqual( + expect.arrayContaining(['mcp_list', 'mcp_call', 'mcp_connect', 'mcp_disconnect']) + ) + expect( + prepareCanvasAgentTools({ ...scope, messages: [] }, invocation(), { ...opts, local: false }) + .toolProvider + ).toBeUndefined() + expect( + prepareCanvasAgentTools( + { ...scope, messages: [], skillRuntime: { skillId: 'external' } }, + invocation(), + opts + ).toolProvider + ).toBeUndefined() + await expect( + first.toolProvider!.callTool('mcp_list', {}, { route, runId: 'outside' }) + ).rejects.toThrow('live Agent thread invocation') + await expect( + first.toolProvider!.callTool( + 'mcp_connect', + { server: 'allowed' }, + { route, runId: 'outside' } + ) + ).rejects.toThrow('live Agent thread invocation') sender.emit('did-start-navigation') - await expect(first.admission!.run('mcp_connect', undefined, async () => ({ content: 'not reached' }))).rejects.toThrow('no longer active') - await expect(first.admission!.run('mcp_list', undefined, async () => ({ content: 'not reached' }))).rejects.toThrow('no longer active') - } finally { first.dispose!() } + await expect( + first.admission!.run('mcp_connect', undefined, async () => ({ content: 'not reached' })) + ).rejects.toThrow('no longer active') + await expect( + first.admission!.run('mcp_list', undefined, async () => ({ content: 'not reached' })) + ).rejects.toThrow('no longer active') + } finally { + first.dispose!() + } }) it('validates app feedback against the stored document, rejects authority extras and isolates scope', async () => { - const document = { title: 'Report', blocks: [{ kind: 'text' as const, text: 'data' }], fields: [{ kind: 'select' as const, id: 'choice', label: 'Pick', options: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] }] } + const document = { + title: 'Report', + blocks: [{ kind: 'text' as const, text: 'data' }], + fields: [ + { + kind: 'select' as const, + id: 'choice', + label: 'Pick', + options: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + } + ] + } const result = channel.request({ kind: 'show_app', document }, 30) document.fields[0].options[0].id = 'changed' const [item] = pending() - expect(item.prompt).toMatchObject({ kind: 'show_app', document: { fields: [{ options: [{ id: 'a' }, { id: 'b' }] }] } }) - expect(() => respond(item.id, { status: 'answered', values: { choice: 'changed' } })).toThrow('Invalid') - expect(() => respond(item.id, { status: 'answered', values: { choice: 'a', approved: true } })).toThrow('Invalid') + expect(item.prompt).toMatchObject({ + kind: 'show_app', + document: { fields: [{ options: [{ id: 'a' }, { id: 'b' }] }] } + }) + expect(() => respond(item.id, { status: 'answered', values: { choice: 'changed' } })).toThrow( + 'Invalid' + ) + expect(() => + respond(item.id, { status: 'answered', values: { choice: 'a', approved: true } }) + ).toThrow('Invalid') expect(() => respond(item.id, { status: 'answered', text: 'a' })).toThrow('Invalid') - expect(() => manager.resolve({ ...scope, conversationId: 'other', interactionId: item.id, answer: { status: 'answered', values: { choice: 'a' } } }, invocation('resolveAgentInteraction'))).toThrow('not active') + expect(() => + manager.resolve( + { + ...scope, + conversationId: 'other', + interactionId: item.id, + answer: { status: 'answered', values: { choice: 'a' } } + }, + invocation('resolveAgentInteraction') + ) + ).toThrow('not active') respond(item.id, { status: 'answered', values: { choice: 'a' } }) expect(await result).toEqual({ status: 'answered', values: { choice: 'a' } }) - expect(() => respond(item.id, { status: 'answered', values: { choice: 'a' } })).toThrow('not active') - }) - it.each(['abort', 'navigation', 'expiry'])('removes declarative displays on %s and rejects late values', async (kind) => { - const controller = new AbortController() - const result = channel.request({ kind: 'show_app', document: { title: 'Report', blocks: [{ kind: 'text', text: 'data' }] } }, 1, controller.signal).catch(() => 'cancelled') - const [item] = pending() - if (kind === 'abort') controller.abort() - else if (kind === 'navigation') sender.emit('did-start-navigation') - else await vi.advanceTimersByTimeAsync(1001) - expect(await result).toEqual(kind === 'expiry' ? { status: 'timeout' } : 'cancelled') - expect(pending()).toEqual([]) - expect(() => respond(item.id, { status: 'answered', values: {} })).toThrow('not active') + expect(() => respond(item.id, { status: 'answered', values: { choice: 'a' } })).toThrow( + 'not active' + ) }) + it.each(['abort', 'navigation', 'expiry'])( + 'removes declarative displays on %s and rejects late values', + async (kind) => { + const controller = new AbortController() + const result = channel + .request( + { + kind: 'show_app', + document: { title: 'Report', blocks: [{ kind: 'text', text: 'data' }] } + }, + 1, + controller.signal + ) + .catch(() => 'cancelled') + const [item] = pending() + if (kind === 'abort') controller.abort() + else if (kind === 'navigation') sender.emit('did-start-navigation') + else await vi.advanceTimersByTimeAsync(1001) + expect(await result).toEqual(kind === 'expiry' ? { status: 'timeout' } : 'cancelled') + expect(pending()).toEqual([]) + expect(() => respond(item.id, { status: 'answered', values: {} })).toThrow('not active') + } + ) it('bounds global app documents and rejects invalid app payloads before retention', async () => { - const channels: AgentThreadInteractionChannel[] = [], promises: Promise[] = [] + const channels: AgentThreadInteractionChannel[] = [], + promises: Promise[] = [] const document = { title: 'Report', blocks: [{ kind: 'text' as const, text: 'data' }] } sender.setMaxListeners(0) try { - await expect(channel.request({ kind: 'show_app', document: { ...document, html: '', '', '', '', 'Fake link', ''])('escapes raw HTML instead of interpreting or silently hiding it %#', body => { + it.each([ + '', + '', + '', + '', + '', + '', + 'Fake link', + '' + ])('escapes raw HTML instead of interpreting or silently hiding it %#', (body) => { const { container } = mount(body) - expect(container.textContent).toBe(body); noAuthority(container) - }) - it.each(['js', 'python', 'shell', 'mermaid', 'math', 'html', 'svg'])('shows %s code as static escaped pre/code, with no run/copy/pin/highlighter UI', language => { - const body = `\`\`\`${language}\n\n\n\`\`\``, { container } = mount(body) - expect(screen.getByText(/notExecuted/).tagName).toBe('CODE'); expect(container.querySelector('pre')).not.toBeNull(); expect(container.textContent).toContain(''); noAuthority(container) + expect(container.textContent).toBe(body) + noAuthority(container) }) + it.each(['js', 'python', 'shell', 'mermaid', 'math', 'html', 'svg'])( + 'shows %s code as static escaped pre/code, with no run/copy/pin/highlighter UI', + (language) => { + const body = `\`\`\`${language}\n\n\n\`\`\``, + { container } = mount(body) + expect(screen.getByText(/notExecuted/).tagName).toBe('CODE') + expect(container.querySelector('pre')).not.toBeNull() + expect(container.textContent).toContain('') + noAuthority(container) + } + ) it.each([ - { body: 'Public **safe** prefix\n\nBea**rer** DECODED_TOKEN', hidden: 'DECODED_TOKEN', visible: 'Bearer [redacted]' }, + { + body: 'Public **safe** prefix\n\nBea**rer** DECODED_TOKEN', + hidden: 'DECODED_TOKEN', + visible: 'Bearer [redacted]' + }, { body: 'Bea`rer` INLINE_TOKEN', hidden: 'INLINE_TOKEN', visible: 'Bearer [redacted]' }, { body: '**Bearer** SPLIT_TOKEN', hidden: 'SPLIT_TOKEN', visible: 'Bearer [redacted]' }, - { body: 'pass**word**=DECODED_PASSWORD', hidden: 'DECODED_PASSWORD', visible: 'password=[redacted]' }, - { body: 'Authori*za*tion: Basic DECODED_AUTH', hidden: 'DECODED_AUTH', visible: 'Authorization: [redacted]' }, - { body: 'https://us**er**:DECODED_URL_PASSWORD@example.invalid/path', hidden: 'DECODED_URL_PASSWORD', visible: '[redacted]@example.invalid' }, - { body: '![Bearer ALT_TOKEN](https://external.invalid/alt)', hidden: 'ALT_TOKEN', visible: 'Bearer [redacted]' }, - { body: '‮Bea**rer** ENTITY_BIDI_TOKEN', hidden: 'ENTITY_BIDI_TOKEN', visible: 'Bearer [redacted]' } - ])('redacts whole decoded text across inline fragments and entities %#', ({ body, hidden, visible }) => { - const before = body, { container } = mount(body) - expect(container.textContent).toContain(visible); expect(container.textContent).not.toContain(hidden); expect(container.querySelector('strong,em,code')).toBeNull(); expect(container.textContent).not.toContain('\u202e'); expect(container.textContent).not.toContain('\u001b'); expect(body).toBe(before); noAuthority(container) - }) + { + body: 'pass**word**=DECODED_PASSWORD', + hidden: 'DECODED_PASSWORD', + visible: 'password=[redacted]' + }, + { + body: 'Authori*za*tion: Basic DECODED_AUTH', + hidden: 'DECODED_AUTH', + visible: 'Authorization: [redacted]' + }, + { + body: 'https://us**er**:DECODED_URL_PASSWORD@example.invalid/path', + hidden: 'DECODED_URL_PASSWORD', + visible: '[redacted]@example.invalid' + }, + { + body: '![Bearer ALT_TOKEN](https://external.invalid/alt)', + hidden: 'ALT_TOKEN', + visible: 'Bearer [redacted]' + }, + { + body: '‮Bea**rer** ENTITY_BIDI_TOKEN', + hidden: 'ENTITY_BIDI_TOKEN', + visible: 'Bearer [redacted]' + } + ])( + 'redacts whole decoded text across inline fragments and entities %#', + ({ body, hidden, visible }) => { + const before = body, + { container } = mount(body) + expect(container.textContent).toContain(visible) + expect(container.textContent).not.toContain(hidden) + expect(container.querySelector('strong,em,code')).toBeNull() + expect(container.textContent).not.toContain('\u202e') + expect(container.textContent).not.toContain('\u001b') + expect(body).toBe(before) + noAuthority(container) + } + ) it('preserves the invalid-ESC fixture as literal replacement text, not a decoded ANSI escape or arbitrary-secret recognition', () => { - const body = '‮Bearer ENTITY_CONTROL_TOKEN', { container } = mount(body) - expect(container.textContent).toContain('\ufffd[31mBearer ENTITY_CONTROL_TOKEN'); expect(container.textContent).not.toContain('\u202e'); expect(container.textContent).not.toContain('\u001b'); expect(container.querySelector('p,strong')).toBeNull(); noAuthority(container) + const body = '‮Bearer ENTITY_CONTROL_TOKEN', + { container } = mount(body) + expect(container.textContent).toContain('\ufffd[31mBearer ENTITY_CONTROL_TOKEN') + expect(container.textContent).not.toContain('\u202e') + expect(container.textContent).not.toContain('\u001b') + expect(container.querySelector('p,strong')).toBeNull() + noAuthority(container) }) it.each([ { body: 'Bearer a**PRIVATE_SUFFIX**', hidden: 'PRIVATE_SUFFIX' }, @@ -63,92 +181,203 @@ describe('bounded formatting-only card body', () => { { body: 'Bearer a~~STRIKE_SUFFIX~~', hidden: 'STRIKE_SUFFIX' }, { body: '![Bearer a**ALT_SUFFIX**](https://external.invalid/p)', hidden: 'ALT_SUFFIX' }, { body: 'password=a**PASSWORD_SUFFIX**', hidden: 'PASSWORD_SUFFIX' } - ])('never lets preformatted redaction markers shield subsequently decoded credential values %#', ({ body, hidden }) => { - const before = body, { container } = mount(body) - expect(container.textContent).toContain('[redacted]'); expect(container.textContent).not.toContain(hidden); expect(container.querySelector('p,strong,em,code,del')).toBeNull(); expect(body).toBe(before); noAuthority(container) - }) + ])( + 'never lets preformatted redaction markers shield subsequently decoded credential values %#', + ({ body, hidden }) => { + const before = body, + { container } = mount(body) + expect(container.textContent).toContain('[redacted]') + expect(container.textContent).not.toContain(hidden) + expect(container.querySelector('p,strong,em,code,del')).toBeNull() + expect(body).toBe(before) + noAuthority(container) + } + ) it('bounds actual formatted parser candidates as well as original body units, never parsing redaction expansion past 4000', () => { - const body = 'Bearer x\n'.repeat(444), plain = formatToolCallValue(body).text, { container } = mount(body) - expect(body.length).toBe(3996); expect(plain.length).toBe(7992); expect(container.querySelector('p,strong')).toBeNull(); expect(container.textContent).toBe(plain); noAuthority(container) + const body = 'Bearer x\n'.repeat(444), + plain = formatToolCallValue(body).text, + { container } = mount(body) + expect(body.length).toBe(3996) + expect(plain.length).toBe(7992) + expect(container.querySelector('p,strong')).toBeNull() + expect(container.textContent).toBe(plain) + noAuthority(container) }) it.each([ { label: 'password', value: 'JSON_PRIVATE_QUOTE"tail' }, { label: 'api_key', value: 'JSON_PRIVATE_STAR**tail**' }, { label: 'token', value: 'JSON_PRIVATE_BACKSLASH\\tail' }, { label: 'secret', value: 'JSON_PRIVATE_ENTITYBtail' } - ])('preserves existing JSON sensitive-row redaction before Markdown could reinterpret escaped values label=$label', row => { - const body = JSON.stringify(row), plain = formatToolCallValue(body).text, { container } = mount(body) - expect(plain).not.toContain('JSON_PRIVATE_'); expect(container.textContent).toBe(plain); expect(container.textContent).not.toContain('JSON_PRIVATE_'); expect(container.querySelector('p,strong,em')).toBeNull(); expect(body).toContain('JSON_PRIVATE_'); noAuthority(container) - }) + ])( + 'preserves existing JSON sensitive-row redaction before Markdown could reinterpret escaped values label=$label', + (row) => { + const body = JSON.stringify(row), + plain = formatToolCallValue(body).text, + { container } = mount(body) + expect(plain).not.toContain('JSON_PRIVATE_') + expect(container.textContent).toBe(plain) + expect(container.textContent).not.toContain('JSON_PRIVATE_') + expect(container.querySelector('p,strong,em')).toBeNull() + expect(body).toContain('JSON_PRIVATE_') + noAuthority(container) + } + ) it('keeps valid JSON objects and arrays as formatted escaped data rather than reinterpreting nested row values or syntax', () => { - const body = JSON.stringify({ rows: [{ label: 'password', value: 'NESTED_PRIVATE"tail' }, { label: 'Public', value: '**Literal public JSON** ' }] }), { container } = mount(body) - expect(container.textContent).toBe(formatToolCallValue(body).text); expect(container.textContent).not.toContain('NESTED_PRIVATE'); expect(container.textContent).toContain('**Literal public JSON**'); expect(container.querySelector('p,strong,em')).toBeNull(); noAuthority(container) + const body = JSON.stringify({ + rows: [ + { label: 'password', value: 'NESTED_PRIVATE"tail' }, + { label: 'Public', value: '**Literal public JSON** ' } + ] + }), + { container } = mount(body) + expect(container.textContent).toBe(formatToolCallValue(body).text) + expect(container.textContent).not.toContain('NESTED_PRIVATE') + expect(container.textContent).toContain('**Literal public JSON**') + expect(container.querySelector('p,strong,em')).toBeNull() + noAuthority(container) }) it('does not reparse a redacted replacement into Markdown or resource syntax', () => { - const { container } = mount('**Public** Bea**rer** TOKEN\n\n![Still alt](https://external.invalid/p)') - expect(container.textContent).toContain('Public Bearer [redacted]'); expect(container.textContent).toContain('Still alt'); expect(container.querySelector('p,strong,em')).toBeNull(); noAuthority(container) + const { container } = mount( + '**Public** Bea**rer** TOKEN\n\n![Still alt](https://external.invalid/p)' + ) + expect(container.textContent).toContain('Public Bearer [redacted]') + expect(container.textContent).toContain('Still alt') + expect(container.querySelector('p,strong,em')).toBeNull() + noAuthority(container) }) it('keeps the existing formatter limits and does not claim to detect arbitrary plain secrets', () => { - const body = 'Ordinary private-looking string NOT_A_RECOGNIZED_CREDENTIAL\n\n**Public**', { container } = mount(body) - expect(container.textContent).toContain('NOT_A_RECOGNIZED_CREDENTIAL'); expect(screen.getByText('Public').tagName).toBe('STRONG'); noAuthority(container) - }) - it.each([undefined, null, false, true, 1, {}, [], ['**forged**'], Object('**boxed**')])('never coerces or parses nonprimitive body %#', body => { - const { container } = mount(body); expect(container).toBeEmptyDOMElement() + const body = 'Ordinary private-looking string NOT_A_RECOGNIZED_CREDENTIAL\n\n**Public**', + { container } = mount(body) + expect(container.textContent).toContain('NOT_A_RECOGNIZED_CREDENTIAL') + expect(screen.getByText('Public').tagName).toBe('STRONG') + noAuthority(container) }) + it.each([undefined, null, false, true, 1, {}, [], ['**forged**'], Object('**boxed**')])( + 'never coerces or parses nonprimitive body %#', + (body) => { + const { container } = mount(body) + expect(container).toBeEmptyDOMElement() + } + ) it('does not invoke conversion hooks in malformed body values', () => { - const toString = vi.fn(() => '**forged**'), toJSON = vi.fn(() => '**forged**'), { container } = mount({ toString, toJSON }) - expect(container).toBeEmptyDOMElement(); expect(toString).not.toHaveBeenCalled(); expect(toJSON).not.toHaveBeenCalled() - }) - it.each(['', ' ', '\n\t', '\u0001\u202e'])('preserves whitespace-only body display and adds no default syntax or authority %#', body => { - const { container } = mount(body); expect(container.textContent).toBe(formatToolCallValue(body).text); expect(container.querySelector('p,strong')).toBeNull(); noAuthority(container) - }) - it.each([4000, 4001])('applies the input bound before parsing without changing legacy body bytes length=%s', length => { - const body = '**Bold**\n\n' + 'x'.repeat(length - 10), before = body, { container } = mount(body) - expect(body.length).toBe(length) - if (length === 4000) expect(screen.getByText('Bold').tagName).toBe('STRONG') - else { expect(container.querySelector('strong,p')).toBeNull(); expect(container.textContent).toBe(body) } - expect(body).toBe(before); noAuthority(container) + const toString = vi.fn(() => '**forged**'), + toJSON = vi.fn(() => '**forged**'), + { container } = mount({ toString, toJSON }) + expect(container).toBeEmptyDOMElement() + expect(toString).not.toHaveBeenCalled() + expect(toJSON).not.toHaveBeenCalled() }) + it.each(['', ' ', '\n\t', '\u0001\u202e'])( + 'preserves whitespace-only body display and adds no default syntax or authority %#', + (body) => { + const { container } = mount(body) + expect(container.textContent).toBe(formatToolCallValue(body).text) + expect(container.querySelector('p,strong')).toBeNull() + noAuthority(container) + } + ) + it.each([4000, 4001])( + 'applies the input bound before parsing without changing legacy body bytes length=%s', + (length) => { + const body = '**Bold**\n\n' + 'x'.repeat(length - 10), + before = body, + { container } = mount(body) + expect(body.length).toBe(length) + if (length === 4000) expect(screen.getByText('Bold').tagName).toBe('STRONG') + else { + expect(container.querySelector('strong,p')).toBeNull() + expect(container.textContent).toBe(body) + } + expect(body).toBe(before) + noAuthority(container) + } + ) it('uses UTF-16 units, not schema characters, as the local parser input bound', () => { - const body = '**Bold**' + '😀'.repeat(1997), { container } = mount(body) - expect(body.length).toBeGreaterThan(LIMITS.input); expect(container.querySelector('strong')).toBeNull(); expect(container.textContent).toBe(body); noAuthority(container) - }) - it('falls back for long legacy input without losing existing display redaction or exceeding its text cap', () => { - const body = '**No parsing**\nBearer LONG_LEGACY_TOKEN\n' + 'x'.repeat(18000), { container } = mount(body) - expect(container.querySelector('strong')).toBeNull(); expect(container.textContent).toBe(formatToolCallValue(body).text); expect(container.textContent).not.toContain('LONG_LEGACY_TOKEN'); expect(container.textContent!.length).toBeLessThanOrEqual(16384); noAuthority(container) - }) - it.each(['Body[^n].\n\n[^n]: **Footnote**', 'Footnote with Bearer TOKEN[^n].\n\n[^n]: text'])('uses escaped-source fallback for generated footnote metadata without global IDs or linkbacks %#', body => { - const { container } = mount(body); expect(container.textContent).toBe(formatToolCallValue(body).text); expect(container.querySelector('p,strong,sup,section')).toBeNull(); noAuthority(container) - }) - it.each([21, 22, 23, 24, 25])('enforces post-parse depth on nested blockquotes depth=%s', count => { - const body = '> '.repeat(count) + '**Nested**', { container } = mount(body) - if (count <= LIMITS.depth - 3) expect(container.querySelector('strong')).not.toBeNull() - else { expect(container.querySelector('strong,blockquote')).toBeNull(); expect(container.textContent).toBe(body) } - noAuthority(container) - }) - it.each([260, 341, 342])('checks the actual parsed-node boundary including the retained 260-span positive fixture count=%s', count => { - const body = Array.from({ length: count }, () => '**x**').join(' '), { container } = mount(body) - expect(body.length).toBeLessThan(LIMITS.input) - if (count <= 341) expect(container.querySelectorAll('strong')).toHaveLength(count) - else { expect(container.querySelector('strong')).toBeNull(); expect(container.textContent).toBe(body) } + const body = '**Bold**' + '😀'.repeat(1997), + { container } = mount(body) + expect(body.length).toBeGreaterThan(LIMITS.input) + expect(container.querySelector('strong')).toBeNull() + expect(container.textContent).toBe(body) noAuthority(container) }) - it.each([256, 257, 300, 341])('also bounds rebuilt heading expansion before emitting React nodes count=%s', count => { - const body = Array.from({ length: count }, () => '# x').join('\n\n'), { container } = mount(body) - expect(body.length).toBeLessThan(LIMITS.input) - if (count === 256) expect(container.querySelectorAll('strong')).toHaveLength(count) - else { expect(container.querySelector('p,strong')).toBeNull(); expect(container.textContent).toBe(body) } - noAuthority(container) - }) - it.each([20, 21])('also bounds the depth added by heading-to-paragraph/strong conversion quoteDepth=%s', count => { - const body = '> '.repeat(count) + '# **Nested**', { container } = mount(body) - if (count === 20) expect(container.querySelector('strong')).not.toBeNull() - else { expect(container.querySelector('strong,blockquote')).toBeNull(); expect(container.textContent).toBe(body) } + it('falls back for long legacy input without losing existing display redaction or exceeding its text cap', () => { + const body = '**No parsing**\nBearer LONG_LEGACY_TOKEN\n' + 'x'.repeat(18000), + { container } = mount(body) + expect(container.querySelector('strong')).toBeNull() + expect(container.textContent).toBe(formatToolCallValue(body).text) + expect(container.textContent).not.toContain('LONG_LEGACY_TOKEN') + expect(container.textContent!.length).toBeLessThanOrEqual(16384) noAuthority(container) }) + it.each(['Body[^n].\n\n[^n]: **Footnote**', 'Footnote with Bearer TOKEN[^n].\n\n[^n]: text'])( + 'uses escaped-source fallback for generated footnote metadata without global IDs or linkbacks %#', + (body) => { + const { container } = mount(body) + expect(container.textContent).toBe(formatToolCallValue(body).text) + expect(container.querySelector('p,strong,sup,section')).toBeNull() + noAuthority(container) + } + ) + it.each([21, 22, 23, 24, 25])( + 'enforces post-parse depth on nested blockquotes depth=%s', + (count) => { + const body = '> '.repeat(count) + '**Nested**', + { container } = mount(body) + if (count <= LIMITS.depth - 3) expect(container.querySelector('strong')).not.toBeNull() + else { + expect(container.querySelector('strong,blockquote')).toBeNull() + expect(container.textContent).toBe(body) + } + noAuthority(container) + } + ) + it.each([260, 341, 342])( + 'checks the actual parsed-node boundary including the retained 260-span positive fixture count=%s', + (count) => { + const body = Array.from({ length: count }, () => '**x**').join(' '), + { container } = mount(body) + expect(body.length).toBeLessThan(LIMITS.input) + if (count <= 341) expect(container.querySelectorAll('strong')).toHaveLength(count) + else { + expect(container.querySelector('strong')).toBeNull() + expect(container.textContent).toBe(body) + } + noAuthority(container) + } + ) + it.each([256, 257, 300, 341])( + 'also bounds rebuilt heading expansion before emitting React nodes count=%s', + (count) => { + const body = Array.from({ length: count }, () => '# x').join('\n\n'), + { container } = mount(body) + expect(body.length).toBeLessThan(LIMITS.input) + if (count === 256) expect(container.querySelectorAll('strong')).toHaveLength(count) + else { + expect(container.querySelector('p,strong')).toBeNull() + expect(container.textContent).toBe(body) + } + noAuthority(container) + } + ) + it.each([20, 21])( + 'also bounds the depth added by heading-to-paragraph/strong conversion quoteDepth=%s', + (count) => { + const body = '> '.repeat(count) + '# **Nested**', + { container } = mount(body) + if (count === 20) expect(container.querySelector('strong')).not.toBeNull() + else { + expect(container.querySelector('strong,blockquote')).toBeNull() + expect(container.textContent).toBe(body) + } + noAuthority(container) + } + ) it('renders malformed ordinary Markdown as escaped text or static formatting, never an error/control', () => { - const body = '**unclosed\n\n[broken](\n\n`unclosed\n\n> quote', { container } = mount(body) - expect(container.textContent).toContain('**unclosed'); expect(container.textContent).toContain('[broken]('); noAuthority(container) + const body = '**unclosed\n\n[broken](\n\n`unclosed\n\n> quote', + { container } = mount(body) + expect(container.textContent).toContain('**unclosed') + expect(container.textContent).toContain('[broken](') + noAuthority(container) }) it('draws no empty lines between formatted blocks, shows list markers, and keeps the line breaks of plain text', () => { const { container } = mount('Intro line\n\n- First item\n- Second item') diff --git a/packages/app/src/renderer/src/pages/ChatPage/components/AgentThreadInteractionPanel.test.tsx b/packages/app/src/renderer/src/pages/ChatPage/components/AgentThreadInteractionPanel.test.tsx index 078292487..f7242a996 100644 --- a/packages/app/src/renderer/src/pages/ChatPage/components/AgentThreadInteractionPanel.test.tsx +++ b/packages/app/src/renderer/src/pages/ChatPage/components/AgentThreadInteractionPanel.test.tsx @@ -6,11 +6,27 @@ import type { AgentThreadInteraction } from '@shared/api/agentThreadInteraction' import AgentThreadInteractionPanel from './AgentThreadInteractionPanel' const mocks = vi.hoisted(() => ({ list: vi.fn(), resolve: vi.fn() })) -vi.mock('../../../utils/windowUtils', () => ({ api: () => ({ svcLLMProxy: { listAgentInteractions: mocks.list, resolveAgentInteraction: mocks.resolve } }) })) +vi.mock('../../../utils/windowUtils', () => ({ + api: () => ({ + svcLLMProxy: { listAgentInteractions: mocks.list, resolveAgentInteraction: mocks.resolve } + }) +})) vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) })) -const route = { channel: 'canvas', scopeType: 'thread', scopeId: 'project', threadId: 'pane' } as const -const question = (id = 'question-a'): AgentThreadInteraction => ({ id, expiresAt: Date.now() + 60000, prompt: { kind: 'ask_user', question: `Question ${id}`, multiline: true } }) -const poll = () => act(async () => { await vi.advanceTimersByTimeAsync(500) }) +const route = { + channel: 'canvas', + scopeType: 'thread', + scopeId: 'project', + threadId: 'pane' +} as const +const question = (id = 'question-a'): AgentThreadInteraction => ({ + id, + expiresAt: Date.now() + 60000, + prompt: { kind: 'ask_user', question: `Question ${id}`, multiline: true } +}) +const poll = () => + act(async () => { + await vi.advanceTimersByTimeAsync(500) + }) /** The card's option buttons say how they are drawn: filled (data-primary) and/or the error colour (data-danger). */ const expectButtonStyle = (button: HTMLElement, filled: boolean, danger: boolean) => { expect(button.getAttribute('data-primary')).toBe(filled ? 'true' : null) @@ -20,336 +36,1092 @@ const card = () => screen.getByTestId('agent-prompt-card') /** An expired card stays, dimmed, with its state and without any control. */ const expectExpired = () => { expect(screen.queryAllByRole('button')).toHaveLength(0) - expect(screen.getByTestId('chat-prompt-card-state')).toHaveTextContent('chat.agent_interaction.state_expired') + expect(screen.getByTestId('chat-prompt-card-state')).toHaveTextContent( + 'chat.agent_interaction.state_expired' + ) } const mount = async (item = question()) => { mocks.list.mockResolvedValue({ interactions: [item] }) const view = render() - await act(async () => { await Promise.resolve() }) + await act(async () => { + await Promise.resolve() + }) return view } -beforeEach(() => { vi.useFakeTimers(); mocks.list.mockReset(); mocks.resolve.mockReset(); mocks.resolve.mockResolvedValue(undefined) }) -afterEach(() => { cleanup(); vi.useRealTimers() }) +beforeEach(() => { + vi.useFakeTimers() + mocks.list.mockReset() + mocks.resolve.mockReset() + mocks.resolve.mockResolvedValue(undefined) +}) +afterEach(() => { + cleanup() + vi.useRealTimers() +}) describe('Agent thread interaction UI', () => { it('formats only body Markdown while keeping every context and an approve-named choice inert until its exact click', async () => { - const body = '**Body strong** and *Body emphasis* and ~~Body removed~~\n\n> Body quote\n\n- Body list\n\n```mermaid\nflowchart TD\nA-->B\n```\n\n| Key | Value |\n| --- | --- |\n| Body table | Data |', prompt = { kind: 'show_card' as const, title: '**Literal title**', icon: '*I*', subtitle: '*Literal subtitle*', footer: '**Literal footer**', fields: [{ label: '*Label*', value: '**Literal field**' }], body, accent: 'success' as const, actions: [{ id: 'approve', label: '**Explicit feedback**', style: 'primary' as const }] } + const body = + '**Body strong** and *Body emphasis* and ~~Body removed~~\n\n> Body quote\n\n- Body list\n\n```mermaid\nflowchart TD\nA-->B\n```\n\n| Key | Value |\n| --- | --- |\n| Body table | Data |', + prompt = { + kind: 'show_card' as const, + title: '**Literal title**', + icon: '*I*', + subtitle: '*Literal subtitle*', + footer: '**Literal footer**', + fields: [{ label: '*Label*', value: '**Literal field**' }], + body, + accent: 'success' as const, + actions: [{ id: 'approve', label: '**Explicit feedback**', style: 'primary' as const }] + } await mount({ id: 'body-format', expiresAt: Date.now() + 60000, prompt }) - expect(screen.getByText('Body strong').tagName).toBe('STRONG'); expect(screen.getByText('Body emphasis').tagName).toBe('EM'); expect(screen.getByText('Body removed').tagName).toBe('DEL'); expect(screen.getByText('Body quote').closest('blockquote')).not.toBeNull(); expect(screen.getByText('Body list').closest('li')).not.toBeNull(); expect(screen.getByText('Body table').closest('td')).not.toBeNull() - expect(screen.getByText(/flowchart TD/).tagName).toBe('CODE'); expect(screen.getByText(/flowchart TD/).closest('pre')).not.toBeNull() - for (const text of [prompt.title, prompt.subtitle, prompt.footer, '*Label*: **Literal field**']) expect(screen.getByText(text).querySelector('strong,em')).toBeNull() - expect(screen.getByText(prompt.icon)).toHaveAttribute('aria-hidden', 'true'); expect(screen.queryByRole('heading')).not.toBeInTheDocument(); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); expect(screen.queryByRole('status')).not.toBeInTheDocument(); expect(screen.getAllByRole('button')).toHaveLength(1); expect(document.querySelector('a,img,script,input,textarea,svg')).toBeNull(); expect(mocks.resolve).not.toHaveBeenCalled() - await act(async () => { fireEvent.click(screen.getByRole('button', { name: prompt.actions[0].label })) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'body-format', answer: { status: 'answered', actionId: 'approve' } }); expect(prompt.body).toBe(body) + expect(screen.getByText('Body strong').tagName).toBe('STRONG') + expect(screen.getByText('Body emphasis').tagName).toBe('EM') + expect(screen.getByText('Body removed').tagName).toBe('DEL') + expect(screen.getByText('Body quote').closest('blockquote')).not.toBeNull() + expect(screen.getByText('Body list').closest('li')).not.toBeNull() + expect(screen.getByText('Body table').closest('td')).not.toBeNull() + expect(screen.getByText(/flowchart TD/).tagName).toBe('CODE') + expect(screen.getByText(/flowchart TD/).closest('pre')).not.toBeNull() + for (const text of [prompt.title, prompt.subtitle, prompt.footer, '*Label*: **Literal field**']) + expect(screen.getByText(text).querySelector('strong,em')).toBeNull() + expect(screen.getByText(prompt.icon)).toHaveAttribute('aria-hidden', 'true') + expect(screen.queryByRole('heading')).not.toBeInTheDocument() + expect(screen.queryByRole('alert')).not.toBeInTheDocument() + expect(screen.queryByRole('status')).not.toBeInTheDocument() + expect(screen.getAllByRole('button')).toHaveLength(1) + expect(document.querySelector('a,img,script,input,textarea,svg')).toBeNull() + expect(mocks.resolve).not.toHaveBeenCalled() + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: prompt.actions[0].label })) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'body-format', + answer: { status: 'answered', actionId: 'approve' } + }) + expect(prompt.body).toBe(body) }) it('reduces body links, images and task boxes to read-only text without introducing another input or feedback button', async () => { - const body = '[Visible label](https://external.invalid/link)\n\n![Visible alt](file:///private/probe.png)\n\n- [x] Body completed task\n- [ ] Body pending task\n\n' - await mount({ id: 'body-inert', expiresAt: Date.now() + 60000, prompt: { kind: 'show_card', title: 'Original feedback title', body, actions: [{ id: 'a', label: 'Only offered feedback' }] } }) - expect(screen.getByText('Visible label')).toBeInTheDocument(); expect(screen.getByText('Visible alt')).toBeInTheDocument(); expect(screen.getByText(/\[x\] Body completed task/)).toBeInTheDocument(); expect(screen.getByText(/\[ \] Body pending task/)).toBeInTheDocument(); expect(screen.getByText('')).toBeInTheDocument() - expect(document.querySelector('a,img,input,textarea,script,iframe,svg')).toBeNull(); expect(screen.getAllByRole('button')).toHaveLength(1); expect(mocks.resolve).not.toHaveBeenCalled() + const body = + '[Visible label](https://external.invalid/link)\n\n![Visible alt](file:///hidden/probe.png)\n\n- [x] Body completed task\n- [ ] Body pending task\n\n' + await mount({ + id: 'body-inert', + expiresAt: Date.now() + 60000, + prompt: { + kind: 'show_card', + title: 'Original feedback title', + body, + actions: [{ id: 'a', label: 'Only offered feedback' }] + } + }) + expect(screen.getByText('Visible label')).toBeInTheDocument() + expect(screen.getByText('Visible alt')).toBeInTheDocument() + expect(screen.getByText(/\[x\] Body completed task/)).toBeInTheDocument() + expect(screen.getByText(/\[ \] Body pending task/)).toBeInTheDocument() + expect(screen.getByText('')).toBeInTheDocument() + expect(document.querySelector('a,img,input,textarea,script,iframe,svg')).toBeNull() + expect(screen.getAllByRole('button')).toHaveLength(1) + expect(mocks.resolve).not.toHaveBeenCalled() }) it('redacts entity-decoded and inline-split credentials from body display without rewriting feedback data', async () => { - const body = 'Public **safe** prefix\n\nBea**rer** ENTITY_BODY_SECRET', prompt = { kind: 'show_card' as const, title: 'Body redaction', body, actions: [{ id: 'a', label: 'Explicit feedback' }] } + const body = 'Public **safe** prefix\n\nBea**rer** ENTITY_BODY_SECRET', + prompt = { + kind: 'show_card' as const, + title: 'Body redaction', + body, + actions: [{ id: 'a', label: 'Explicit feedback' }] + } await mount({ id: 'body-decoded', expiresAt: Date.now() + 60000, prompt }) - expect(document.body.textContent).toContain('Bearer [redacted]'); expect(document.body.textContent).not.toContain('ENTITY_BODY_SECRET'); expect(screen.getByText(/Public safe prefix/).querySelector('strong')).toBeNull(); expect(prompt.body).toBe(body); expect(mocks.resolve).not.toHaveBeenCalled() - }) - it.each([undefined, null, false, 1, {}, [], ['✓'], Object('✓'), { toJSON: () => '✓' }, { toString: () => '✓' }, 'x'.repeat(65), '😀'.repeat(33), '', ' ', '\n\t', '\u0001\u202e'])('omits empty or forged live icon decoration without spacing, conversion, resources or default %#', async icon => { - const prompt = { kind: 'show_card' as const, title: 'Original undecorated title', icon, actions: [{ id: 'a', label: 'A' }] } - await mount({ id: 'icon-fallback', expiresAt: Date.now() + 60000, prompt } as never) - const title = screen.getByText(prompt.title); expect(title.textContent).toBe(prompt.title); expect(title.querySelector('span')).toBeNull(); expect(title.querySelector('[aria-hidden]')).toBeNull() - expect(document.querySelector('img,a,script,input,textarea')).toBeNull(); expect(mocks.resolve).not.toHaveBeenCalled(); expect(screen.getAllByRole('button')).toHaveLength(1) + expect(document.body.textContent).toContain('Bearer [redacted]') + expect(document.body.textContent).not.toContain('ENTITY_BODY_SECRET') + expect(screen.getByText(/Public safe prefix/).querySelector('strong')).toBeNull() + expect(prompt.body).toBe(body) + expect(mocks.resolve).not.toHaveBeenCalled() }) + it.each([ + undefined, + null, + false, + 1, + {}, + [], + ['✓'], + Object('✓'), + { toJSON: () => '✓' }, + { toString: () => '✓' }, + 'x'.repeat(65), + '😀'.repeat(33), + '', + ' ', + '\n\t', + '\u0001\u202e' + ])( + 'omits empty or forged live icon decoration without spacing, conversion, resources or default %#', + async (icon) => { + const prompt = { + kind: 'show_card' as const, + title: 'Original undecorated title', + icon, + actions: [{ id: 'a', label: 'A' }] + } + await mount({ id: 'icon-fallback', expiresAt: Date.now() + 60000, prompt } as never) + const title = screen.getByText(prompt.title) + expect(title.textContent).toBe(prompt.title) + expect(title.querySelector('span')).toBeNull() + expect(title.querySelector('[aria-hidden]')).toBeNull() + expect(document.querySelector('img,a,script,input,textarea')).toBeNull() + expect(mocks.resolve).not.toHaveBeenCalled() + expect(screen.getAllByRole('button')).toHaveLength(1) + } + ) it('ignores inherited icon and never invokes malformed icon conversion hooks', async () => { - const toJSON = vi.fn(() => '✓'), toString = vi.fn(() => '✓'), prompt = Object.assign(Object.create({ icon: 'INHERITED_ICON_IGNORE' }), { kind: 'show_card' as const, title: 'Own icon only', actions: [{ id: 'a', label: 'A' }] }) + const toJSON = vi.fn(() => '✓'), + toString = vi.fn(() => '✓'), + prompt = Object.assign(Object.create({ icon: 'INHERITED_ICON_IGNORE' }), { + kind: 'show_card' as const, + title: 'Own icon only', + actions: [{ id: 'a', label: 'A' }] + }) const view = await mount({ id: 'icon-own', expiresAt: Date.now() + 60000, prompt }) - expect(screen.queryByText('INHERITED_ICON_IGNORE')).not.toBeInTheDocument(); expect(screen.getByText(prompt.title).querySelector('span')).toBeNull(); view.unmount() + expect(screen.queryByText('INHERITED_ICON_IGNORE')).not.toBeInTheDocument() + expect(screen.getByText(prompt.title).querySelector('span')).toBeNull() + view.unmount() for (const icon of [{ toJSON, toString }, Object.assign(Object('✓'), { toJSON, toString })]) { - const next = await mount({ id: 'icon-hooks', expiresAt: Date.now() + 60000, prompt: { ...prompt, icon } } as never) - expect(screen.getByText(prompt.title).querySelector('span')).toBeNull(); next.unmount() + const next = await mount({ + id: 'icon-hooks', + expiresAt: Date.now() + 60000, + prompt: { ...prompt, icon } + } as never) + expect(screen.getByText(prompt.title).querySelector('span')).toBeNull() + next.unmount() } - expect(toJSON).not.toHaveBeenCalled(); expect(toString).not.toHaveBeenCalled(); expect(mocks.resolve).not.toHaveBeenCalled() - }) - it.each(['primary', 'secondary', 'danger'] as const)('redacts icon decoration only, preserving original title, fixed button styles and actual status independence style=%s', async style => { - const icon = '\u001b[31mBearer ICON_UI_SECRET\u001b[0m\u202e', prompt = { kind: 'show_card' as const, title: 'Accessible unchanged title', icon, subtitle: '', footer: 'Closing context', fields: [{ label: 'State', value: 'Not approval' }], accent: 'success' as const, actions: [{ id: 'approve', label: 'Explicit feedback', style }] } - await mount({ id: 'icon-styles', expiresAt: Date.now() + 60000, prompt }) - const mark = screen.getByText('Bearer [redacted]'), title = screen.getByText(prompt.title), button = screen.getByRole('button', { name: 'Explicit feedback' }) - expect(title).toHaveAccessibleName(''); expect(title.textContent).toBe('Bearer [redacted]' + prompt.title); expect(mark).toHaveAttribute('aria-hidden', 'true'); expect(title.firstChild).toBe(mark) - expectButtonStyle(button, style !== 'secondary', style === 'danger') - expect(card()).not.toHaveAttribute('icon'); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); expect(screen.queryByRole('status')).not.toBeInTheDocument() - expect(document.body.textContent).not.toContain('ICON_UI_SECRET'); expect(document.body.textContent).not.toContain('\u202e'); expect(prompt.icon).toBe(icon); expect(mocks.resolve).not.toHaveBeenCalled() - await act(async () => { fireEvent.click(button) }); expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'icon-styles', answer: { status: 'answered', actionId: 'approve' } }) - }) - it.each(['no dismiss button', 'expiry'] as const)('keeps decorative icons passive during %s', async ending => { - await mount({ id: 'icon-end', expiresAt: Date.now() + 10, prompt: { kind: 'show_card', title: 'Decorative icon lifetime', icon: '✓👩🏽‍💻', actions: [{ id: 'a', label: 'Explicit feedback', style: 'danger' }] } }) - expect(screen.getByText('✓👩🏽‍💻')).toHaveAttribute('aria-hidden', 'true'); expect(mocks.resolve).not.toHaveBeenCalled() - // Upstream's card has only its own actions: no extra dismiss button. - if (ending === 'no dismiss button') { expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull(); expect(screen.getAllByRole('button')).toHaveLength(1); await poll(); expect(mocks.resolve).not.toHaveBeenCalled() } - else { await act(async () => { await vi.advanceTimersByTimeAsync(10) }); expectExpired(); expect(mocks.resolve).not.toHaveBeenCalled() } - }) - it.each(['resolve', 'reject'] as const)('does not duplicate an icon choice or let late %s affect a replacement scope', async ending => { - const item: AgentThreadInteraction = { id: 'icon-old', expiresAt: Date.now() + 60000, prompt: { kind: 'show_card', title: 'Old icon title', icon: '✓', actions: [{ id: 'approve', label: 'Old explicit feedback', style: 'primary' }] } }, view = await mount(item) - let release!: () => void, reject!: (error: Error) => void - mocks.resolve.mockImplementationOnce(() => new Promise((resolve, fail) => { release = resolve; reject = fail })) - fireEvent.click(screen.getByRole('button', { name: 'Old explicit feedback' })); fireEvent.click(screen.getByRole('button', { name: 'Old explicit feedback' })); expect(mocks.resolve).toHaveBeenCalledOnce() - mocks.list.mockResolvedValue({ interactions: [{ ...item, id: 'icon-new', prompt: { ...item.prompt, title: 'New icon title', icon: '👩🏽‍💻', actions: [{ id: 'no', label: 'New explicit feedback' }] } }] }) - view.rerender(); await act(async () => { await Promise.resolve() }) - await act(async () => { if (ending === 'resolve') release(); else reject(new Error('old request failed')); await Promise.resolve() }) - expect(screen.getByText('👩🏽‍💻')).toHaveAttribute('aria-hidden', 'true'); expect(screen.getByText('New icon title')).toBeInTheDocument(); expect(screen.queryByText('Old icon title')).not.toBeInTheDocument() - expect(screen.getByRole('button', { name: 'New explicit feedback' })).not.toBeDisabled(); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); expect(mocks.resolve).toHaveBeenCalledOnce() - }) - it.each(['✓', '👩🏽‍💻', ''])('renders a decorative escaped text icon before the original live title, never status, resource or approval %#', async icon => { - const prompt = { kind: 'show_card' as const, title: 'Original feedback title', icon, actions: [{ id: 'approve', label: 'Explicit feedback' }] } - await mount({ id: 'icon-choice', expiresAt: Date.now() + 60000, prompt }) - const mark = screen.getByText(icon), title = screen.getByText(prompt.title) - expect(mark.tagName).toBe('SPAN'); expect(mark).toHaveAttribute('aria-hidden', 'true'); expect(title.contains(mark)).toBe(true) - expect(title.textContent).toBe(icon + prompt.title) - expect(screen.getAllByRole('button')).toHaveLength(1); expect(mocks.resolve).not.toHaveBeenCalled(); expect(document.querySelector('img,a,script,input,textarea')).toBeNull() - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Explicit feedback' })) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'icon-choice', answer: { status: 'answered', actionId: 'approve' } }) - expect(prompt.icon).toBe(icon) - }) - it.each((['light', 'dark'] as const).flatMap(mode => ['primary', 'secondary', 'danger'].map(style => [mode, style] as const)))('uses only fixed custom-theme button variants/colors independent of card accent mode=%s style=%s', async (mode, style) => { - const theme = createTheme({ palette: { mode, primary: { main: '#13579b' }, error: { main: '#579bdf' }, success: { main: '#3579bd' } } }) - const prompt = { kind: 'show_card' as const, title: 'Button styling only', accent: 'success' as const, footer: 'Bearer STYLE_UI_SECRET', actions: [{ id: 'approve', label: 'Styled feedback', style }] } - mocks.list.mockResolvedValue({ interactions: [{ id: 'theme-style', expiresAt: Date.now() + 60000, prompt }] }) - render() - await act(async () => { await Promise.resolve() }) - const button = screen.getByRole('button', { name: 'Styled feedback' }), color = style === 'danger' ? '#579bdf' : '#13579b' - expectButtonStyle(button, style !== 'secondary', style === 'danger') - // A filled button takes the theme's colour; an outlined one stays in the text colour. - if (style === 'secondary') expect(button).not.toHaveStyle({ backgroundColor: color }) - else expect(button).toHaveStyle({ backgroundColor: color }) - expect(card()).toHaveStyle({ borderColor: alpha('#3579bd', 0.4) }) - expect(screen.getAllByRole('button')).toHaveLength(1); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); expect(screen.queryByRole('status')).not.toBeInTheDocument() - expect(document.body.textContent).not.toContain('STYLE_UI_SECRET'); expect(prompt.footer).toContain('STYLE_UI_SECRET') + expect(toJSON).not.toHaveBeenCalled() + expect(toString).not.toHaveBeenCalled() expect(mocks.resolve).not.toHaveBeenCalled() - await act(async () => { fireEvent.click(button) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'theme-style', answer: { status: 'answered', actionId: 'approve' } }) - }) - it.each([undefined, null, false, 1, {}, [], Object('primary'), { toJSON: () => 'primary' }, { toString: () => 'primary' }, 'link', 'error', 'Primary', 'primary ', '#f00', 'url(https://external.invalid)', 'constructor', '__proto__'])('never forwards forged button style or turns it into URL/answer authority %#', async style => { - const prompt = { kind: 'show_card' as const, title: 'Forged style fallback', actions: [{ id: 'a', label: 'Original feedback', style }] } - mocks.list.mockResolvedValue({ interactions: [{ id: 'forged-style', expiresAt: Date.now() + 60000, prompt }] }) - render() - await act(async () => { await Promise.resolve() }) - const button = screen.getByRole('button', { name: 'Original feedback' }) - expectButtonStyle(button, false, false); expect(button).not.toHaveAttribute('href'); expect(button).not.toHaveAttribute('style') - expect(document.querySelector('a,img,input,textarea,script')).toBeNull(); expect(mocks.resolve).not.toHaveBeenCalled() - await act(async () => { fireEvent.click(button) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'forged-style', answer: { status: 'answered', actionId: 'a' } }) - expect(prompt.actions[0].style).toBe(style) }) + it.each(['primary', 'secondary', 'danger'] as const)( + 'redacts icon decoration only, preserving original title, fixed button styles and actual status independence style=%s', + async (style) => { + const icon = '\u001b[31mBearer ICON_UI_SECRET\u001b[0m\u202e', + prompt = { + kind: 'show_card' as const, + title: 'Accessible unchanged title', + icon, + subtitle: '', + footer: 'Closing context', + fields: [{ label: 'State', value: 'Not approval' }], + accent: 'success' as const, + actions: [{ id: 'approve', label: 'Explicit feedback', style }] + } + await mount({ id: 'icon-styles', expiresAt: Date.now() + 60000, prompt }) + const mark = screen.getByText('Bearer [redacted]'), + title = screen.getByText(prompt.title), + button = screen.getByRole('button', { name: 'Explicit feedback' }) + expect(title).toHaveAccessibleName('') + expect(title.textContent).toBe('Bearer [redacted]' + prompt.title) + expect(mark).toHaveAttribute('aria-hidden', 'true') + expect(title.firstChild).toBe(mark) + expectButtonStyle(button, style !== 'secondary', style === 'danger') + expect(card()).not.toHaveAttribute('icon') + expect(screen.queryByRole('alert')).not.toBeInTheDocument() + expect(screen.queryByRole('status')).not.toBeInTheDocument() + expect(document.body.textContent).not.toContain('ICON_UI_SECRET') + expect(document.body.textContent).not.toContain('\u202e') + expect(prompt.icon).toBe(icon) + expect(mocks.resolve).not.toHaveBeenCalled() + await act(async () => { + fireEvent.click(button) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'icon-styles', + answer: { status: 'answered', actionId: 'approve' } + }) + } + ) + it.each(['no dismiss button', 'expiry'] as const)( + 'keeps decorative icons passive during %s', + async (ending) => { + await mount({ + id: 'icon-end', + expiresAt: Date.now() + 10, + prompt: { + kind: 'show_card', + title: 'Decorative icon lifetime', + icon: '✓👩🏽‍💻', + actions: [{ id: 'a', label: 'Explicit feedback', style: 'danger' }] + } + }) + expect(screen.getByText('✓👩🏽‍💻')).toHaveAttribute('aria-hidden', 'true') + expect(mocks.resolve).not.toHaveBeenCalled() + // Upstream's card has only its own actions: no extra dismiss button. + if (ending === 'no dismiss button') { + expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull() + expect(screen.getAllByRole('button')).toHaveLength(1) + await poll() + expect(mocks.resolve).not.toHaveBeenCalled() + } else { + await act(async () => { + await vi.advanceTimersByTimeAsync(10) + }) + expectExpired() + expect(mocks.resolve).not.toHaveBeenCalled() + } + } + ) + it.each(['resolve', 'reject'] as const)( + 'does not duplicate an icon choice or let late %s affect a replacement scope', + async (ending) => { + const item: AgentThreadInteraction = { + id: 'icon-old', + expiresAt: Date.now() + 60000, + prompt: { + kind: 'show_card', + title: 'Old icon title', + icon: '✓', + actions: [{ id: 'approve', label: 'Old explicit feedback', style: 'primary' }] + } + }, + view = await mount(item) + let release!: () => void, reject!: (error: Error) => void + mocks.resolve.mockImplementationOnce( + () => + new Promise((resolve, fail) => { + release = resolve + reject = fail + }) + ) + fireEvent.click(screen.getByRole('button', { name: 'Old explicit feedback' })) + fireEvent.click(screen.getByRole('button', { name: 'Old explicit feedback' })) + expect(mocks.resolve).toHaveBeenCalledOnce() + mocks.list.mockResolvedValue({ + interactions: [ + { + ...item, + id: 'icon-new', + prompt: { + ...item.prompt, + title: 'New icon title', + icon: '👩🏽‍💻', + actions: [{ id: 'no', label: 'New explicit feedback' }] + } + } + ] + }) + view.rerender() + await act(async () => { + await Promise.resolve() + }) + await act(async () => { + if (ending === 'resolve') release() + else reject(new Error('old request failed')) + await Promise.resolve() + }) + expect(screen.getByText('👩🏽‍💻')).toHaveAttribute('aria-hidden', 'true') + expect(screen.getByText('New icon title')).toBeInTheDocument() + expect(screen.queryByText('Old icon title')).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: 'New explicit feedback' })).not.toBeDisabled() + expect(screen.queryByRole('alert')).not.toBeInTheDocument() + expect(mocks.resolve).toHaveBeenCalledOnce() + } + ) + it.each(['✓', '👩🏽‍💻', ''])( + 'renders a decorative escaped text icon before the original live title, never status, resource or approval %#', + async (icon) => { + const prompt = { + kind: 'show_card' as const, + title: 'Original feedback title', + icon, + actions: [{ id: 'approve', label: 'Explicit feedback' }] + } + await mount({ id: 'icon-choice', expiresAt: Date.now() + 60000, prompt }) + const mark = screen.getByText(icon), + title = screen.getByText(prompt.title) + expect(mark.tagName).toBe('SPAN') + expect(mark).toHaveAttribute('aria-hidden', 'true') + expect(title.contains(mark)).toBe(true) + expect(title.textContent).toBe(icon + prompt.title) + expect(screen.getAllByRole('button')).toHaveLength(1) + expect(mocks.resolve).not.toHaveBeenCalled() + expect(document.querySelector('img,a,script,input,textarea')).toBeNull() + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Explicit feedback' })) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'icon-choice', + answer: { status: 'answered', actionId: 'approve' } + }) + expect(prompt.icon).toBe(icon) + } + ) + it.each( + (['light', 'dark'] as const).flatMap((mode) => + ['primary', 'secondary', 'danger'].map((style) => [mode, style] as const) + ) + )( + 'uses only fixed custom-theme button variants/colors independent of card accent mode=%s style=%s', + async (mode, style) => { + const theme = createTheme({ + palette: { + mode, + primary: { main: '#13579b' }, + error: { main: '#579bdf' }, + success: { main: '#3579bd' } + } + }) + const prompt = { + kind: 'show_card' as const, + title: 'Button styling only', + accent: 'success' as const, + footer: 'Bearer STYLE_UI_SECRET', + actions: [{ id: 'approve', label: 'Styled feedback', style }] + } + mocks.list.mockResolvedValue({ + interactions: [{ id: 'theme-style', expiresAt: Date.now() + 60000, prompt }] + }) + render( + + + + ) + await act(async () => { + await Promise.resolve() + }) + const button = screen.getByRole('button', { name: 'Styled feedback' }), + color = style === 'danger' ? '#579bdf' : '#13579b' + expectButtonStyle(button, style !== 'secondary', style === 'danger') + // A filled button takes the theme's colour; an outlined one stays in the text colour. + if (style === 'secondary') expect(button).not.toHaveStyle({ backgroundColor: color }) + else expect(button).toHaveStyle({ backgroundColor: color }) + expect(card()).toHaveStyle({ borderColor: alpha('#3579bd', 0.4) }) + expect(screen.getAllByRole('button')).toHaveLength(1) + expect(screen.queryByRole('alert')).not.toBeInTheDocument() + expect(screen.queryByRole('status')).not.toBeInTheDocument() + expect(document.body.textContent).not.toContain('STYLE_UI_SECRET') + expect(prompt.footer).toContain('STYLE_UI_SECRET') + expect(mocks.resolve).not.toHaveBeenCalled() + await act(async () => { + fireEvent.click(button) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'theme-style', + answer: { status: 'answered', actionId: 'approve' } + }) + } + ) + it.each([ + undefined, + null, + false, + 1, + {}, + [], + Object('primary'), + { toJSON: () => 'primary' }, + { toString: () => 'primary' }, + 'link', + 'error', + 'Primary', + 'primary ', + '#f00', + 'url(https://external.invalid)', + 'constructor', + '__proto__' + ])( + 'never forwards forged button style or turns it into URL/answer authority %#', + async (style) => { + const prompt = { + kind: 'show_card' as const, + title: 'Forged style fallback', + actions: [{ id: 'a', label: 'Original feedback', style }] + } + mocks.list.mockResolvedValue({ + interactions: [{ id: 'forged-style', expiresAt: Date.now() + 60000, prompt }] + }) + render() + await act(async () => { + await Promise.resolve() + }) + const button = screen.getByRole('button', { name: 'Original feedback' }) + expectButtonStyle(button, false, false) + expect(button).not.toHaveAttribute('href') + expect(button).not.toHaveAttribute('style') + expect(document.querySelector('a,img,input,textarea,script')).toBeNull() + expect(mocks.resolve).not.toHaveBeenCalled() + await act(async () => { + fireEvent.click(button) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'forged-style', + answer: { status: 'answered', actionId: 'a' } + }) + expect(prompt.actions[0].style).toBe(style) + } + ) it('ignores inherited button style and keeps mixed omitted choices independent, with no dismiss button', async () => { - const actions = [{ id: 'a', label: 'Primary feedback', style: 'primary' as const }, { id: 'b', label: 'Original feedback' }, Object.assign(Object.create({ style: 'danger' }), { id: 'c', label: 'Inherited ignored' })] - await mount({ id: 'mixed-styles', expiresAt: Date.now() + 60000, prompt: { kind: 'show_card', title: 'Mixed style data', actions } }) + const actions = [ + { id: 'a', label: 'Primary feedback', style: 'primary' as const }, + { id: 'b', label: 'Original feedback' }, + Object.assign(Object.create({ style: 'danger' }), { id: 'c', label: 'Inherited ignored' }) + ] + await mount({ + id: 'mixed-styles', + expiresAt: Date.now() + 60000, + prompt: { kind: 'show_card', title: 'Mixed style data', actions } + }) expectButtonStyle(screen.getByRole('button', { name: 'Primary feedback' }), true, false) - for (const name of ['Original feedback', 'Inherited ignored']) expectButtonStyle(screen.getByRole('button', { name }), false, false) - expect(mocks.resolve).not.toHaveBeenCalled(); expect(Object.hasOwn(actions[1], 'style')).toBe(false) - expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull(); expect(screen.getAllByRole('button')).toHaveLength(3) - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Inherited ignored' })) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'mixed-styles', answer: { status: 'answered', actionId: 'c' } }) - }) - it.each(['primary', 'secondary', 'danger'] as const)('renders fixed action style without changing explicit feedback, with no dismiss button style=%s', async style => { - const prompt = { kind: 'show_card' as const, title: 'Button style is not approval', actions: [{ id: 'approve', label: 'Send feedback', style }] } - await mount({ id: 'styled-choice', expiresAt: Date.now() + 60000, prompt }) - const button = screen.getByRole('button', { name: 'Send feedback' }) - expectButtonStyle(button, style !== 'secondary', style === 'danger') - expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull(); expect(screen.getAllByRole('button')).toHaveLength(1) - expect(mocks.resolve).not.toHaveBeenCalled(); expect(document.querySelector('a,img,input,textarea,script')).toBeNull() - await act(async () => { fireEvent.click(button) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'styled-choice', answer: { status: 'answered', actionId: 'approve' } }) - expect(prompt.actions[0].style).toBe(style) - }) - it.each(['error', 'red', 'url(https://external.invalid)', 'constructor', { color: 'red' }])('never forwards a forged live accent to CSS, attributes or response data %#', async accent => { - const theme = createTheme({ palette: { divider: 'rgb(13, 35, 57)' } }) - const prompt = { kind: 'show_card' as const, title: 'Untrusted hint', accent, actions: [{ id: 'ack', label: 'Dismiss by choice' }] } - mocks.list.mockResolvedValue({ interactions: [{ id: 'forged-accent', expiresAt: Date.now() + 60000, prompt }] }) - render() - await act(async () => { await Promise.resolve() }) - const region = card() - expect(region).toHaveStyle({ borderColor: 'rgb(13, 35, 57)' }); expect(region).not.toHaveAttribute('accent') - expect(document.querySelector('a,img,input,textarea,script')).toBeNull(); expect(mocks.resolve).not.toHaveBeenCalled() - expect(screen.queryByRole('alert')).not.toBeInTheDocument(); expect(screen.getAllByRole('button')).toHaveLength(1) - expect(prompt.accent).toBe(accent) - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Dismiss by choice' })) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'forged-accent', answer: { status: 'answered', actionId: 'ack' } }) - }) - it.each(['bare', 'fields', 'subtitle', 'footer', 'all'])('maps a valid accent only to display styling with all optional contexts %#', async variant => { - const prompt = { kind: 'show_card' as const, title: 'Fixed palette choice', accent: 'danger' as const, ...(['fields', 'all'].includes(variant) ? { fields: [{ label: 'Status', value: 'Not tool status' }] } : {}), ...(['subtitle', 'all'].includes(variant) ? { subtitle: 'Context only' } : {}), ...(['footer', 'all'].includes(variant) ? { footer: 'Bearer ACCENT_CONTEXT_SECRET' } : {}), actions: [{ id: 'approve', label: 'Feedback only' }, { id: 'no', label: 'No feedback' }] } - await mount({ id: 'context-accent', expiresAt: Date.now() + 60000, prompt }) - expect(screen.getByText(prompt.title)).toBeInTheDocument(); expect(screen.getAllByRole('button')).toHaveLength(2) - expect(document.querySelector('b,a,img,input,textarea,script')).toBeNull(); expect(document.body.textContent).not.toContain('ACCENT_CONTEXT_SECRET') + for (const name of ['Original feedback', 'Inherited ignored']) + expectButtonStyle(screen.getByRole('button', { name }), false, false) expect(mocks.resolve).not.toHaveBeenCalled() - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'No feedback' })) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'context-accent', answer: { status: 'answered', actionId: 'no' } }) - }) - it.each((['light', 'dark'] as const).flatMap(mode => ['primary', 'info', 'success', 'warning', 'danger', 'neutral'].map(accent => [mode, accent] as const)))('uses fixed custom-theme card border/title accent without changing buttons, status or explicit reply mode=%s accent=%s', async (mode, accent) => { - const theme = createTheme({ palette: { mode, primary: { main: '#13579b' }, info: { main: '#2468ac' }, success: { main: '#3579bd' }, warning: { main: '#468ace' }, error: { main: '#579bdf' }, divider: 'rgb(12, 34, 56)', text: { primary: 'rgb(23, 45, 67)' } } }) - const tokens = { primary: '#13579b', info: '#2468ac', success: '#3579bd', warning: '#468ace', danger: '#579bdf', neutral: 'rgb(12, 34, 56)' } - const prompt = { kind: 'show_card' as const, title: 'Visual accent is not a result', accent, subtitle: 'Bearer ACCENT_UI_SECRET', footer: 'Feedback only', actions: [{ id: 'approve', label: 'Explicit feedback' }] } - mocks.list.mockResolvedValue({ interactions: [{ id: 'accent-choice', expiresAt: Date.now() + 60000, prompt }] }) - render() - await act(async () => { await Promise.resolve() }) - const region = card(), title = screen.getByText(prompt.title) - // The accent tints the card's border (40%); the card's title keeps the text colour. - expect(region).toHaveStyle({ borderColor: accent === 'neutral' ? tokens.neutral : alpha(tokens[accent as keyof typeof tokens], 0.4) }) - expect(title.closest('header')).toHaveStyle({ color: 'rgb(23, 45, 67)' }) - expect(screen.queryByRole('alert')).not.toBeInTheDocument(); expect(screen.queryByRole('status')).not.toBeInTheDocument() - expect(screen.getAllByRole('button')).toHaveLength(1); expect(document.querySelector('a,img,input,textarea,script')).toBeNull() - expect(document.body.textContent).not.toContain('ACCENT_UI_SECRET'); expect(prompt.subtitle).toContain('ACCENT_UI_SECRET') - expect(mocks.resolve).not.toHaveBeenCalled() - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Explicit feedback' })) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'accent-choice', answer: { status: 'answered', actionId: 'approve' } }) - }) - it.each([1, 4].flatMap(count => ['bare', 'fields', 'subtitle', 'both'].map(variant => [count, variant] as const)))('renders a plain redacted footer after context but before explicit buttons actions=%s context=%s', async (count, variant) => { - const footer = ' Bearer FOOTER_LIVE_SECRET' - const prompt = { kind: 'show_card' as const, title: 'Footer choice', body: 'Body context', ...(['fields', 'both'].includes(variant) ? { fields: [{ label: 'Status', value: 'Read only' }] } : {}), ...(['subtitle', 'both'].includes(variant) ? { subtitle: 'Smaller context' } : {}), footer, actions: Array.from({ length: count }, (_, i) => ({ id: `a${i}`, label: `Feedback ${i}` })) } - await mount({ id: 'footer-card', expiresAt: Date.now() + 60000, prompt }) - const footerText = screen.getByText(' Bearer [redacted]') - expect(screen.getByText(prompt.fields ? 'Status: Read only' : 'Body context').compareDocumentPosition(footerText) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(footerText.compareDocumentPosition(screen.getByRole('button', { name: 'Feedback 0' })) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(document.body.textContent).not.toContain('FOOTER_LIVE_SECRET') - expect(document.querySelector('img,a,script,input,textarea')).toBeNull() - expect(mocks.resolve).not.toHaveBeenCalled(); expect(prompt.footer).toBe(footer) - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Feedback 0' })) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'footer-card', answer: { status: 'answered', actionId: 'a0' } }) - expect(screen.queryAllByRole('button')).toHaveLength(0) - }) - it.each(['Authorization: Basic FOOTER_BASIC_SECRET', 'api_key=FOOTER_KEY_SECRET', 'https://user:FOOTER_URL_SECRET@example.invalid', '\u001b[31mBearer FOOTER_CONTROL_SECRET\u001b[0m\u202e'])('renders recognized footer patterns redacted without rewriting original data or autoconfirming %#', async footer => { - const prompt = { kind: 'show_card' as const, title: 'Footer patterns', footer, actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] } - await mount({ id: 'footer-pattern', expiresAt: Date.now() + 60000, prompt }) - expect(document.body.textContent).toContain('[redacted]') - expect(document.body.textContent).not.toMatch(/FOOTER_(?:BASIC|KEY|URL|CONTROL)_SECRET/) - expect(document.querySelector('img,a,script,input,textarea')).toBeNull() - expect(mocks.resolve).not.toHaveBeenCalled(); expect(prompt.footer).toBe(footer) + expect(Object.hasOwn(actions[1], 'style')).toBe(false) expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull() - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'B' })) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'footer-pattern', answer: { status: 'answered', actionId: 'b' } }) + expect(screen.getAllByRole('button')).toHaveLength(3) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Inherited ignored' })) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'mixed-styles', + answer: { status: 'answered', actionId: 'c' } + }) }) - it.each((['no dismiss button', 'expiry'] as const).flatMap(kind => [false, true].map(withAccent => [kind, withAccent] as const)))('never treats footer single-action %s as consent or an affirmative answer accent=%s', async (kind, withAccent) => { - await mount({ id: 'footer-terminal', expiresAt: Date.now() + 10, prompt: { kind: 'show_card', title: 'Footer terminal', ...(withAccent ? { accent: 'success' as const } : {}), footer: 'Not approval', actions: [{ id: 'approve', label: 'Explicit feedback' }] } }) - expect(mocks.resolve).not.toHaveBeenCalled() - if (kind === 'no dismiss button') { - expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull(); expect(screen.getAllByRole('button')).toHaveLength(1) - await poll(); expect(mocks.resolve).not.toHaveBeenCalled() - } else { - await act(async () => { await vi.advanceTimersByTimeAsync(10) }) - expectExpired(); expect(mocks.resolve).not.toHaveBeenCalled() + it.each(['primary', 'secondary', 'danger'] as const)( + 'renders fixed action style without changing explicit feedback, with no dismiss button style=%s', + async (style) => { + const prompt = { + kind: 'show_card' as const, + title: 'Button style is not approval', + actions: [{ id: 'approve', label: 'Send feedback', style }] + } + await mount({ id: 'styled-choice', expiresAt: Date.now() + 60000, prompt }) + const button = screen.getByRole('button', { name: 'Send feedback' }) + expectButtonStyle(button, style !== 'secondary', style === 'danger') + expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull() + expect(screen.getAllByRole('button')).toHaveLength(1) + expect(mocks.resolve).not.toHaveBeenCalled() + expect(document.querySelector('a,img,input,textarea,script')).toBeNull() + await act(async () => { + fireEvent.click(button) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'styled-choice', + answer: { status: 'answered', actionId: 'approve' } + }) + expect(prompt.actions[0].style).toBe(style) } - }) - it.each([false, true])('does not let a late footer choice resolution consume a replacement conversation accent=%s', async withAccent => { - const item: AgentThreadInteraction = { id: 'footer-old', expiresAt: Date.now() + 60000, prompt: { kind: 'show_card', title: 'Old footer', ...(withAccent ? { accent: 'danger' as const } : {}), footer: 'Old closing context', actions: [{ id: 'a', label: 'Old feedback' }] } } - const view = await mount(item) - let release!: () => void - mocks.resolve.mockImplementationOnce(() => new Promise(resolve => { release = resolve })) - const button = screen.getByRole('button', { name: 'Old feedback' }); fireEvent.click(button); fireEvent.click(button) - expect(mocks.resolve).toHaveBeenCalledTimes(1); expect(button).toBeDisabled() - mocks.list.mockResolvedValue({ interactions: [{ ...item, id: 'footer-new', prompt: { kind: 'show_card', title: 'New footer', ...(withAccent ? { accent: 'info' as const } : {}), footer: 'New closing context', actions: [{ id: 'a', label: 'New feedback' }] } }] }) - view.rerender() - await act(async () => { await Promise.resolve() }) - await act(async () => { release(); await Promise.resolve() }) - expect(screen.getByText('New closing context')).toBeInTheDocument() - expect(screen.getByRole('button', { name: 'New feedback' })).not.toBeDisabled() - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'footer-old', answer: { status: 'answered', actionId: 'a' } }) - }) - it.each(['bare', 'fields', 'subtitle', 'both'] as const)('requires an explicit click on the lone action, with no dismiss button, context=%s', async variant => { - const prompt = { kind: 'show_card' as const, title: 'Single explicit button', actions: [{ id: 'approve', label: 'Feedback only, not approval' }], - ...(['fields', 'both'].includes(variant) ? { fields: [{ label: 'Status', value: '' }] } : {}), - ...(['subtitle', 'both'].includes(variant) ? { subtitle: 'Bearer SINGLE_UI_SECRET' } : {}) } - await mount({ id: 'single-button', expiresAt: Date.now() + 60000, prompt }) - expect(screen.getAllByRole('button')).toHaveLength(1) - expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull() - expect(document.querySelector('img,a,input,textarea,script')).toBeNull() - expect(document.body.textContent).not.toContain('SINGLE_UI_SECRET') - await poll() - expect(mocks.resolve).not.toHaveBeenCalled() - let release!: () => void - mocks.resolve.mockImplementationOnce(() => new Promise(resolve => { release = resolve })) - const button = screen.getByRole('button', { name: 'Feedback only, not approval' }) - fireEvent.click(button); fireEvent.click(button) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'single-button', answer: { status: 'answered', actionId: 'approve' } }) - expect(button).toBeDisabled() - await act(async () => { release(); await Promise.resolve() }) - expect(screen.queryAllByRole('button')).toHaveLength(0) - await poll(); expect(screen.queryAllByRole('button')).toHaveLength(0) - }) - it.each(['no dismiss button', 'expiry'] as const)('never treats lone-action %s as an affirmative response', async kind => { - await mount({ id: 'single-terminal', expiresAt: Date.now() + 10, prompt: { kind: 'show_card', title: 'One is not automatic', actions: [{ id: 'approve', label: 'Explicit feedback' }] } }) - expect(mocks.resolve).not.toHaveBeenCalled() - if (kind === 'no dismiss button') { - expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull(); expect(screen.getAllByRole('button')).toHaveLength(1) - await poll(); expect(mocks.resolve).not.toHaveBeenCalled() - } else { - await act(async () => { await vi.advanceTimersByTimeAsync(10) }) - expectExpired() + ) + it.each(['error', 'red', 'url(https://external.invalid)', 'constructor', { color: 'red' }])( + 'never forwards a forged live accent to CSS, attributes or response data %#', + async (accent) => { + const theme = createTheme({ palette: { divider: 'rgb(13, 35, 57)' } }) + const prompt = { + kind: 'show_card' as const, + title: 'Untrusted hint', + accent, + actions: [{ id: 'ack', label: 'Dismiss by choice' }] + } + mocks.list.mockResolvedValue({ + interactions: [{ id: 'forged-accent', expiresAt: Date.now() + 60000, prompt }] + }) + render( + + + + ) + await act(async () => { + await Promise.resolve() + }) + const region = card() + expect(region).toHaveStyle({ borderColor: 'rgb(13, 35, 57)' }) + expect(region).not.toHaveAttribute('accent') + expect(document.querySelector('a,img,input,textarea,script')).toBeNull() expect(mocks.resolve).not.toHaveBeenCalled() + expect(screen.queryByRole('alert')).not.toBeInTheDocument() + expect(screen.getAllByRole('button')).toHaveLength(1) + expect(prompt.accent).toBe(accent) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Dismiss by choice' })) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'forged-accent', + answer: { status: 'answered', actionId: 'ack' } + }) } - }) + ) + it.each(['bare', 'fields', 'subtitle', 'footer', 'all'])( + 'maps a valid accent only to display styling with all optional contexts %#', + async (variant) => { + const prompt = { + kind: 'show_card' as const, + title: 'Fixed palette choice', + accent: 'danger' as const, + ...(['fields', 'all'].includes(variant) + ? { fields: [{ label: 'Status', value: 'Not tool status' }] } + : {}), + ...(['subtitle', 'all'].includes(variant) ? { subtitle: 'Context only' } : {}), + ...(['footer', 'all'].includes(variant) ? { footer: 'Bearer ACCENT_CONTEXT_SECRET' } : {}), + actions: [ + { id: 'approve', label: 'Feedback only' }, + { id: 'no', label: 'No feedback' } + ] + } + await mount({ id: 'context-accent', expiresAt: Date.now() + 60000, prompt }) + expect(screen.getByText(prompt.title)).toBeInTheDocument() + expect(screen.getAllByRole('button')).toHaveLength(2) + expect(document.querySelector('b,a,img,input,textarea,script')).toBeNull() + expect(document.body.textContent).not.toContain('ACCENT_CONTEXT_SECRET') + expect(mocks.resolve).not.toHaveBeenCalled() + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'No feedback' })) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'context-accent', + answer: { status: 'answered', actionId: 'no' } + }) + } + ) + it.each( + (['light', 'dark'] as const).flatMap((mode) => + ['primary', 'info', 'success', 'warning', 'danger', 'neutral'].map( + (accent) => [mode, accent] as const + ) + ) + )( + 'uses fixed custom-theme card border/title accent without changing buttons, status or explicit reply mode=%s accent=%s', + async (mode, accent) => { + const theme = createTheme({ + palette: { + mode, + primary: { main: '#13579b' }, + info: { main: '#2468ac' }, + success: { main: '#3579bd' }, + warning: { main: '#468ace' }, + error: { main: '#579bdf' }, + divider: 'rgb(12, 34, 56)', + text: { primary: 'rgb(23, 45, 67)' } + } + }) + const tokens = { + primary: '#13579b', + info: '#2468ac', + success: '#3579bd', + warning: '#468ace', + danger: '#579bdf', + neutral: 'rgb(12, 34, 56)' + } + const prompt = { + kind: 'show_card' as const, + title: 'Visual accent is not a result', + accent, + subtitle: 'Bearer ACCENT_UI_SECRET', + footer: 'Feedback only', + actions: [{ id: 'approve', label: 'Explicit feedback' }] + } + mocks.list.mockResolvedValue({ + interactions: [{ id: 'accent-choice', expiresAt: Date.now() + 60000, prompt }] + }) + render( + + + + ) + await act(async () => { + await Promise.resolve() + }) + const region = card(), + title = screen.getByText(prompt.title) + // The accent tints the card's border (40%); the card's title keeps the text colour. + expect(region).toHaveStyle({ + borderColor: + accent === 'neutral' ? tokens.neutral : alpha(tokens[accent as keyof typeof tokens], 0.4) + }) + expect(title.closest('header')).toHaveStyle({ color: 'rgb(23, 45, 67)' }) + expect(screen.queryByRole('alert')).not.toBeInTheDocument() + expect(screen.queryByRole('status')).not.toBeInTheDocument() + expect(screen.getAllByRole('button')).toHaveLength(1) + expect(document.querySelector('a,img,input,textarea,script')).toBeNull() + expect(document.body.textContent).not.toContain('ACCENT_UI_SECRET') + expect(prompt.subtitle).toContain('ACCENT_UI_SECRET') + expect(mocks.resolve).not.toHaveBeenCalled() + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Explicit feedback' })) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'accent-choice', + answer: { status: 'answered', actionId: 'approve' } + }) + } + ) + it.each( + [1, 4].flatMap((count) => + ['bare', 'fields', 'subtitle', 'both'].map((variant) => [count, variant] as const) + ) + )( + 'renders a plain redacted footer after context but before explicit buttons actions=%s context=%s', + async (count, variant) => { + const footer = ' Bearer FOOTER_LIVE_SECRET' + const prompt = { + kind: 'show_card' as const, + title: 'Footer choice', + body: 'Body context', + ...(['fields', 'both'].includes(variant) + ? { fields: [{ label: 'Status', value: 'Read only' }] } + : {}), + ...(['subtitle', 'both'].includes(variant) ? { subtitle: 'Smaller context' } : {}), + footer, + actions: Array.from({ length: count }, (_, i) => ({ id: `a${i}`, label: `Feedback ${i}` })) + } + await mount({ id: 'footer-card', expiresAt: Date.now() + 60000, prompt }) + const footerText = screen.getByText( + ' Bearer [redacted]' + ) + expect( + screen + .getByText(prompt.fields ? 'Status: Read only' : 'Body context') + .compareDocumentPosition(footerText) & Node.DOCUMENT_POSITION_FOLLOWING + ).toBeTruthy() + expect( + footerText.compareDocumentPosition(screen.getByRole('button', { name: 'Feedback 0' })) & + Node.DOCUMENT_POSITION_FOLLOWING + ).toBeTruthy() + expect(document.body.textContent).not.toContain('FOOTER_LIVE_SECRET') + expect(document.querySelector('img,a,script,input,textarea')).toBeNull() + expect(mocks.resolve).not.toHaveBeenCalled() + expect(prompt.footer).toBe(footer) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Feedback 0' })) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'footer-card', + answer: { status: 'answered', actionId: 'a0' } + }) + expect(screen.queryAllByRole('button')).toHaveLength(0) + } + ) + it.each([ + 'Authorization: Basic FOOTER_BASIC_SECRET', + 'api_key=FOOTER_KEY_SECRET', + 'https://user:FOOTER_URL_SECRET@example.invalid', + '\u001b[31mBearer FOOTER_CONTROL_SECRET\u001b[0m\u202e' + ])( + 'renders recognized footer patterns redacted without rewriting original data or autoconfirming %#', + async (footer) => { + const prompt = { + kind: 'show_card' as const, + title: 'Footer patterns', + footer, + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + } + await mount({ id: 'footer-pattern', expiresAt: Date.now() + 60000, prompt }) + expect(document.body.textContent).toContain('[redacted]') + expect(document.body.textContent).not.toMatch(/FOOTER_(?:BASIC|KEY|URL|CONTROL)_SECRET/) + expect(document.querySelector('img,a,script,input,textarea')).toBeNull() + expect(mocks.resolve).not.toHaveBeenCalled() + expect(prompt.footer).toBe(footer) + expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull() + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'B' })) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'footer-pattern', + answer: { status: 'answered', actionId: 'b' } + }) + } + ) + it.each( + (['no dismiss button', 'expiry'] as const).flatMap((kind) => + [false, true].map((withAccent) => [kind, withAccent] as const) + ) + )( + 'never treats footer single-action %s as consent or an affirmative answer accent=%s', + async (kind, withAccent) => { + await mount({ + id: 'footer-terminal', + expiresAt: Date.now() + 10, + prompt: { + kind: 'show_card', + title: 'Footer terminal', + ...(withAccent ? { accent: 'success' as const } : {}), + footer: 'Not approval', + actions: [{ id: 'approve', label: 'Explicit feedback' }] + } + }) + expect(mocks.resolve).not.toHaveBeenCalled() + if (kind === 'no dismiss button') { + expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull() + expect(screen.getAllByRole('button')).toHaveLength(1) + await poll() + expect(mocks.resolve).not.toHaveBeenCalled() + } else { + await act(async () => { + await vi.advanceTimersByTimeAsync(10) + }) + expectExpired() + expect(mocks.resolve).not.toHaveBeenCalled() + } + } + ) + it.each([false, true])( + 'does not let a late footer choice resolution consume a replacement conversation accent=%s', + async (withAccent) => { + const item: AgentThreadInteraction = { + id: 'footer-old', + expiresAt: Date.now() + 60000, + prompt: { + kind: 'show_card', + title: 'Old footer', + ...(withAccent ? { accent: 'danger' as const } : {}), + footer: 'Old closing context', + actions: [{ id: 'a', label: 'Old feedback' }] + } + } + const view = await mount(item) + let release!: () => void + mocks.resolve.mockImplementationOnce( + () => + new Promise((resolve) => { + release = resolve + }) + ) + const button = screen.getByRole('button', { name: 'Old feedback' }) + fireEvent.click(button) + fireEvent.click(button) + expect(mocks.resolve).toHaveBeenCalledTimes(1) + expect(button).toBeDisabled() + mocks.list.mockResolvedValue({ + interactions: [ + { + ...item, + id: 'footer-new', + prompt: { + kind: 'show_card', + title: 'New footer', + ...(withAccent ? { accent: 'info' as const } : {}), + footer: 'New closing context', + actions: [{ id: 'a', label: 'New feedback' }] + } + } + ] + }) + view.rerender() + await act(async () => { + await Promise.resolve() + }) + await act(async () => { + release() + await Promise.resolve() + }) + expect(screen.getByText('New closing context')).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'New feedback' })).not.toBeDisabled() + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'footer-old', + answer: { status: 'answered', actionId: 'a' } + }) + } + ) + it.each(['bare', 'fields', 'subtitle', 'both'] as const)( + 'requires an explicit click on the lone action, with no dismiss button, context=%s', + async (variant) => { + const prompt = { + kind: 'show_card' as const, + title: 'Single explicit button', + actions: [{ id: 'approve', label: 'Feedback only, not approval' }], + ...(['fields', 'both'].includes(variant) + ? { fields: [{ label: 'Status', value: '' }] } + : {}), + ...(['subtitle', 'both'].includes(variant) ? { subtitle: 'Bearer SINGLE_UI_SECRET' } : {}) + } + await mount({ id: 'single-button', expiresAt: Date.now() + 60000, prompt }) + expect(screen.getAllByRole('button')).toHaveLength(1) + expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull() + expect(document.querySelector('img,a,input,textarea,script')).toBeNull() + expect(document.body.textContent).not.toContain('SINGLE_UI_SECRET') + await poll() + expect(mocks.resolve).not.toHaveBeenCalled() + let release!: () => void + mocks.resolve.mockImplementationOnce( + () => + new Promise((resolve) => { + release = resolve + }) + ) + const button = screen.getByRole('button', { name: 'Feedback only, not approval' }) + fireEvent.click(button) + fireEvent.click(button) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'single-button', + answer: { status: 'answered', actionId: 'approve' } + }) + expect(button).toBeDisabled() + await act(async () => { + release() + await Promise.resolve() + }) + expect(screen.queryAllByRole('button')).toHaveLength(0) + await poll() + expect(screen.queryAllByRole('button')).toHaveLength(0) + } + ) + it.each(['no dismiss button', 'expiry'] as const)( + 'never treats lone-action %s as an affirmative response', + async (kind) => { + await mount({ + id: 'single-terminal', + expiresAt: Date.now() + 10, + prompt: { + kind: 'show_card', + title: 'One is not automatic', + actions: [{ id: 'approve', label: 'Explicit feedback' }] + } + }) + expect(mocks.resolve).not.toHaveBeenCalled() + if (kind === 'no dismiss button') { + expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull() + expect(screen.getAllByRole('button')).toHaveLength(1) + await poll() + expect(mocks.resolve).not.toHaveBeenCalled() + } else { + await act(async () => { + await vi.advanceTimersByTimeAsync(10) + }) + expectExpired() + expect(mocks.resolve).not.toHaveBeenCalled() + } + } + ) it('does not let a late single-action resolution consume a replacement conversation', async () => { - const item: AgentThreadInteraction = { id: 'single-old', expiresAt: Date.now() + 60000, prompt: { kind: 'show_card', title: 'Old single', actions: [{ id: 'approve', label: 'Old feedback' }] } } + const item: AgentThreadInteraction = { + id: 'single-old', + expiresAt: Date.now() + 60000, + prompt: { + kind: 'show_card', + title: 'Old single', + actions: [{ id: 'approve', label: 'Old feedback' }] + } + } const view = await mount(item) let release!: () => void - mocks.resolve.mockImplementationOnce(() => new Promise(resolve => { release = resolve })) + mocks.resolve.mockImplementationOnce( + () => + new Promise((resolve) => { + release = resolve + }) + ) fireEvent.click(screen.getByRole('button', { name: 'Old feedback' })) - mocks.list.mockResolvedValue({ interactions: [{ ...item, id: 'single-new', prompt: { kind: 'show_card', title: 'New single', actions: [{ id: 'approve', label: 'New feedback' }] } }] }) + mocks.list.mockResolvedValue({ + interactions: [ + { + ...item, + id: 'single-new', + prompt: { + kind: 'show_card', + title: 'New single', + actions: [{ id: 'approve', label: 'New feedback' }] + } + } + ] + }) view.rerender() - await act(async () => { await Promise.resolve() }) - await act(async () => { release(); await Promise.resolve() }) + await act(async () => { + await Promise.resolve() + }) + await act(async () => { + release() + await Promise.resolve() + }) expect(screen.getByRole('button', { name: 'New feedback' })).not.toBeDisabled() - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'single-old', answer: { status: 'answered', actionId: 'approve' } }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'single-old', + answer: { status: 'answered', actionId: 'approve' } + }) }) it('renders the smaller choice subtitle as inert redacted context and returns no subtitle or authority in the answer', async () => { const subtitle = ' Bearer SUBTITLE_LIVE_SECRET' - await mount({ id: 'subtitle-card', expiresAt: Date.now() + 60000, prompt: { kind: 'show_card', title: 'Subtitle choice', ...{ subtitle }, actions: [{ id: 'approve', label: 'Feedback only' }, { id: 'no', label: 'Other feedback' }] } }) - expect(screen.getByText(' Bearer [redacted]')).toBeInTheDocument() + await mount({ + id: 'subtitle-card', + expiresAt: Date.now() + 60000, + prompt: { + kind: 'show_card', + title: 'Subtitle choice', + ...{ subtitle }, + actions: [ + { id: 'approve', label: 'Feedback only' }, + { id: 'no', label: 'Other feedback' } + ] + } + }) + expect( + screen.getByText(' Bearer [redacted]') + ).toBeInTheDocument() expect(document.body.textContent).not.toContain('SUBTITLE_LIVE_SECRET') expect(document.querySelector('img,a,script,input,textarea')).toBeNull() - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Feedback only' })) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'subtitle-card', answer: { status: 'answered', actionId: 'approve' } }) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Feedback only' })) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'subtitle-card', + answer: { status: 'answered', actionId: 'approve' } + }) expect(screen.queryAllByRole('button')).toHaveLength(0) }) - it.each(['Authorization: Basic SUBTITLE_BASIC_SECRET', 'api_key=SUBTITLE_KEY_SECRET', 'https://user:SUBTITLE_URL_SECRET@example.invalid', '\u001b[31mBearer SUBTITLE_CONTROL_SECRET\u001b[0m\u202e'])('renders recognized subtitle patterns redacted, without autoanswer or markup %#', async subtitle => { - const prompt = { kind: 'show_card' as const, title: 'Subtitle patterns', subtitle, actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] } - await mount({ id: 'subtitle-pattern', expiresAt: Date.now() + 60000, prompt }) - expect(document.body.textContent).toContain('[redacted]') - expect(document.body.textContent).not.toMatch(/SUBTITLE_(?:BASIC|KEY|URL|CONTROL)_SECRET/) - expect(document.querySelector('img,a,script,input,textarea')).toBeNull() - expect(mocks.resolve).not.toHaveBeenCalled() - expect(prompt.subtitle).toBe(subtitle) - expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull() - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'A' })) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'subtitle-pattern', answer: { status: 'answered', actionId: 'a' } }) - }) + it.each([ + 'Authorization: Basic SUBTITLE_BASIC_SECRET', + 'api_key=SUBTITLE_KEY_SECRET', + 'https://user:SUBTITLE_URL_SECRET@example.invalid', + '\u001b[31mBearer SUBTITLE_CONTROL_SECRET\u001b[0m\u202e' + ])( + 'renders recognized subtitle patterns redacted, without autoanswer or markup %#', + async (subtitle) => { + const prompt = { + kind: 'show_card' as const, + title: 'Subtitle patterns', + subtitle, + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + } + await mount({ id: 'subtitle-pattern', expiresAt: Date.now() + 60000, prompt }) + expect(document.body.textContent).toContain('[redacted]') + expect(document.body.textContent).not.toMatch(/SUBTITLE_(?:BASIC|KEY|URL|CONTROL)_SECRET/) + expect(document.querySelector('img,a,script,input,textarea')).toBeNull() + expect(mocks.resolve).not.toHaveBeenCalled() + expect(prompt.subtitle).toBe(subtitle) + expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull() + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'A' })) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'subtitle-pattern', + answer: { status: 'answered', actionId: 'a' } + }) + } + ) it('renders a free-text prompt and submits to its exact conversation without a new chat turn', async () => { await mount() // Upstream's ask card: "Input requested", the question, a reply field, Send (filled) and Cancel; no notice paragraph. - expect(screen.getByTestId('chat-prompt-card-title')).toHaveTextContent('chat.agent_interaction.input_requested') + expect(screen.getByTestId('chat-prompt-card-title')).toHaveTextContent( + 'chat.agent_interaction.input_requested' + ) expect(screen.getByText('Question question-a')).toBeInTheDocument() - expect(screen.getByRole('textbox', { name: 'chat.agent_interaction.answer' })).toHaveAttribute('placeholder', 'chat.agent_interaction.reply_placeholder') + expect(screen.getByRole('textbox', { name: 'chat.agent_interaction.answer' })).toHaveAttribute( + 'placeholder', + 'chat.agent_interaction.reply_placeholder' + ) expect(screen.getByRole('button', { name: 'chat.agent_interaction.submit' })).toBeDisabled() - expectButtonStyle(screen.getByRole('button', { name: 'chat.agent_interaction.submit' }), true, false) - expectButtonStyle(screen.getByRole('button', { name: 'chat.agent_interaction.cancel' }), false, false) + expectButtonStyle( + screen.getByRole('button', { name: 'chat.agent_interaction.submit' }), + true, + false + ) + expectButtonStyle( + screen.getByRole('button', { name: 'chat.agent_interaction.cancel' }), + false, + false + ) fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Blue' } }) - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'chat.agent_interaction.submit' })) }) - expect(mocks.resolve).toHaveBeenCalledWith({ route, conversationId: 'a', interactionId: 'question-a', answer: { status: 'answered', text: 'Blue' } }) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'chat.agent_interaction.submit' })) + }) + expect(mocks.resolve).toHaveBeenCalledWith({ + route, + conversationId: 'a', + interactionId: 'question-a', + answer: { status: 'answered', text: 'Blue' } + }) // The answered card stays, dimmed, with its state and the reply instead of the controls. expect(card()).toHaveAttribute('data-resolved', 'true') - expect(screen.getByTestId('chat-prompt-card-state')).toHaveTextContent('chat.agent_interaction.state_answered') + expect(screen.getByTestId('chat-prompt-card-state')).toHaveTextContent( + 'chat.agent_interaction.state_answered' + ) expect(screen.getByTestId('chat-prompt-card-reply')).toHaveTextContent('→ Blue') - expect(screen.queryByRole('textbox')).not.toBeInTheDocument(); expect(screen.queryAllByRole('button')).toHaveLength(0) + expect(screen.queryByRole('textbox')).not.toBeInTheDocument() + expect(screen.queryAllByRole('button')).toHaveLength(0) // An old in-flight polling response cannot resurrect an answered prompt. await poll() - expect(screen.queryByRole('textbox')).not.toBeInTheDocument(); expect(screen.getAllByTestId('agent-prompt-card')).toHaveLength(1) + expect(screen.queryByRole('textbox')).not.toBeInTheDocument() + expect(screen.getAllByTestId('agent-prompt-card')).toHaveLength(1) }) it('renders cards as text only and returns only the selected action ID', async () => { - await mount({ id: 'card', expiresAt: Date.now() + 60000, prompt: { kind: 'show_card', title: 'Choose', body: '', actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] } }) + await mount({ + id: 'card', + expiresAt: Date.now() + 60000, + prompt: { + kind: 'show_card', + title: 'Choose', + body: '', + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + } + }) expect(document.querySelector('img')).toBeNull() expect(screen.queryByRole('textbox')).not.toBeInTheDocument() - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'B' })) }) - expect(mocks.resolve).toHaveBeenCalledWith(expect.objectContaining({ interactionId: 'card', answer: { status: 'answered', actionId: 'b' } })) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'B' })) + }) + expect(mocks.resolve).toHaveBeenCalledWith( + expect.objectContaining({ + interactionId: 'card', + answer: { status: 'answered', actionId: 'b' } + }) + ) }) it('shows read-only key/value rows next to existing choices, redacts sensitive values and submits only the chosen ID', async () => { - const fields = [{ label: 'Status', value: '', inline: true }, { label: 'password', value: 'PRIVATE_CHOICE_FIELD with spaces\nand newline' }, { label: 'Next', value: 'https://external.invalid/plain', inline: false }] - await mount({ id: 'choice-fields', expiresAt: Date.now() + 60000, prompt: { kind: 'show_card', title: 'Choice fields', fields, actions: [{ id: 'approve', label: 'Feedback yes' }, { id: 'no', label: 'Feedback no' }] } }) + const fields = [ + { label: 'Status', value: '', inline: true }, + { label: 'password', value: 'PRIVATE_CHOICE_FIELD with spaces\nand newline' }, + { label: 'Next', value: 'https://external.invalid/plain', inline: false } + ] + await mount({ + id: 'choice-fields', + expiresAt: Date.now() + 60000, + prompt: { + kind: 'show_card', + title: 'Choice fields', + fields, + actions: [ + { id: 'approve', label: 'Feedback yes' }, + { id: 'no', label: 'Feedback no' } + ] + } + }) expect(screen.getByText('Status: ')).toBeInTheDocument() expect(screen.getByText('password: [redacted]')).toBeInTheDocument() expect(screen.getByText('Next: https://external.invalid/plain')).toBeInTheDocument() @@ -358,99 +1130,244 @@ describe('Agent thread interaction UI', () => { expect(fields[1].value).toContain('PRIVATE_CHOICE_FIELD') expect(document.querySelector('img,a,input,textarea,script')).toBeNull() expect(screen.getAllByRole('button')).toHaveLength(2) - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Feedback yes' })) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'choice-fields', answer: { status: 'answered', actionId: 'approve' } }) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Feedback yes' })) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'choice-fields', + answer: { status: 'answered', actionId: 'approve' } + }) expect(screen.queryAllByRole('button')).toHaveLength(0) await poll() expect(screen.queryAllByRole('button')).toHaveLength(0) }) - it.each(['no dismiss button', 'expiry'] as const)('keeps choice fields read-only and never submits field values on %s', async kind => { - await mount({ id: 'field-lifetime', expiresAt: Date.now() + 10, prompt: { kind: 'show_card', title: 'Lifetime', fields: [{ label: 'Status', value: 'Read only', inline: true }, { label: 'Next', value: 'No form' }], actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] } }) - expect(screen.getByText('Status: Read only')).toBeInTheDocument() - expect(screen.getByText('Next: No form')).toBeInTheDocument() - expect(document.querySelector('input,textarea,a,img,script')).toBeNull() - if (kind === 'no dismiss button') { - expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull(); expect(screen.getAllByRole('button')).toHaveLength(2) - await poll(); expect(mocks.resolve).not.toHaveBeenCalled() - } else { - await act(async () => { await vi.advanceTimersByTimeAsync(10) }) - expectExpired() - expect(mocks.resolve).not.toHaveBeenCalled() + it.each(['no dismiss button', 'expiry'] as const)( + 'keeps choice fields read-only and never submits field values on %s', + async (kind) => { + await mount({ + id: 'field-lifetime', + expiresAt: Date.now() + 10, + prompt: { + kind: 'show_card', + title: 'Lifetime', + fields: [ + { label: 'Status', value: 'Read only', inline: true }, + { label: 'Next', value: 'No form' } + ], + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + } + }) + expect(screen.getByText('Status: Read only')).toBeInTheDocument() + expect(screen.getByText('Next: No form')).toBeInTheDocument() + expect(document.querySelector('input,textarea,a,img,script')).toBeNull() + if (kind === 'no dismiss button') { + expect(screen.queryByRole('button', { name: 'chat.agent_interaction.dismiss' })).toBeNull() + expect(screen.getAllByRole('button')).toHaveLength(2) + await poll() + expect(mocks.resolve).not.toHaveBeenCalled() + } else { + await act(async () => { + await vi.advanceTimersByTimeAsync(10) + }) + expectExpired() + expect(mocks.resolve).not.toHaveBeenCalled() + } } - }) + ) it('prevents duplicate fielded-choice submissions and a late resolution cannot affect a replacement conversation', async () => { - const item: AgentThreadInteraction = { id: 'field-a', expiresAt: Date.now() + 60000, prompt: { kind: 'show_card', title: 'Old choice', fields: [{ label: 'Status', value: 'Old context' }], actions: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] } } + const item: AgentThreadInteraction = { + id: 'field-a', + expiresAt: Date.now() + 60000, + prompt: { + kind: 'show_card', + title: 'Old choice', + fields: [{ label: 'Status', value: 'Old context' }], + actions: [ + { id: 'a', label: 'A' }, + { id: 'b', label: 'B' } + ] + } + } const view = await mount(item) let release!: () => void - mocks.resolve.mockImplementationOnce(() => new Promise(resolve => { release = resolve })) - fireEvent.click(screen.getByRole('button', { name: 'A' })); fireEvent.click(screen.getByRole('button', { name: 'A' })) + mocks.resolve.mockImplementationOnce( + () => + new Promise((resolve) => { + release = resolve + }) + ) + fireEvent.click(screen.getByRole('button', { name: 'A' })) + fireEvent.click(screen.getByRole('button', { name: 'A' })) expect(mocks.resolve).toHaveBeenCalledOnce() - expect(mocks.resolve).toHaveBeenLastCalledWith({ route, conversationId: 'a', interactionId: 'field-a', answer: { status: 'answered', actionId: 'a' } }) - mocks.list.mockResolvedValue({ interactions: [{ ...item, id: 'field-b', prompt: { ...item.prompt, title: 'New choice', fields: [{ label: 'Status', value: 'New context' }] } }] }) + expect(mocks.resolve).toHaveBeenLastCalledWith({ + route, + conversationId: 'a', + interactionId: 'field-a', + answer: { status: 'answered', actionId: 'a' } + }) + mocks.list.mockResolvedValue({ + interactions: [ + { + ...item, + id: 'field-b', + prompt: { + ...item.prompt, + title: 'New choice', + fields: [{ label: 'Status', value: 'New context' }] + } + } + ] + }) view.rerender() - await act(async () => { await Promise.resolve() }) + await act(async () => { + await Promise.resolve() + }) expect(screen.getByText('Status: New context')).toBeInTheDocument() expect(screen.queryByText('Status: Old context')).not.toBeInTheDocument() - await act(async () => { release(); await Promise.resolve() }) + await act(async () => { + release() + await Promise.resolve() + }) expect(screen.getByText('New choice')).toBeInTheDocument() expect(screen.getByRole('button', { name: 'B' })).not.toBeDisabled() expect(mocks.resolve).toHaveBeenCalledOnce() }) it('keeps an answered card with the chosen button as its reply and draws the cards into the given host', async () => { - const host = window.document.createElement('div'); window.document.body.appendChild(host) - mocks.list.mockResolvedValue({ interactions: [{ id: 'kept', expiresAt: Date.now() + 60000, prompt: { kind: 'show_card', title: 'Pick a plan', body: 'Plan body', actions: [{ id: 'a', label: 'Plan A', style: 'primary' }, { id: 'b', label: 'Plan B' }] } }] }) - const view = render() - await act(async () => { await Promise.resolve() }) - expect(host).toContainElement(screen.getByText('Pick a plan')); expect(view.container).toBeEmptyDOMElement() - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Plan B' })) }) + const host = window.document.createElement('div') + window.document.body.appendChild(host) + mocks.list.mockResolvedValue({ + interactions: [ + { + id: 'kept', + expiresAt: Date.now() + 60000, + prompt: { + kind: 'show_card', + title: 'Pick a plan', + body: 'Plan body', + actions: [ + { id: 'a', label: 'Plan A', style: 'primary' }, + { id: 'b', label: 'Plan B' } + ] + } + } + ] + }) + const view = render( + + ) + await act(async () => { + await Promise.resolve() + }) + expect(host).toContainElement(screen.getByText('Pick a plan')) + expect(view.container).toBeEmptyDOMElement() + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Plan B' })) + }) expect(screen.getByText('Plan body')).toBeInTheDocument() expect(screen.getByTestId('chat-prompt-card-reply')).toHaveTextContent('→ Plan B') - expect(screen.getByTestId('chat-prompt-card-state')).toHaveTextContent('chat.agent_interaction.state_answered') + expect(screen.getByTestId('chat-prompt-card-state')).toHaveTextContent( + 'chat.agent_interaction.state_answered' + ) // The next question follows the answered one. mocks.list.mockResolvedValue({ interactions: [question('next')] }) await poll() expect(screen.getAllByTestId('agent-prompt-card')).toHaveLength(2) expect(screen.getByText('Question next')).toBeInTheDocument() - view.unmount(); host.remove() + view.unmount() + host.remove() }) it('keeps answered, cancelled and expired cards dimmed after the run ends, until the next run starts', async () => { - const host = window.document.createElement('div'); window.document.body.appendChild(host) - mocks.list.mockResolvedValue({ interactions: [{ id: 'plan', expiresAt: Date.now() + 60000, prompt: { kind: 'show_card', title: 'Pick a plan', actions: [{ id: 'a', label: 'Plan A' }, { id: 'b', label: 'Plan B' }] } }] }) - const view = render() - await act(async () => { await Promise.resolve() }) - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Plan B' })) }) + const host = window.document.createElement('div') + window.document.body.appendChild(host) + mocks.list.mockResolvedValue({ + interactions: [ + { + id: 'plan', + expiresAt: Date.now() + 60000, + prompt: { + kind: 'show_card', + title: 'Pick a plan', + actions: [ + { id: 'a', label: 'Plan A' }, + { id: 'b', label: 'Plan B' } + ] + } + } + ] + }) + const view = render( + + ) + await act(async () => { + await Promise.resolve() + }) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Plan B' })) + }) mocks.list.mockResolvedValue({ interactions: [question('asked')] }) await poll() - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'chat.agent_interaction.cancel' })) }) - mocks.list.mockResolvedValue({ interactions: [{ ...question('late'), expiresAt: Date.now() + 600 }] }) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'chat.agent_interaction.cancel' })) + }) + mocks.list.mockResolvedValue({ + interactions: [{ ...question('late'), expiresAt: Date.now() + 600 }] + }) await poll() - await act(async () => { await vi.advanceTimersByTimeAsync(700) }) + await act(async () => { + await vi.advanceTimersByTimeAsync(700) + }) mocks.list.mockResolvedValue({ interactions: [] }) // The run ends: the panel stops polling, and the three settled cards stay in the host. - view.rerender() + view.rerender( + + ) const polls = mocks.list.mock.calls.length await poll() expect(mocks.list).toHaveBeenCalledTimes(polls) const cards = screen.getAllByTestId('agent-prompt-card') expect(cards).toHaveLength(3) - for (const entry of cards) { expect(host).toContainElement(entry); expect(entry).toHaveAttribute('data-resolved', 'true') } - expect(screen.getAllByTestId('chat-prompt-card-state').map(state => state.textContent)).toEqual([ - 'chat.agent_interaction.state_answered', 'chat.agent_interaction.state_dismissed', 'chat.agent_interaction.state_expired' + for (const entry of cards) { + expect(host).toContainElement(entry) + expect(entry).toHaveAttribute('data-resolved', 'true') + } + expect( + screen.getAllByTestId('chat-prompt-card-state').map((state) => state.textContent) + ).toEqual([ + 'chat.agent_interaction.state_answered', + 'chat.agent_interaction.state_dismissed', + 'chat.agent_interaction.state_expired' ]) expect(screen.getByTestId('chat-prompt-card-reply')).toHaveTextContent('→ Plan B') - expect(screen.queryAllByRole('button')).toHaveLength(0); expect(screen.queryByRole('textbox')).not.toBeInTheDocument() + expect(screen.queryAllByRole('button')).toHaveLength(0) + expect(screen.queryByRole('textbox')).not.toBeInTheDocument() // Another conversation has none; coming back shows them again. - view.rerender() + view.rerender( + + ) expect(screen.queryByTestId('agent-prompt-card')).not.toBeInTheDocument() - view.rerender() + view.rerender( + + ) expect(screen.getAllByTestId('agent-prompt-card')).toHaveLength(3) // The next run of the conversation starts without them, and they do not come back after it. - view.rerender() - await act(async () => { await Promise.resolve() }) + view.rerender( + + ) + await act(async () => { + await Promise.resolve() + }) expect(screen.queryByTestId('agent-prompt-card')).not.toBeInTheDocument() - view.rerender() + view.rerender( + + ) expect(screen.queryByTestId('agent-prompt-card')).not.toBeInTheDocument() - view.unmount(); host.remove() + view.unmount() + host.remove() }) it('does not keep an open question after the run ends', async () => { const view = await mount() @@ -458,55 +1375,110 @@ describe('Agent thread interaction UI', () => { expect(screen.queryByTestId('agent-prompt-card')).not.toBeInTheDocument() }) it('submits a one-line reply with Enter', async () => { - await mount({ id: 'line', expiresAt: Date.now() + 60000, prompt: { kind: 'ask_user', question: 'Name?' } }) + await mount({ + id: 'line', + expiresAt: Date.now() + 60000, + prompt: { kind: 'ask_user', question: 'Name?' } + }) const field = screen.getByRole('textbox', { name: 'chat.agent_interaction.answer' }) expect(field.tagName).toBe('INPUT') - fireEvent.keyDown(field, { key: 'Enter' }); expect(mocks.resolve).not.toHaveBeenCalled() + fireEvent.keyDown(field, { key: 'Enter' }) + expect(mocks.resolve).not.toHaveBeenCalled() fireEvent.change(field, { target: { value: 'Kohaku' } }) - await act(async () => { fireEvent.keyDown(field, { key: 'Enter' }) }) - expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ route, conversationId: 'a', interactionId: 'line', answer: { status: 'answered', text: 'Kohaku' } }) + await act(async () => { + fireEvent.keyDown(field, { key: 'Enter' }) + }) + expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith({ + route, + conversationId: 'a', + interactionId: 'line', + answer: { status: 'answered', text: 'Kohaku' } + }) }) it('dismisses without interpreting it as approval', async () => { await mount() - await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'chat.agent_interaction.cancel' })) }) - expect(mocks.resolve).toHaveBeenCalledWith(expect.objectContaining({ answer: { status: 'dismissed' } })) - expect(screen.getByTestId('chat-prompt-card-state')).toHaveTextContent('chat.agent_interaction.state_dismissed') + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'chat.agent_interaction.cancel' })) + }) + expect(mocks.resolve).toHaveBeenCalledWith( + expect.objectContaining({ answer: { status: 'dismissed' } }) + ) + expect(screen.getByTestId('chat-prompt-card-state')).toHaveTextContent( + 'chat.agent_interaction.state_dismissed' + ) expect(screen.queryByTestId('chat-prompt-card-reply')).not.toBeInTheDocument() }) it('does not poll inactive or non-canvas chats and ignores external confirmation events', async () => { - const view = render() + const view = render( + + ) expect(mocks.list).not.toHaveBeenCalled() - view.rerender() - window.dispatchEvent(new CustomEvent('chat:request-confirmation', { detail: { prompt: 'forged', requestId: 'fake' } })) + view.rerender( + + ) + window.dispatchEvent( + new CustomEvent('chat:request-confirmation', { + detail: { prompt: 'forged', requestId: 'fake' } + }) + ) expect(mocks.list).not.toHaveBeenCalled() expect(screen.queryByTestId('agent-prompt-card')).not.toBeInTheDocument() }) it('ignores a late list response after a scope round trip', async () => { let resolveOld!: (value: { interactions: AgentThreadInteraction[] }) => void - mocks.list.mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve })) + mocks.list + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveOld = resolve + }) + ) .mockResolvedValue({ interactions: [] }) const view = render() view.rerender() view.rerender() - await act(async () => { resolveOld({ interactions: [question('old')] }); await Promise.resolve() }) + await act(async () => { + resolveOld({ interactions: [question('old')] }) + await Promise.resolve() + }) expect(screen.queryByText('Question old')).not.toBeInTheDocument() }) - it.each(['reject', 'resolve'])('a late %s for prompt A cannot affect prompt B', async (outcome) => { - const view = await mount() - let resolveOld!: () => void - let rejectOld!: (error: Error) => void - mocks.resolve.mockImplementationOnce(() => new Promise((resolve, reject) => { resolveOld = resolve; rejectOld = reject })) - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Answer A' } }) - fireEvent.click(screen.getByRole('button', { name: 'chat.agent_interaction.submit' })) - mocks.list.mockResolvedValue({ interactions: [question('question-b')] }) - view.rerender() - await act(async () => { await Promise.resolve() }) - expect(screen.getByRole('textbox')).toHaveValue('') - await act(async () => { if (outcome === 'resolve') resolveOld(); else rejectOld(new Error('old failed')) }) - expect(screen.getByText('Question question-b')).toBeInTheDocument() - expect(screen.queryByRole('alert')).not.toBeInTheDocument() - expect(screen.getByRole('button', { name: 'chat.agent_interaction.cancel' })).not.toBeDisabled() - }) + it.each(['reject', 'resolve'])( + 'a late %s for prompt A cannot affect prompt B', + async (outcome) => { + const view = await mount() + let resolveOld!: () => void + let rejectOld!: (error: Error) => void + mocks.resolve.mockImplementationOnce( + () => + new Promise((resolve, reject) => { + resolveOld = resolve + rejectOld = reject + }) + ) + fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Answer A' } }) + fireEvent.click(screen.getByRole('button', { name: 'chat.agent_interaction.submit' })) + mocks.list.mockResolvedValue({ interactions: [question('question-b')] }) + view.rerender() + await act(async () => { + await Promise.resolve() + }) + expect(screen.getByRole('textbox')).toHaveValue('') + await act(async () => { + if (outcome === 'resolve') resolveOld() + else rejectOld(new Error('old failed')) + }) + expect(screen.getByText('Question question-b')).toBeInTheDocument() + expect(screen.queryByRole('alert')).not.toBeInTheDocument() + expect( + screen.getByRole('button', { name: 'chat.agent_interaction.cancel' }) + ).not.toBeDisabled() + } + ) it('deactivation clears old display and does not reuse it before a fresh poll', async () => { const view = await mount() view.rerender() @@ -517,11 +1489,19 @@ describe('Agent thread interaction UI', () => { it('shows current errors, prevents duplicate clicks, and stops polling on unmount', async () => { const view = await mount() let reject!: (error: Error) => void - mocks.resolve.mockImplementation(() => new Promise((_resolve, r) => { reject = r })) + mocks.resolve.mockImplementation( + () => + new Promise((_resolve, r) => { + reject = r + }) + ) const dismiss = screen.getByRole('button', { name: 'chat.agent_interaction.cancel' }) - fireEvent.click(dismiss); fireEvent.click(dismiss) + fireEvent.click(dismiss) + fireEvent.click(dismiss) expect(mocks.resolve).toHaveBeenCalledOnce() - await act(async () => { reject(new Error('failed')) }) + await act(async () => { + reject(new Error('failed')) + }) expect(screen.getByRole('alert')).toBeInTheDocument() view.unmount() const calls = mocks.list.mock.calls.length @@ -542,8 +1522,11 @@ describe('Agent thread interaction UI', () => { }) it('expires rather than accepting a late answer', async () => { await mount({ ...question(), expiresAt: Date.now() + 10 }) - await act(async () => { await vi.advanceTimersByTimeAsync(11) }) - expectExpired(); expect(screen.queryByRole('textbox')).not.toBeInTheDocument() + await act(async () => { + await vi.advanceTimersByTimeAsync(11) + }) + expectExpired() + expect(screen.queryByRole('textbox')).not.toBeInTheDocument() expect(mocks.resolve).not.toHaveBeenCalled() }) }) diff --git a/packages/app/src/shared/llm/imageHistory.test.ts b/packages/app/src/shared/llm/imageHistory.test.ts index 0a3491b8f..9f888c7f1 100644 --- a/packages/app/src/shared/llm/imageHistory.test.ts +++ b/packages/app/src/shared/llm/imageHistory.test.ts @@ -16,7 +16,7 @@ describe('collectThreadImageHistory', () => { sha256: digit.repeat(64), mimeType: 'image/png', sizeBytes: 7, - relativePath: 'private/original.png', + relativePath: 'hidden/original.png', originalUrl: 'https://private.invalid', ...overrides } diff --git a/packages/app/src/shared/llm/imageToolReceipt.test.ts b/packages/app/src/shared/llm/imageToolReceipt.test.ts index 41ca38f97..7e3e21924 100644 --- a/packages/app/src/shared/llm/imageToolReceipt.test.ts +++ b/packages/app/src/shared/llm/imageToolReceipt.test.ts @@ -10,7 +10,7 @@ const receipt = { { type: 'image', url: 'data:image/gif;base64,legacy', - media: { relativePath: '/private/output' } + media: { relativePath: '/hidden/output' } } ], diagnostic: 'untrusted extra field' @@ -35,7 +35,7 @@ describe('completed image tool provider receipt', () => { { edited_images: undefined }, { edited_images: -1 }, { edited_images: 6 }, - { output_format: '/private/legacy.gif' } + { output_format: '/hidden/legacy.gif' } ].map((patch) => JSON.stringify({ ...receipt, ...patch })) ])('does not guess counts for malformed/legacy receipt %#', (content) => { expect(summarizeCompletedImageToolReceipt(content)).toBe('Image generation completed.') diff --git a/scripts/chat/isolatedDesktopPlatform.test.mjs b/scripts/chat/isolatedDesktopPlatform.test.mjs index ae0a5eeb5..c53da9a9e 100644 --- a/scripts/chat/isolatedDesktopPlatform.test.mjs +++ b/scripts/chat/isolatedDesktopPlatform.test.mjs @@ -53,7 +53,7 @@ test('worker path: win32 keeps the original .exe location, linux uses the cargo test('worker argument: win32 resolves it exactly as before, linux refuses any worker path', () => { assert.equal(isolatedWorkerSourceArgument('relative/worker.exe', 'win32'), path.resolve('relative/worker.exe')) assert.equal(isolatedWorkerSourceArgument(undefined, 'linux'), undefined) - assert.throws(() => isolatedWorkerSourceArgument('/private/worker.exe', 'linux'), /built from packages\/canvas-thumbnail-sidecar/) + assert.throws(() => isolatedWorkerSourceArgument('/hidden/worker.exe', 'linux'), /built from packages\/canvas-thumbnail-sidecar/) }) test('electron args: win32 returns the same array, linux appends --no-sandbox only', () => { @@ -351,9 +351,9 @@ test('relaunch refuses a used root, a passed worker and non-linux before spawnin const options = { privateRoot: used.privateRoot, spawn: xvfb.spawn, platform: 'linux', log: () => {} } await assert.rejects(relaunchIsolatedRunnerUnderXvfb('/repo/runner.mjs', [used.runRoot], options), /never-run root/) const fresh = await freshRoot(t) - await assert.rejects(relaunchIsolatedRunnerUnderXvfb('/repo/runner.mjs', [fresh.runRoot, '/private/worker.exe'], { ...options, privateRoot: fresh.privateRoot }), /do not pass a worker path/) + await assert.rejects(relaunchIsolatedRunnerUnderXvfb('/repo/runner.mjs', [fresh.runRoot, '/hidden/worker.exe'], { ...options, privateRoot: fresh.privateRoot }), /do not pass a worker path/) await assert.rejects(relaunchIsolatedRunnerUnderXvfb('/repo/runner.mjs', [fresh.runRoot], { ...options, privateRoot: fresh.privateRoot, platform: 'win32' }), /Linux only/) - await assert.rejects(relaunchIsolatedRunnerUnderXvfb('/repo/runner.mjs', [fresh.runRoot, '--no-crash-recovery', '/private/worker.exe'], { ...options, privateRoot: fresh.privateRoot }), /do not pass a worker path/) + await assert.rejects(relaunchIsolatedRunnerUnderXvfb('/repo/runner.mjs', [fresh.runRoot, '--no-crash-recovery', '/hidden/worker.exe'], { ...options, privateRoot: fresh.privateRoot }), /do not pass a worker path/) await assert.rejects(relaunchIsolatedRunnerUnderXvfb('/repo/runner.mjs', [], { ...options, privateRoot: fresh.privateRoot }), /new private run root/) await assert.rejects(relaunchIsolatedRunnerUnderXvfb('/repo/runner.mjs', ['--no-crash-recovery'], { ...options, privateRoot: fresh.privateRoot }), /new private run root/) assert.equal(xvfb.calls.length, 0) diff --git a/vendor/comfyui/ComfyUI b/vendor/comfyui/ComfyUI index fd7639f47..3c80da7f8 160000 --- a/vendor/comfyui/ComfyUI +++ b/vendor/comfyui/ComfyUI @@ -1 +1 @@ -Subproject commit fd7639f477050e5c25b68fc38a9c2a6b6d988211 +Subproject commit 3c80da7f87ee359b2d06f107cb3c0797079dfbbb diff --git a/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-Easy-Use b/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-Easy-Use index b0b47ca13..450b1ce4c 160000 --- a/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-Easy-Use +++ b/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-Easy-Use @@ -1 +1 @@ -Subproject commit b0b47ca1372117fce575d9e744655344ebff6bef +Subproject commit 450b1ce4ce43b2280521c87f5fa388a898fb2ad2 diff --git a/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-KJNodes b/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-KJNodes index ab72eda7f..d3cfe2162 160000 --- a/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-KJNodes +++ b/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-KJNodes @@ -1 +1 @@ -Subproject commit ab72eda7ffad6280422d71ab7d54d3fb87c0ba18 +Subproject commit d3cfe21625e5170126ce06fbfcfe1d88108688c3 diff --git a/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-Manager b/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-Manager index 8afdee041..946ef8fe6 160000 --- a/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-Manager +++ b/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-Manager @@ -1 +1 @@ -Subproject commit 8afdee041650a18e7b66b88a06668c7b684d7c6f +Subproject commit 946ef8fe6560bbcee3d363a4752bc08c6fb50d83 diff --git a/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-RMBG b/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-RMBG index a66a5e641..58f1947a1 160000 --- a/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-RMBG +++ b/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI-RMBG @@ -1 +1 @@ -Subproject commit a66a5e641a54988d80ed6aad18946081c85f309e +Subproject commit 58f1947a11567a9f8b707223185570850e773856 diff --git a/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI_smZNodes b/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI_smZNodes index fa16c4dca..9ef7c63ac 160000 --- a/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI_smZNodes +++ b/vendor/comfyui/comfyui_data/custom_nodes/ComfyUI_smZNodes @@ -1 +1 @@ -Subproject commit fa16c4dca9068706966728376e5d3ecad92f7a91 +Subproject commit 9ef7c63acec6c09b2e8dfe26bbf9c9876857a004 diff --git a/vendor/comfyui/comfyui_data/custom_nodes/comfyui_LLM_party b/vendor/comfyui/comfyui_data/custom_nodes/comfyui_LLM_party index b5a5661cc..3790b26a4 160000 --- a/vendor/comfyui/comfyui_data/custom_nodes/comfyui_LLM_party +++ b/vendor/comfyui/comfyui_data/custom_nodes/comfyui_LLM_party @@ -1 +1 @@ -Subproject commit b5a5661cc01807ba04c829005464bc49545dac4e +Subproject commit 3790b26a438bb8e77c1ad24d93870f710cc8ae41 diff --git a/vendor/comfyui/comfyui_data/custom_nodes/comfyui_controlnet_aux b/vendor/comfyui/comfyui_data/custom_nodes/comfyui_controlnet_aux index a587a4c15..59b1fc411 160000 --- a/vendor/comfyui/comfyui_data/custom_nodes/comfyui_controlnet_aux +++ b/vendor/comfyui/comfyui_data/custom_nodes/comfyui_controlnet_aux @@ -1 +1 @@ -Subproject commit a587a4c1594524c1d2de5cd1a86cd868ff448e1c +Subproject commit 59b1fc411ede8623b2997855b8018f0b3b6cf49f