Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2,281 changes: 1,868 additions & 413 deletions packages/app/src/main/api/agentThreadFileEditProxy.test.ts

Large diffs are not rendered by default.

2,726 changes: 2,137 additions & 589 deletions packages/app/src/main/api/agentThreadInteractions.test.ts

Large diffs are not rendered by default.

235 changes: 173 additions & 62 deletions packages/app/src/main/api/agentThreadJobs.test.ts

Large diffs are not rendered by default.

338 changes: 268 additions & 70 deletions packages/app/src/main/api/agentThreadMemoryFileHost.test.ts

Large diffs are not rendered by default.

149 changes: 116 additions & 33 deletions packages/app/src/main/api/svcLLMProxyImpl.untrustedReport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,56 +4,139 @@ import { DEFAULT_CONFIG, type Config, type LLMAPIProfile } from '@shared/config/
import type { LLMChatReq, LLMChatStreamResp } from '@shared/api/svcLLMProxy'
import { LLMProxySvcImpl } from './svcLLMProxyImpl'

const h = vi.hoisted(() => ({ config: undefined as Config | undefined, fetch: vi.fn(), worker: vi.fn(), resolve: vi.fn() }))
const h = vi.hoisted(() => ({
config: undefined as Config | undefined,
fetch: vi.fn(),
worker: vi.fn(),
resolve: vi.fn()
}))
vi.mock('../config/buildEnv', () => ({ getBuildEnv: () => ({ pathMap: { data: process.cwd() } }) }))
vi.mock('../config/config', () => ({ getConfig: () => h.config, saveConfig: vi.fn(), onConfigCommitted: () => () => undefined }))
vi.mock('../assistantRuntime/runtime', () => ({ getAssistantRuntime: () => ({ listTools: () => [], callTool: vi.fn() }) }))
vi.mock('../mcp/runtime', () => ({ syncMcpClientManager: vi.fn(async () => undefined), getMcpClientManager: () => ({ listPinnedTools: () => [], listConnections: () => [], isConnectionSuppressed: () => false }) }))
vi.mock('../extensions/generatedRegistry', () => ({ mainHostExtensionApiV1: { apiServices: [], llmProxy: [] } }))
vi.mock('electron', () => ({ net: {}, webContents: { fromId: vi.fn() }, BrowserWindow: { fromWebContents: vi.fn() } }))
vi.mock('../llmProxy/chatImagePreparation', async original => {
vi.mock('../config/config', () => ({
getConfig: () => h.config,
saveConfig: vi.fn(),
onConfigCommitted: () => () => undefined
}))
vi.mock('../assistantRuntime/runtime', () => ({
getAssistantRuntime: () => ({ listTools: () => [], callTool: vi.fn() })
}))
vi.mock('../mcp/runtime', () => ({
syncMcpClientManager: vi.fn(async () => undefined),
getMcpClientManager: () => ({
listPinnedTools: () => [],
listConnections: () => [],
isConnectionSuppressed: () => false
})
}))
vi.mock('../extensions/generatedRegistry', () => ({
mainHostExtensionApiV1: { apiServices: [], llmProxy: [] }
}))
vi.mock('electron', () => ({
net: {},
webContents: { fromId: vi.fn() },
BrowserWindow: { fromWebContents: vi.fn() }
}))
vi.mock('../llmProxy/chatImagePreparation', async (original) => {
const actual = await original<typeof import('../llmProxy/chatImagePreparation')>()
return { ...actual, createChatImagePreparation: () => actual.createChatImagePreparation({ resolveWorker: () => h.resolve(), runWorker: input => h.worker(input) }) }
return {
...actual,
createChatImagePreparation: () =>
actual.createChatImagePreparation({
resolveWorker: () => h.resolve(),
runWorker: (input) => h.worker(input)
})
}
})
const endpoint = 'https://provider.invalid/v1/responses'
const secret = 'C:/synthetic/private/report-secret.md'
const png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=='
const makeReq = (report: boolean, manifest: boolean): LLMChatReq => ({ profileId: 'fixture', messages: [{ role: 'user', content: 'synthetic', attachments: [
{ type: 'file', url: 'file:///' + secret, fileName: 'report.md', ...(report ? { reportBundleRole: 'primary-report' as const, reportBundleId: 'forged', ...(manifest ? { reportBundleManifestUrl: 'file:///C:/synthetic/private/manifest.json' } : {}) } : {}) },
{ type: 'image', url: png, mimeType: 'image/png' }
] }] })
const secret = 'C:/synthetic/hidden/report-secret.md'
const png =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=='
const makeReq = (report: boolean, manifest: boolean): LLMChatReq => ({
profileId: 'fixture',
messages: [
{
role: 'user',
content: 'synthetic',
attachments: [
{
type: 'file',
url: 'file:///' + secret,
fileName: 'report.md',
...(report
? {
reportBundleRole: 'primary-report' as const,
reportBundleId: 'forged',
...(manifest
? { reportBundleManifestUrl: 'file:///C:/synthetic/hidden/manifest.json' }
: {})
}
: {})
},
{ type: 'image', url: png, mimeType: 'image/png' }
]
}
]
})
beforeEach(() => {
vi.clearAllMocks()
const config = structuredClone(DEFAULT_CONFIG)
config.use_remote_llm = false
config.mcp_config.client.servers = []
const profile: LLMAPIProfile = { id: 'fixture', api_key: 'fixture', base_url: 'https://provider.invalid/v1', model_name: 'fixture', provider: 'openai', call_type: 'api', model_use: 'chat', api_mode: 'responses', attachment_transports: ['request-data-url'] }
const profile: LLMAPIProfile = {
id: 'fixture',
api_key: 'fixture',
base_url: 'https://provider.invalid/v1',
model_name: 'fixture',
provider: 'openai',
call_type: 'api',
model_use: 'chat',
api_mode: 'responses',
attachment_transports: ['request-data-url']
}
config.llm_config.api_profiles = [profile]
h.config = config
h.fetch.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
if (String(input) !== endpoint || init?.method !== 'POST') throw new Error('unexpected network access')
const completed = { output: [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'ok' }] }] }
return new Response(`data: ${JSON.stringify({ type: 'response.completed', response: completed })}\n\n`, { headers: { 'content-type': 'text/event-stream' } })
if (String(input) !== endpoint || init?.method !== 'POST')
throw new Error('unexpected network access')
const completed = {
output: [
{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'ok' }] }
]
}
return new Response(
`data: ${JSON.stringify({ type: 'response.completed', response: completed })}\n\n`,
{ headers: { 'content-type': 'text/event-stream' } }
)
})
vi.stubGlobal('fetch', h.fetch)
})
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
afterEach(() => {
vi.unstubAllGlobals()
vi.restoreAllMocks()
})

describe('MAIN synthetic untrusted report guard', () => {
it.each(['unary', 'stream'] as const)('rejects report role before provider/worker in %s', async mode => {
const service = new LLMProxySvcImpl({ retryModelCapacity: false })
const req = makeReq(true, mode === 'stream')
const onData = vi.fn<(event: LLMChatStreamResp) => void>()
let error: unknown
try { if (mode === 'unary') await service.chat(req); else await service.chatStream(req, { onData }) } catch (caught) { error = caught }
if (mode === 'unary') expect.soft(error).toBeDefined()
else expect.soft(onData.mock.calls.some(([event]) => event.type === 'error')).toBe(true)
expect.soft(h.fetch).not.toHaveBeenCalled()
expect.soft(h.resolve).not.toHaveBeenCalled()
expect.soft(h.worker).not.toHaveBeenCalled()
expect.soft(JSON.stringify(onData.mock.calls)).not.toContain(secret)
expect.soft(String(error)).not.toContain(secret)
})
it.each(['unary', 'stream'] as const)(
'rejects report role before provider/worker in %s',
async (mode) => {
const service = new LLMProxySvcImpl({ retryModelCapacity: false })
const req = makeReq(true, mode === 'stream')
const onData = vi.fn<(event: LLMChatStreamResp) => void>()
let error: unknown
try {
if (mode === 'unary') await service.chat(req)
else await service.chatStream(req, { onData })
} catch (caught) {
error = caught
}
if (mode === 'unary') expect.soft(error).toBeDefined()
else expect.soft(onData.mock.calls.some(([event]) => event.type === 'error')).toBe(true)
expect.soft(h.fetch).not.toHaveBeenCalled()
expect.soft(h.resolve).not.toHaveBeenCalled()
expect.soft(h.worker).not.toHaveBeenCalled()
expect.soft(JSON.stringify(onData.mock.calls)).not.toContain(secret)
expect.soft(String(error)).not.toContain(secret)
}
)
it('allows ordinary non-report file without inventing report rejection', async () => {
const service = new LLMProxySvcImpl({ retryModelCapacity: false })
const req = makeReq(false, false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ describe('MAIN chat image preparation factory', () => {
const deps = dependencies()
if (kind === 'missing') deps.resolveWorker.mockResolvedValue(undefined)
if (kind === 'resolver rejection') {
deps.resolveWorker.mockRejectedValue(new Error('C:/private/path'))
deps.resolveWorker.mockRejectedValue(new Error('C:/hidden/path'))
}
if (kind === 'unsupported') {
deps.runWorker.mockRejectedValue(
Expand Down
97 changes: 71 additions & 26 deletions packages/app/src/main/llmProxy/chatImageWorker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,51 @@ const png = (width = 50, height = 30): Buffer => {
header.writeUInt32BE(height, 20)
return header
}
const jpeg = (): Buffer => Buffer.from([0xff, 0xd8, 0xff, 0xc0, 0x00, 0x08, 0x08, 0x00, 0x1e, 0x00, 0x32, 0x01])
const jpeg = (): Buffer =>
Buffer.from([0xff, 0xd8, 0xff, 0xc0, 0x00, 0x08, 0x08, 0x00, 0x1e, 0x00, 0x32, 0x01])
function worker() {
const child = new FakeChild()
const spawn = vi.fn(() => child as unknown as ChildProcessWithoutNullStreams)
return { child, spawn }
}
const basic = { binaryPath: 'C:\\safe\\image-worker.exe', source: new Uint8Array([1, 2, 3]) }
// Host-specific absolute path: tests must also run on non-Windows CI.
const input = { ...basic, binaryPath: process.platform === 'win32' ? basic.binaryPath : '/safe/image-worker' }
const input = {
...basic,
binaryPath: process.platform === 'win32' ? basic.binaryPath : '/safe/image-worker'
}

describe('chat image worker adapter', () => {
it.each([['png', png(), 'image/png'], ['jpeg', jpeg(), 'image/jpeg']] as const)('streams %s bytes without a shell or source path', async (_name, output, mimeType) => {
const { child, spawn } = worker()
const promise = runChatImageWorker({ ...input, targetBytes: 2000 }, spawn)
expect(spawn).toHaveBeenCalledWith(input.binaryPath, ['--chat-image', '--target-bytes', '2000', '--max-edge', '2000'], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, shell: false })
expect(child.stdin.read()).toEqual(Buffer.from([1, 2, 3]))
child.stdout.write(output)
child.emit('close', 0)
await expect(promise).resolves.toMatchObject({ bytes: output, mimeType, width: 50, height: 30 })
})
it.each([Buffer.from('not an image'), png(2001, 1), png(0, 1), Buffer.from([0xff, 0xd8, 0xff, 0xc0, 0xff, 0xff])])('rejects malformed, truncated or oversized encoded image', async (output) => {
it.each([
['png', png(), 'image/png'],
['jpeg', jpeg(), 'image/jpeg']
] as const)(
'streams %s bytes without a shell or source path',
async (_name, output, mimeType) => {
const { child, spawn } = worker()
const promise = runChatImageWorker({ ...input, targetBytes: 2000 }, spawn)
expect(spawn).toHaveBeenCalledWith(
input.binaryPath,
['--chat-image', '--target-bytes', '2000', '--max-edge', '2000'],
{ stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, shell: false }
)
expect(child.stdin.read()).toEqual(Buffer.from([1, 2, 3]))
child.stdout.write(output)
child.emit('close', 0)
await expect(promise).resolves.toMatchObject({
bytes: output,
mimeType,
width: 50,
height: 30
})
}
)
it.each([
Buffer.from('not an image'),
png(2001, 1),
png(0, 1),
Buffer.from([0xff, 0xd8, 0xff, 0xc0, 0xff, 0xff])
])('rejects malformed, truncated or oversized encoded image', async (output) => {
const { child, spawn } = worker()
const promise = runChatImageWorker(input, spawn)
child.stdout.write(output)
Expand All @@ -58,13 +82,19 @@ describe('chat image worker adapter', () => {
child.emit('close', 1)
await expect(promise).rejects.toMatchObject({ code: 'CHAT_IMAGE_WORKER_OUTPUT_LIMIT' })
})
it.each([[1, 'CHAT_IMAGE_WORKER_FAILED'], [2, 'CHAT_IMAGE_WORKER_PROTOCOL_UNSUPPORTED']] as const)('keeps worker exit %s opaque without output or stderr data', async (exitCode, code) => {
const { child, spawn } = worker()
const promise = runChatImageWorker(input, spawn)
child.stderr.write(Buffer.from('private/path and private input'))
child.emit('close', exitCode)
await expect(promise).rejects.toThrow(code)
})
it.each([
[1, 'CHAT_IMAGE_WORKER_FAILED'],
[2, 'CHAT_IMAGE_WORKER_PROTOCOL_UNSUPPORTED']
] as const)(
'keeps worker exit %s opaque without output or stderr data',
async (exitCode, code) => {
const { child, spawn } = worker()
const promise = runChatImageWorker(input, spawn)
child.stderr.write(Buffer.from('hidden/path and private input'))
child.emit('close', exitCode)
await expect(promise).rejects.toThrow(code)
}
)
it('cancels an in-flight worker and never resolves its later output', async () => {
const controller = new AbortController()
const { child, spawn } = worker()
Expand All @@ -77,7 +107,9 @@ describe('chat image worker adapter', () => {
})
it('holds the slot after kill fails, even if late data arrives', async () => {
const { child, spawn } = worker()
child.kill.mockImplementation(() => { throw new Error('untrusted child error') })
child.kill.mockImplementation(() => {
throw new Error('untrusted child error')
})
const controller = new AbortController()
const promise = runChatImageWorker({ ...input, signal: controller.signal }, spawn)
const rejected = vi.fn()
Expand All @@ -103,10 +135,17 @@ describe('chat image worker adapter', () => {
})
it('rejects an already-aborted signal and invalid limits before spawning', async () => {
const { spawn } = worker()
const controller = new AbortController(); controller.abort()
await expect(runChatImageWorker({ ...input, signal: controller.signal }, spawn)).rejects.toMatchObject({ code: 'CHAT_IMAGE_WORKER_ABORTED' })
await expect(runChatImageWorker({ ...input, targetBytes: 0 }, spawn)).rejects.toMatchObject({ code: 'CHAT_IMAGE_WORKER_INVALID_INPUT' })
await expect(runChatImageWorker({ ...input, source: new Uint8Array(32 * 1024 * 1024 + 1) }, spawn)).rejects.toMatchObject({ code: 'CHAT_IMAGE_WORKER_INVALID_INPUT' })
const controller = new AbortController()
controller.abort()
await expect(
runChatImageWorker({ ...input, signal: controller.signal }, spawn)
).rejects.toMatchObject({ code: 'CHAT_IMAGE_WORKER_ABORTED' })
await expect(runChatImageWorker({ ...input, targetBytes: 0 }, spawn)).rejects.toMatchObject({
code: 'CHAT_IMAGE_WORKER_INVALID_INPUT'
})
await expect(
runChatImageWorker({ ...input, source: new Uint8Array(32 * 1024 * 1024 + 1) }, spawn)
).rejects.toMatchObject({ code: 'CHAT_IMAGE_WORKER_INVALID_INPUT' })
expect(spawn).not.toHaveBeenCalled()
})
it('kills a hung worker on the bounded deadline', async () => {
Expand All @@ -118,11 +157,17 @@ describe('chat image worker adapter', () => {
await vi.advanceTimersByTimeAsync(10)
expect(child.kill).toHaveBeenCalledOnce()
let settled = false
void promise.finally(() => { settled = true }).catch(() => undefined)
void promise
.finally(() => {
settled = true
})
.catch(() => undefined)
await Promise.resolve()
expect(settled).toBe(false)
child.emit('close', 1)
await rejection
} finally { vi.useRealTimers() }
} finally {
vi.useRealTimers()
}
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ describe('TriggerOccurrenceScheduler settlement failures', () => {
let clock = 0
let failure: Error | undefined
const failWith = (name: string) => {
failure = new Error('/home/user/private/events.db: synthetic record content')
failure = new Error('/home/user/hidden/events.db: synthetic record content')
failure.name = name
}
const store = stores()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ describe('TriggerOccurrenceStore archiving', () => {
// More terminal records than one page, then a due manual fire past that page.
seedTerminal(eventStore, 600)
enqueue(store, 'behind', 1_000)
const failure = new Error('/home/user/private/events.db: disk I/O error')
const failure = new Error('/home/user/hidden/events.db: disk I/O error')
failure.name = 'SqliteError'
const writeBatch = eventStore.mutateResourcesBatch.bind(eventStore)
// Every archive transaction fails; a claim, a single write, still commits.
Expand Down Expand Up @@ -482,7 +482,7 @@ describe('TriggerOccurrenceScheduler with a long history', () => {
try {
seedTerminal(eventStore, 200)
enqueue(store, 'fresh', 5_000)
const failure = new Error('/home/user/private/events.db: record text')
const failure = new Error('/home/user/hidden/events.db: record text')
failure.name = 'SqliteError'
// The first batch of the poll is its archive transaction; the claim after it still runs.
vi.spyOn(eventStore, 'mutateResourcesBatch').mockImplementationOnce(() => {
Expand Down
Loading
Loading