mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat: add multi-run fusion and session change walkthroughs
Fuse two to five completed multi-run entries into one synthesized session, and explain a session's diff as ordered walkthrough stops cached by diff hash. - Multi-run fusion service, persistence, routes and FuseRunDialog - Change walkthrough service, persistence, routes and ChangesWalkthroughDialog - Shared unified-diff parser plus bounded text generation, json-extract, text-truncate and service-error helpers
This commit is contained in:
1 parent
90c6ccf236
commit
b36d412ca2
66 files changed
+6228
-468
No files matched your search
@@ -0,0 +1,108 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import type { ChangeWalkthrough } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
ensureChangeWalkthroughTable,
|
||||
getChangeWalkthrough,
|
||||
saveChangeWalkthrough,
|
||||
} from '../../src/db/change-walkthroughs'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
|
||||
const SESSION_ID = 'ses_walkthrough'
|
||||
|
||||
function walkthrough(overrides: Partial<ChangeWalkthrough> = {}): ChangeWalkthrough {
|
||||
return {
|
||||
sessionId: SESSION_ID,
|
||||
diffHash: 'hash-1',
|
||||
summary: 'A short summary',
|
||||
stops: [{ title: 'First stop', explanation: 'Why it matters', hunkIds: ['f0h0'] }],
|
||||
hunks: [
|
||||
{
|
||||
id: 'f0h0',
|
||||
file: 'src/app.ts',
|
||||
status: 'modified',
|
||||
header: '@@ -1,2 +1,2 @@',
|
||||
text: '@@ -1,2 +1,2 @@\n-const a = 1;\n+const a = 2;',
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
omittedFiles: [{ file: 'assets/logo.png', reason: 'binary' }],
|
||||
createdAt: 1_000,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function walkthroughTableExists(db: Database): boolean {
|
||||
return Boolean(
|
||||
db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'change_walkthroughs'").get(),
|
||||
)
|
||||
}
|
||||
|
||||
describe('change walkthroughs', () => {
|
||||
let db: Database
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('creates the change_walkthroughs table in migration 29', () => {
|
||||
expect(walkthroughTableExists(db)).toBe(true)
|
||||
})
|
||||
|
||||
it('creates the table idempotently', () => {
|
||||
expect(() => ensureChangeWalkthroughTable(db)).not.toThrow()
|
||||
expect(walkthroughTableExists(db)).toBe(true)
|
||||
})
|
||||
|
||||
it('returns null for a session without a stored walkthrough', () => {
|
||||
expect(getChangeWalkthrough(db, 'ses_missing')).toBeNull()
|
||||
})
|
||||
|
||||
it('round-trips a stored walkthrough', () => {
|
||||
const stored = walkthrough()
|
||||
saveChangeWalkthrough(db, stored)
|
||||
|
||||
expect(getChangeWalkthrough(db, SESSION_ID)).toEqual(stored)
|
||||
})
|
||||
|
||||
it('keeps a single row holding the latest payload on repeated saves', () => {
|
||||
saveChangeWalkthrough(db, walkthrough())
|
||||
saveChangeWalkthrough(db, walkthrough({ diffHash: 'hash-2', summary: 'Updated', createdAt: 2_000 }))
|
||||
|
||||
const count = db
|
||||
.prepare('SELECT COUNT(*) AS count FROM change_walkthroughs WHERE session_id = ?')
|
||||
.get(SESSION_ID) as { count: number }
|
||||
expect(count.count).toBe(1)
|
||||
|
||||
const stored = getChangeWalkthrough(db, SESSION_ID)
|
||||
expect(stored).toMatchObject({ diffHash: 'hash-2', summary: 'Updated', createdAt: 2_000 })
|
||||
})
|
||||
|
||||
it('treats a corrupt payload as missing', () => {
|
||||
db.prepare('INSERT INTO change_walkthroughs(session_id, diff_hash, payload, created_at) VALUES(?,?,?,?)').run(
|
||||
SESSION_ID,
|
||||
'hash-1',
|
||||
'{not json',
|
||||
1_000,
|
||||
)
|
||||
|
||||
expect(getChangeWalkthrough(db, SESSION_ID)).toBeNull()
|
||||
})
|
||||
|
||||
it('treats a payload that fails schema validation as missing', () => {
|
||||
db.prepare('INSERT INTO change_walkthroughs(session_id, diff_hash, payload, created_at) VALUES(?,?,?,?)').run(
|
||||
SESSION_ID,
|
||||
'hash-1',
|
||||
JSON.stringify({ sessionId: SESSION_ID }),
|
||||
1_000,
|
||||
)
|
||||
|
||||
expect(getChangeWalkthrough(db, SESSION_ID)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,229 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { FuseMultiRunRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
createMultiRunWithEntries,
|
||||
getMultiRun,
|
||||
getMultiRunFusionByRequest,
|
||||
insertMultiRunFusion,
|
||||
listMultiRuns,
|
||||
updateMultiRunFusion,
|
||||
type CreateMultiRunFusionInput,
|
||||
} from '../../src/db/multi-runs'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { deleteRepo } from '../../src/db/queries'
|
||||
|
||||
const REPO_ID = 7
|
||||
|
||||
function fusionInput(overrides: Partial<CreateMultiRunFusionInput> = {}): CreateMultiRunFusionInput {
|
||||
return {
|
||||
multiRunId: 0,
|
||||
requestId: 'req-1',
|
||||
model: 'openai/gpt-5',
|
||||
instructions: 'combine them',
|
||||
isolated: true,
|
||||
baseRef: 'main',
|
||||
sources: [
|
||||
{ entryId: 1, sessionId: 'ses_a', model: 'openai/a', truncated: false },
|
||||
{ entryId: 2, sessionId: 'ses_b', model: 'openai/b', truncated: true },
|
||||
],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function fusionTableExists(db: Database): boolean {
|
||||
return Boolean(
|
||||
db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'multi_run_fusions'").get(),
|
||||
)
|
||||
}
|
||||
|
||||
describe('multi-run fusions', () => {
|
||||
let db: Database
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
function createRun(models = ['openai/a', 'openai/b']): number {
|
||||
const run = createMultiRunWithEntries(
|
||||
db,
|
||||
{ repoId: REPO_ID, name: 'Sweep', prompt: 'go', isolated: true, baseRef: null },
|
||||
models,
|
||||
)
|
||||
return run.id
|
||||
}
|
||||
|
||||
it('creates the multi_run_fusions table', () => {
|
||||
expect(fusionTableExists(db)).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps existing multi-run data when the fusions migration is applied', () => {
|
||||
const existing = new Database(':memory:')
|
||||
migrate(
|
||||
existing,
|
||||
allMigrations.filter((migration) => migration.id !== '202610061700-multi-run-fusions'),
|
||||
)
|
||||
existing
|
||||
.prepare('INSERT INTO multi_runs(repo_id, name, prompt, isolated, base_ref, created_at) VALUES(?,?,?,?,?,?)')
|
||||
.run(REPO_ID, 'Sweep', 'go', 1, null, 1)
|
||||
const multiRunId = Number(
|
||||
(existing.prepare('SELECT last_insert_rowid() AS id').get() as { id: number }).id,
|
||||
)
|
||||
const insertEntry = existing.prepare(
|
||||
'INSERT INTO multi_run_entries(multi_run_id, model, status, session_id, directory, error, created_at, updated_at) VALUES(?,?,?,?,?,?,?,?)',
|
||||
)
|
||||
insertEntry.run(multiRunId, 'openai/a', 'started', 'ses_a', null, null, 1, 1)
|
||||
insertEntry.run(multiRunId, 'openai/b', 'started', 'ses_b', null, null, 1, 1)
|
||||
|
||||
migrate(existing, allMigrations)
|
||||
|
||||
const reloaded = getMultiRun(existing, multiRunId)
|
||||
expect(reloaded?.entries.map((entry) => entry.model)).toEqual(['openai/a', 'openai/b'])
|
||||
expect(reloaded?.fusions).toEqual([])
|
||||
expect(fusionTableExists(existing)).toBe(true)
|
||||
existing.close()
|
||||
})
|
||||
|
||||
it('inserts a fusion once per request id and replays the stored record', () => {
|
||||
const multiRunId = createRun()
|
||||
const first = insertMultiRunFusion(db, fusionInput({ multiRunId }))
|
||||
const second = insertMultiRunFusion(db, fusionInput({ multiRunId, model: 'openai/other' }))
|
||||
|
||||
expect(first.created).toBe(true)
|
||||
expect(second.created).toBe(false)
|
||||
expect(second.fusion.id).toBe(first.fusion.id)
|
||||
expect(second.fusion.model).toBe('openai/gpt-5')
|
||||
|
||||
const count = db
|
||||
.prepare('SELECT COUNT(*) AS count FROM multi_run_fusions WHERE multi_run_id = ?')
|
||||
.get(multiRunId) as { count: number }
|
||||
expect(count.count).toBe(1)
|
||||
})
|
||||
|
||||
it('rolls back the insert when the stored sources fail readback validation', () => {
|
||||
const multiRunId = createRun()
|
||||
|
||||
expect(() =>
|
||||
insertMultiRunFusion(
|
||||
db,
|
||||
fusionInput({
|
||||
multiRunId,
|
||||
sources: [{ entryId: 1.5, sessionId: 'ses_a', model: 'openai/a', truncated: false }],
|
||||
}),
|
||||
),
|
||||
).toThrow()
|
||||
|
||||
const count = db
|
||||
.prepare('SELECT COUNT(*) AS count FROM multi_run_fusions WHERE multi_run_id = ?')
|
||||
.get(multiRunId) as { count: number }
|
||||
expect(count.count).toBe(0)
|
||||
expect(getMultiRun(db, multiRunId)?.fusions).toEqual([])
|
||||
})
|
||||
|
||||
it('stores parsed sources and the starting status of a new fusion', () => {
|
||||
const multiRunId = createRun()
|
||||
const { fusion } = insertMultiRunFusion(db, fusionInput({ multiRunId }))
|
||||
|
||||
expect(fusion).toMatchObject({ multiRunId, requestId: 'req-1', status: 'starting', isolated: true })
|
||||
expect(fusion.sources).toEqual([
|
||||
{ entryId: 1, sessionId: 'ses_a', model: 'openai/a', truncated: false },
|
||||
{ entryId: 2, sessionId: 'ses_b', model: 'openai/b', truncated: true },
|
||||
])
|
||||
})
|
||||
|
||||
it('guards updates by the current status', () => {
|
||||
const multiRunId = createRun()
|
||||
const { fusion } = insertMultiRunFusion(db, fusionInput({ multiRunId }))
|
||||
|
||||
const started = updateMultiRunFusion(db, fusion.id, ['starting'], {
|
||||
status: 'started',
|
||||
sessionId: 'ses_new',
|
||||
directory: '/worktrees/fusion',
|
||||
})
|
||||
expect(started).toMatchObject({ status: 'started', sessionId: 'ses_new', directory: '/worktrees/fusion' })
|
||||
|
||||
expect(updateMultiRunFusion(db, fusion.id, ['starting'], { status: 'failed', error: 'late' })).toBeNull()
|
||||
|
||||
const failed = updateMultiRunFusion(db, fusion.id, ['started'], { status: 'failed', error: 'boom' })
|
||||
expect(failed).toMatchObject({ status: 'failed', error: 'boom' })
|
||||
})
|
||||
|
||||
it('includes fusions with parsed sources on getMultiRun and listMultiRuns', () => {
|
||||
const multiRunId = createRun()
|
||||
insertMultiRunFusion(db, fusionInput({ multiRunId }))
|
||||
|
||||
const fetched = getMultiRun(db, multiRunId)
|
||||
expect(fetched?.fusions).toHaveLength(1)
|
||||
expect(fetched?.fusions[0]?.sources[0]).toEqual({
|
||||
entryId: 1,
|
||||
sessionId: 'ses_a',
|
||||
model: 'openai/a',
|
||||
truncated: false,
|
||||
})
|
||||
|
||||
const listed = listMultiRuns(db, REPO_ID, 20)
|
||||
expect(listed[0]?.fusions).toHaveLength(1)
|
||||
expect(listed[0]?.fusions[0]?.sources).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('returns an empty fusion list for runs without fusions', () => {
|
||||
const multiRunId = createRun()
|
||||
expect(getMultiRun(db, multiRunId)?.fusions).toEqual([])
|
||||
expect(listMultiRuns(db, REPO_ID, 20)[0]?.fusions).toEqual([])
|
||||
})
|
||||
|
||||
it('reads a fusion by its request id', () => {
|
||||
const multiRunId = createRun()
|
||||
const { fusion } = insertMultiRunFusion(db, fusionInput({ multiRunId }))
|
||||
|
||||
expect(getMultiRunFusionByRequest(db, multiRunId, 'req-1')?.id).toBe(fusion.id)
|
||||
expect(getMultiRunFusionByRequest(db, multiRunId, 'missing')).toBeNull()
|
||||
expect(getMultiRunFusionByRequest(db, multiRunId + 1, 'req-1')).toBeNull()
|
||||
})
|
||||
|
||||
it('removes fusions when the repository is deleted', () => {
|
||||
const multiRunId = createRun()
|
||||
insertMultiRunFusion(db, fusionInput({ multiRunId }))
|
||||
|
||||
deleteRepo(db, REPO_ID)
|
||||
|
||||
expect(db.prepare('SELECT COUNT(*) AS count FROM multi_run_fusions').get()).toEqual({ count: 0 })
|
||||
expect(db.prepare('SELECT COUNT(*) AS count FROM multi_run_entries').get()).toEqual({ count: 0 })
|
||||
expect(db.prepare('SELECT COUNT(*) AS count FROM multi_runs').get()).toEqual({ count: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('FuseMultiRunRequestSchema', () => {
|
||||
const valid = {
|
||||
requestId: '00000000-0000-4000-8000-000000000000',
|
||||
entryIds: [1, 2],
|
||||
model: 'openai/gpt-5',
|
||||
isolate: true,
|
||||
}
|
||||
|
||||
it('accepts at least two unique entry ids', () => {
|
||||
expect(FuseMultiRunRequestSchema.safeParse(valid).success).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects fewer than two entry ids', () => {
|
||||
expect(FuseMultiRunRequestSchema.safeParse({ ...valid, entryIds: [1] }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects duplicate entry ids', () => {
|
||||
expect(FuseMultiRunRequestSchema.safeParse({ ...valid, entryIds: [1, 1] }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a non-uuid request id', () => {
|
||||
expect(FuseMultiRunRequestSchema.safeParse({ ...valid, requestId: 'req-1' }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects instructions over the limit', () => {
|
||||
expect(FuseMultiRunRequestSchema.safeParse({ ...valid, instructions: 'x'.repeat(4001) }).success).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -242,6 +242,7 @@ describe('Database Queries', () => {
|
||||
it('should delete repo-scoped rows, including multi-runs, in one transaction', () => {
|
||||
mockDb.transaction.mockImplementation((fn: () => void) => fn)
|
||||
|
||||
const deleteFusionsStmt = { run: vi.fn().mockReturnValue({ changes: 3 }) }
|
||||
const deleteEntriesStmt = { run: vi.fn().mockReturnValue({ changes: 2 }) }
|
||||
const deleteMultiRunsStmt = { run: vi.fn().mockReturnValue({ changes: 1 }) }
|
||||
const deleteRunsStmt = { run: vi.fn().mockReturnValue({ changes: 2 }) }
|
||||
@@ -249,6 +250,7 @@ describe('Database Queries', () => {
|
||||
const deleteSettingsStmt = { run: vi.fn().mockReturnValue({ changes: 0 }) }
|
||||
const deleteRepoStmt = { run: vi.fn().mockReturnValue({ changes: 1 }) }
|
||||
mockDb.prepare
|
||||
.mockReturnValueOnce(deleteFusionsStmt)
|
||||
.mockReturnValueOnce(deleteEntriesStmt)
|
||||
.mockReturnValueOnce(deleteMultiRunsStmt)
|
||||
.mockReturnValueOnce(deleteJobsStmt)
|
||||
@@ -260,18 +262,22 @@ describe('Database Queries', () => {
|
||||
|
||||
expect(mockDb.transaction).toHaveBeenCalledTimes(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(1,
|
||||
'DELETE FROM multi_run_fusions WHERE multi_run_id IN (SELECT id FROM multi_runs WHERE repo_id = ?)'
|
||||
)
|
||||
expect(deleteFusionsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(2,
|
||||
'DELETE FROM multi_run_entries WHERE multi_run_id IN (SELECT id FROM multi_runs WHERE repo_id = ?)'
|
||||
)
|
||||
expect(deleteEntriesStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(2, 'DELETE FROM multi_runs WHERE repo_id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(3, 'DELETE FROM multi_runs WHERE repo_id = ?')
|
||||
expect(deleteMultiRunsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(3, 'DELETE FROM schedule_jobs WHERE repo_id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(4, 'DELETE FROM schedule_jobs WHERE repo_id = ?')
|
||||
expect(deleteJobsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(4, 'DELETE FROM schedule_runs WHERE repo_id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(5, 'DELETE FROM schedule_runs WHERE repo_id = ?')
|
||||
expect(deleteRunsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(5, 'DELETE FROM repo_settings WHERE repo_id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(6, 'DELETE FROM repo_settings WHERE repo_id = ?')
|
||||
expect(deleteSettingsStmt.run).toHaveBeenCalledWith(1)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(6,
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(7,
|
||||
'DELETE FROM repos WHERE id = ?'
|
||||
)
|
||||
expect(deleteRepoStmt.run).toHaveBeenCalledWith(1)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import type { FileDiffInfo, SessionInfo } from '@opencode-manager/shared/opencode'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { ChangeWalkthroughService } from '../../src/services/change-walkthroughs'
|
||||
import { createChangeWalkthroughRoutes } from '../../src/routes/change-walkthroughs'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
|
||||
const SESSION_ID = 'ses_walkthrough'
|
||||
|
||||
function change(file: string, patch: string, status: FileDiffInfo['status'] = 'modified'): FileDiffInfo {
|
||||
return { file, patch, additions: 1, deletions: 1, status }
|
||||
}
|
||||
|
||||
const CHANGES: FileDiffInfo[] = [change('src/a.ts', '@@ -1,2 +1,2 @@\n-const a = 1;\n+const a = 2;')]
|
||||
|
||||
const MODEL_REPLY = JSON.stringify({
|
||||
summary: 'A summary',
|
||||
stops: [{ title: 'First', explanation: 'Why', hunkIds: ['f0h0'] }],
|
||||
})
|
||||
|
||||
interface FakeSession {
|
||||
info?: SessionInfo | Error
|
||||
changes?: FileDiffInfo[] | Error
|
||||
}
|
||||
|
||||
function createFakeClient(sessions: Record<string, FakeSession>) {
|
||||
const generateCalls: string[] = []
|
||||
let reply = MODEL_REPLY
|
||||
|
||||
const client = {
|
||||
api: {
|
||||
session: {
|
||||
get: vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
const config = sessions[sessionID]
|
||||
if (!config) {
|
||||
throw Object.assign(new Error('Session not found'), { _tag: 'SessionNotFoundError' })
|
||||
}
|
||||
if (config.info instanceof Error) {
|
||||
throw config.info
|
||||
}
|
||||
return config.info ?? ({ id: sessionID, title: `Title ${sessionID}` } as SessionInfo)
|
||||
}),
|
||||
diff: vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
const config = sessions[sessionID]
|
||||
if (config?.changes instanceof Error) {
|
||||
throw config.changes
|
||||
}
|
||||
return config?.changes ?? []
|
||||
}),
|
||||
},
|
||||
message: {
|
||||
list: vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
if (!sessions[sessionID]) {
|
||||
return { data: [], cursor: {} }
|
||||
}
|
||||
return { data: [{ id: 'msg-1', type: 'user', time: { created: 0 }, text: 'x' }], cursor: {} }
|
||||
}),
|
||||
},
|
||||
generate: {
|
||||
text: vi.fn(async (input: { prompt: string }) => {
|
||||
generateCalls.push(input.prompt)
|
||||
return { text: reply }
|
||||
}),
|
||||
},
|
||||
},
|
||||
forwardRaw: vi.fn(),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return {
|
||||
client,
|
||||
generateCalls,
|
||||
setReply: (next: string) => {
|
||||
reply = next
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('change walkthrough routes', () => {
|
||||
let db: Database
|
||||
let sessions: Record<string, FakeSession>
|
||||
let fake: ReturnType<typeof createFakeClient>
|
||||
let app: Hono
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
sessions = { [SESSION_ID]: { changes: CHANGES } }
|
||||
fake = createFakeClient(sessions)
|
||||
const service = new ChangeWalkthroughService(db, fake.client)
|
||||
app = new Hono()
|
||||
app.route('/change-walkthroughs', createChangeWalkthroughRoutes(service))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('GET returns the state for a session', async () => {
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { walkthrough: unknown; currentDiffHash: string | null; stale: boolean }
|
||||
expect(body.walkthrough).toBeNull()
|
||||
expect(body.stale).toBe(false)
|
||||
expect(body.currentDiffHash).toEqual(expect.any(String))
|
||||
})
|
||||
|
||||
it('GET returns 404 for a missing session', async () => {
|
||||
const res = await app.request('/change-walkthroughs/ses_missing')
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
await expect(res.json()).resolves.toMatchObject({ error: 'Session not found' })
|
||||
})
|
||||
|
||||
it('POST creates a walkthrough and GET reads it back', async () => {
|
||||
const postRes = await app.request(`/change-walkthroughs/${SESSION_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
|
||||
expect(postRes.status).toBe(201)
|
||||
const created = (await postRes.json()) as { walkthrough: { summary: string; sessionId: string } }
|
||||
expect(created.walkthrough.summary).toBe('A summary')
|
||||
|
||||
const getRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
|
||||
const state = (await getRes.json()) as { walkthrough: { summary: string } }
|
||||
expect(state.walkthrough.summary).toBe('A summary')
|
||||
})
|
||||
|
||||
it('POST accepts an empty body', async () => {
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
})
|
||||
|
||||
it('POST returns 200 without a second model call when changes are unchanged', async () => {
|
||||
await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
|
||||
const second = await app.request(`/change-walkthroughs/${SESSION_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
|
||||
expect(second.status).toBe(200)
|
||||
expect(fake.generateCalls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('POST regenerates when asked', async () => {
|
||||
await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ regenerate: true }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
expect(fake.generateCalls).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('POST rejects an invalid body with 400', async () => {
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ regenerate: 'yes' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('POST rejects malformed JSON with 400', async () => {
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: '{not json',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('POST returns 409 with a code when there are no text changes', async () => {
|
||||
sessions[SESSION_ID]!.changes = [
|
||||
change('assets/logo.png', 'diff --git a/assets/logo.png b/assets/logo.png\nBinary files differ'),
|
||||
]
|
||||
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
await expect(res.json()).resolves.toMatchObject({ code: 'WALKTHROUGH_NO_TEXT_CHANGES' })
|
||||
})
|
||||
|
||||
it('POST returns 502 with a code when the model response is unparseable', async () => {
|
||||
fake.setReply('not json')
|
||||
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(502)
|
||||
await expect(res.json()).resolves.toMatchObject({ code: 'WALKTHROUGH_UNPARSEABLE' })
|
||||
})
|
||||
|
||||
it('POST returns 404 for a missing session', async () => {
|
||||
const res = await app.request('/change-walkthroughs/ses_missing', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -14,6 +14,7 @@ function createRun(overrides: Partial<MultiRun> = {}): MultiRun {
|
||||
baseRef: null,
|
||||
createdAt: 1,
|
||||
entries: [],
|
||||
fusions: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
@@ -29,16 +30,27 @@ function launchBody(overrides: Record<string, unknown> = {}): string {
|
||||
})
|
||||
}
|
||||
|
||||
function fuseBody(overrides: Record<string, unknown> = {}): string {
|
||||
return JSON.stringify({
|
||||
requestId: '11111111-1111-4111-8111-111111111111',
|
||||
entryIds: [1, 2],
|
||||
model: 'openai/a',
|
||||
isolate: true,
|
||||
...overrides,
|
||||
})
|
||||
}
|
||||
|
||||
describe('multi-run routes', () => {
|
||||
let service: {
|
||||
list: ReturnType<typeof vi.fn>
|
||||
launch: ReturnType<typeof vi.fn>
|
||||
discard: ReturnType<typeof vi.fn>
|
||||
fuse: ReturnType<typeof vi.fn>
|
||||
}
|
||||
let app: Hono
|
||||
|
||||
beforeEach(() => {
|
||||
service = { list: vi.fn(), launch: vi.fn(), discard: vi.fn() }
|
||||
service = { list: vi.fn(), launch: vi.fn(), discard: vi.fn(), fuse: vi.fn() }
|
||||
app = new Hono()
|
||||
app.route('/multi-runs', createMultiRunRoutes(service as unknown as MultiRunService))
|
||||
})
|
||||
@@ -147,4 +159,89 @@ describe('multi-run routes', () => {
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('POST fusions fuses a run and returns 201 when created', async () => {
|
||||
service.fuse.mockResolvedValue({ run: createRun(), created: true })
|
||||
|
||||
const res = await app.request('/multi-runs/3/fusions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: fuseBody(),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
await expect(res.json()).resolves.toEqual({ run: createRun() })
|
||||
expect(service.fuse).toHaveBeenCalledWith(3, {
|
||||
requestId: '11111111-1111-4111-8111-111111111111',
|
||||
entryIds: [1, 2],
|
||||
model: 'openai/a',
|
||||
isolate: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('POST fusions returns 200 for an idempotent replay', async () => {
|
||||
service.fuse.mockResolvedValue({ run: createRun(), created: false })
|
||||
|
||||
const res = await app.request('/multi-runs/3/fusions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: fuseBody(),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
await expect(res.json()).resolves.toEqual({ run: createRun() })
|
||||
})
|
||||
|
||||
it('POST fusions serialises an unavailable-sources error with code and details', async () => {
|
||||
service.fuse.mockRejectedValue(
|
||||
new MultiRunError('Some selected results are not ready to fuse', 409, {
|
||||
code: 'FUSION_SOURCES_UNAVAILABLE',
|
||||
details: {
|
||||
unavailableSources: [
|
||||
{ entryId: 2, model: 'openai/b', reason: 'running', message: 'The session is still running.' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await app.request('/multi-runs/3/fusions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: fuseBody(),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
await expect(res.json()).resolves.toEqual({
|
||||
error: 'Some selected results are not ready to fuse',
|
||||
code: 'FUSION_SOURCES_UNAVAILABLE',
|
||||
details: {
|
||||
unavailableSources: [
|
||||
{ entryId: 2, model: 'openai/b', reason: 'running', message: 'The session is still running.' },
|
||||
],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('POST fusions maps a missing run to 404', async () => {
|
||||
service.fuse.mockRejectedValue(new MultiRunError('Multi-run not found', 404))
|
||||
|
||||
const res = await app.request('/multi-runs/3/fusions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: fuseBody(),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('POST fusions rejects a body with fewer than two entries with 400', async () => {
|
||||
const res = await app.request('/multi-runs/3/fusions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: fuseBody({ entryIds: [1] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(service.fuse).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { spawn, spawnSync } from 'child_process'
|
||||
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
import { repoRoot } from '../helpers/repo-root'
|
||||
@@ -54,13 +54,16 @@ afterEach(() => {
|
||||
rmSync(workDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const runInstaller = (env: Record<string, string> = {}) =>
|
||||
const runInstaller = (
|
||||
env: Record<string, string> = {},
|
||||
path = `${stubDir}:/usr/bin:/bin`,
|
||||
) =>
|
||||
new Promise<{ status: number | null; stdout: string; stderr: string }>((resolve, reject) => {
|
||||
const child = spawn('sh', [installerPath], {
|
||||
const child = spawn('/bin/sh', [installerPath], {
|
||||
detached: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: {
|
||||
PATH: `${stubDir}:/usr/bin:/bin`,
|
||||
PATH: path,
|
||||
HOME: workDir,
|
||||
OCM_DIR: installDir,
|
||||
OCM_STUB_LOG: logPath,
|
||||
@@ -157,9 +160,11 @@ describe('install.sh', () => {
|
||||
})
|
||||
|
||||
it('stops before downloading anything when Docker is missing', async () => {
|
||||
rmSync(join(stubDir, 'docker'))
|
||||
const isolatedBin = join(workDir, 'isolated-bin')
|
||||
mkdirSync(isolatedBin)
|
||||
copyFileSync(join(stubDir, 'curl'), join(isolatedBin, 'curl'))
|
||||
|
||||
const res = await runInstaller()
|
||||
const res = await runInstaller({}, isolatedBin)
|
||||
|
||||
expect(res.status).toBe(1)
|
||||
expect(res.stderr).toContain('Docker is required')
|
||||
|
||||
@@ -0,0 +1,516 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import type { FileDiffInfo, SessionInfo, SessionMessageInfo } from '@opencode-manager/shared/opencode'
|
||||
import {
|
||||
WALKTHROUGH_DIFF_MAX_CHARS,
|
||||
WALKTHROUGH_HUNK_MAX_CHARS,
|
||||
WALKTHROUGH_MAX_STOPS,
|
||||
WALKTHROUGH_TEXT_MAX_CHARS,
|
||||
type WalkthroughHunk,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import {
|
||||
ChangeWalkthroughError,
|
||||
ChangeWalkthroughService,
|
||||
buildWalkthroughInput,
|
||||
buildWalkthroughPrompt,
|
||||
computeChangesHash,
|
||||
parseWalkthroughResponse,
|
||||
} from '../../src/services/change-walkthroughs'
|
||||
|
||||
const SESSION_ID = 'ses_walkthrough'
|
||||
|
||||
function userMessage(id: string): SessionMessageInfo {
|
||||
return { id, type: 'user', time: { created: 0 }, text: id } as SessionMessageInfo
|
||||
}
|
||||
|
||||
function change(file: string, patch: string, status: FileDiffInfo['status'] = 'modified'): FileDiffInfo {
|
||||
return { file, patch, additions: 1, deletions: 1, status }
|
||||
}
|
||||
|
||||
function hunkPatch(line: number): string {
|
||||
return `@@ -${line},2 +${line},2 @@\n-const a${line} = 1;\n+const a${line} = 2;`
|
||||
}
|
||||
|
||||
function bigHunk(index: number, size = WALKTHROUGH_HUNK_MAX_CHARS): string {
|
||||
return `@@ -${index},1 +${index},1 @@\n+${'x'.repeat(size)}`
|
||||
}
|
||||
|
||||
function modelReply(
|
||||
stops: Array<{ title: string; explanation: string; hunkIds: string[] }>,
|
||||
summary = 'Summary',
|
||||
): string {
|
||||
return JSON.stringify({ summary, stops })
|
||||
}
|
||||
|
||||
interface FakeSession {
|
||||
info?: SessionInfo | Error
|
||||
changes?: FileDiffInfo[] | Error
|
||||
}
|
||||
|
||||
function createFakeClient(sessions: Record<string, FakeSession>) {
|
||||
const generateCalls: string[] = []
|
||||
let generateImpl: () => Promise<string> = async () => modelReply([])
|
||||
|
||||
const client = {
|
||||
api: {
|
||||
session: {
|
||||
get: vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
const config = sessions[sessionID]
|
||||
if (!config) {
|
||||
throw Object.assign(new Error('Session not found'), { _tag: 'SessionNotFoundError' })
|
||||
}
|
||||
if (config.info instanceof Error) {
|
||||
throw config.info
|
||||
}
|
||||
return config.info ?? ({ id: sessionID, title: `Title ${sessionID}` } as SessionInfo)
|
||||
}),
|
||||
diff: vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
const config = sessions[sessionID]
|
||||
if (config?.changes instanceof Error) {
|
||||
throw config.changes
|
||||
}
|
||||
return config?.changes ?? []
|
||||
}),
|
||||
},
|
||||
message: {
|
||||
list: vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
if (!sessions[sessionID]) {
|
||||
return { data: [], cursor: {} }
|
||||
}
|
||||
return { data: [userMessage('msg-1')], cursor: {} }
|
||||
}),
|
||||
},
|
||||
generate: {
|
||||
text: vi.fn(async (input: { prompt: string }) => {
|
||||
generateCalls.push(input.prompt)
|
||||
return { text: await generateImpl() }
|
||||
}),
|
||||
},
|
||||
},
|
||||
forwardRaw: vi.fn(),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return {
|
||||
client,
|
||||
generateCalls,
|
||||
setGenerateImpl: (impl: () => Promise<string>) => {
|
||||
generateImpl = impl
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
}
|
||||
|
||||
describe('computeChangesHash', () => {
|
||||
it('is stable for identical changes', () => {
|
||||
const changes = [change('src/a.ts', hunkPatch(1))]
|
||||
expect(computeChangesHash(changes)).toBe(computeChangesHash(changes))
|
||||
})
|
||||
|
||||
it('changes when any field changes', () => {
|
||||
const base = change('src/a.ts', hunkPatch(1))
|
||||
expect(computeChangesHash([base])).not.toBe(computeChangesHash([change('src/a.ts', hunkPatch(2))]))
|
||||
expect(computeChangesHash([base])).not.toBe(computeChangesHash([change('src/b.ts', hunkPatch(1))]))
|
||||
expect(computeChangesHash([base])).not.toBe(
|
||||
computeChangesHash([change('src/a.ts', hunkPatch(1), 'added')]),
|
||||
)
|
||||
})
|
||||
|
||||
it('is order sensitive', () => {
|
||||
const a = change('src/a.ts', hunkPatch(1))
|
||||
const b = change('src/b.ts', hunkPatch(1))
|
||||
expect(computeChangesHash([a, b])).not.toBe(computeChangesHash([b, a]))
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildWalkthroughInput', () => {
|
||||
it('assigns file and hunk ordered ids', () => {
|
||||
const { hunks, omittedFiles } = buildWalkthroughInput(
|
||||
[
|
||||
change('src/a.ts', `${hunkPatch(1)}\n${hunkPatch(10)}`),
|
||||
change('src/b.ts', hunkPatch(1)),
|
||||
],
|
||||
'My session',
|
||||
)
|
||||
|
||||
expect(omittedFiles).toEqual([])
|
||||
expect(hunks.map((hunk) => hunk.id)).toEqual(['f0h0', 'f0h1', 'f1h0'])
|
||||
expect(hunks.map((hunk) => hunk.file)).toEqual(['src/a.ts', 'src/a.ts', 'src/b.ts'])
|
||||
})
|
||||
|
||||
it('omits files with no hunks as binary', () => {
|
||||
const { hunks, omittedFiles } = buildWalkthroughInput(
|
||||
[
|
||||
change('assets/logo.png', 'diff --git a/assets/logo.png b/assets/logo.png\nBinary files differ'),
|
||||
change('src/a.ts', hunkPatch(1)),
|
||||
],
|
||||
'My session',
|
||||
)
|
||||
|
||||
expect(hunks).toHaveLength(1)
|
||||
expect(omittedFiles).toEqual([{ file: 'assets/logo.png', reason: 'binary' }])
|
||||
})
|
||||
|
||||
it('truncates an oversized hunk and marks it', () => {
|
||||
const longLine = `+${'x'.repeat(WALKTHROUGH_HUNK_MAX_CHARS + 100)}`
|
||||
const { hunks } = buildWalkthroughInput([change('src/a.ts', `@@ -1 +1 @@\n${longLine}`)], 'My session')
|
||||
|
||||
expect(hunks[0]!.truncated).toBe(true)
|
||||
expect(hunks[0]!.text).toContain('[hunk truncated]')
|
||||
})
|
||||
|
||||
it('bounds the included hunks and omits the remaining files as budget', () => {
|
||||
const changes = Array.from({ length: 10 }, (_, index) => change(`src/f${index}.ts`, bigHunk(index)))
|
||||
const { hunks, omittedFiles } = buildWalkthroughInput(changes, 'My session')
|
||||
|
||||
const included = hunks.reduce((sum, hunk) => sum + hunk.text.length, 0)
|
||||
expect(included).toBeLessThanOrEqual(WALKTHROUGH_DIFF_MAX_CHARS)
|
||||
expect(omittedFiles.filter((file) => file.reason === 'budget').length).toBeGreaterThan(0)
|
||||
expect(omittedFiles.every((file) => file.reason === 'budget')).toBe(true)
|
||||
})
|
||||
|
||||
it('never half-includes a file', () => {
|
||||
const patch = Array.from({ length: 9 }, (_, index) => bigHunk(index)).join('\n')
|
||||
const { hunks, omittedFiles } = buildWalkthroughInput([change('src/a.ts', patch)], 'My session')
|
||||
|
||||
expect(hunks).toEqual([])
|
||||
expect(omittedFiles).toEqual([{ file: 'src/a.ts', reason: 'budget' }])
|
||||
})
|
||||
|
||||
it('keeps the prompt within budget for many small hunks behind a very long path', () => {
|
||||
const longPath = `src/${'p'.repeat(996)}.ts`
|
||||
const manyHunks = Array.from(
|
||||
{ length: 300 },
|
||||
(_, index) => `@@ -${index + 1} +${index + 1} @@\n+line${index}`,
|
||||
).join('\n')
|
||||
const changes = [change('src/small.ts', hunkPatch(1)), change(longPath, manyHunks)]
|
||||
|
||||
const { hunks, omittedFiles } = buildWalkthroughInput(changes, 'My session')
|
||||
const prompt = buildWalkthroughPrompt({ title: 'My session', hunks })
|
||||
|
||||
expect(hunks.length).toBeGreaterThan(0)
|
||||
expect(prompt.length).toBeLessThanOrEqual(WALKTHROUGH_DIFF_MAX_CHARS)
|
||||
expect(omittedFiles).toEqual([{ file: longPath, reason: 'budget' }])
|
||||
})
|
||||
|
||||
it('reserves the title in the budget so a long title admits less content', () => {
|
||||
const changes = Array.from({ length: 20 }, (_, index) => change(`src/f${index}.ts`, bigHunk(index)))
|
||||
const longTitle = 'T'.repeat(20_000)
|
||||
|
||||
const withLongTitle = buildWalkthroughInput(changes, longTitle)
|
||||
const withShortTitle = buildWalkthroughInput(changes, 'short')
|
||||
|
||||
expect(withLongTitle.hunks.length).toBeLessThan(withShortTitle.hunks.length)
|
||||
expect(
|
||||
buildWalkthroughPrompt({ title: longTitle, hunks: withLongTitle.hunks }).length,
|
||||
).toBeLessThanOrEqual(WALKTHROUGH_DIFF_MAX_CHARS)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildWalkthroughPrompt', () => {
|
||||
const hunks: WalkthroughHunk[] = [
|
||||
{
|
||||
id: 'f0h0',
|
||||
file: 'src/a.ts',
|
||||
status: 'modified',
|
||||
header: '@@ -1,2 +1,2 @@',
|
||||
text: hunkPatch(1),
|
||||
truncated: false,
|
||||
},
|
||||
]
|
||||
|
||||
it('lists every hunk with its id, file and status in a diff block', () => {
|
||||
const prompt = buildWalkthroughPrompt({ title: 'My session', hunks })
|
||||
|
||||
expect(prompt).toContain('### f0h0 src/a.ts (modified)')
|
||||
expect(prompt).toContain('```diff')
|
||||
expect(prompt).toContain(hunkPatch(1))
|
||||
expect(prompt).toContain('My session')
|
||||
})
|
||||
|
||||
it('states the stop limit and the response shape', () => {
|
||||
const prompt = buildWalkthroughPrompt({ title: 'My session', hunks })
|
||||
|
||||
expect(prompt).toContain(`at most ${WALKTHROUGH_MAX_STOPS} stops`)
|
||||
expect(prompt).toContain('"stops"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseWalkthroughResponse', () => {
|
||||
const hunks: WalkthroughHunk[] = ['f0h0', 'f0h1', 'f1h0'].map((id, index) => ({
|
||||
id,
|
||||
file: index === 2 ? 'src/b.ts' : 'src/a.ts',
|
||||
status: 'modified',
|
||||
header: '@@ -1,2 +1,2 @@',
|
||||
text: hunkPatch(index + 1),
|
||||
truncated: false,
|
||||
}))
|
||||
|
||||
it('drops unknown ids and repeat references, first occurrence wins', () => {
|
||||
const parsed = parseWalkthroughResponse(
|
||||
modelReply([
|
||||
{ title: 'A', explanation: 'first', hunkIds: ['f0h0', 'nope'] },
|
||||
{ title: 'B', explanation: 'second', hunkIds: ['f0h0', 'f0h1'] },
|
||||
]),
|
||||
hunks,
|
||||
)
|
||||
|
||||
expect(parsed?.stops.map((stop) => stop.hunkIds)).toEqual([['f0h0'], ['f0h1'], ['f1h0']])
|
||||
})
|
||||
|
||||
it('drops stops left empty', () => {
|
||||
const parsed = parseWalkthroughResponse(
|
||||
modelReply([
|
||||
{ title: 'A', explanation: 'first', hunkIds: ['nope'] },
|
||||
{ title: 'B', explanation: 'second', hunkIds: ['f0h0', 'f0h1', 'f1h0'] },
|
||||
]),
|
||||
hunks,
|
||||
)
|
||||
|
||||
expect(parsed?.stops.map((stop) => stop.title)).toEqual(['B'])
|
||||
})
|
||||
|
||||
it('appends unreferenced hunks as a final remaining stop', () => {
|
||||
const parsed = parseWalkthroughResponse(
|
||||
modelReply([{ title: 'A', explanation: 'first', hunkIds: ['f0h0'] }]),
|
||||
hunks,
|
||||
)
|
||||
|
||||
expect(parsed?.stops.at(-1)).toEqual({
|
||||
title: 'Remaining changes',
|
||||
explanation: 'These changes were not covered by the generated walkthrough.',
|
||||
hunkIds: ['f0h1', 'f1h0'],
|
||||
})
|
||||
})
|
||||
|
||||
it('does not append a remaining stop when every hunk is covered', () => {
|
||||
const parsed = parseWalkthroughResponse(
|
||||
modelReply([{ title: 'A', explanation: 'first', hunkIds: ['f0h0', 'f0h1', 'f1h0'] }]),
|
||||
hunks,
|
||||
)
|
||||
|
||||
expect(parsed?.stops).toHaveLength(1)
|
||||
expect(parsed?.stops[0]!.title).toBe('A')
|
||||
})
|
||||
|
||||
it('caps model stops and text lengths', () => {
|
||||
const manyHunks: WalkthroughHunk[] = Array.from(
|
||||
{ length: WALKTHROUGH_MAX_STOPS + 5 },
|
||||
(_, index) => ({
|
||||
id: `f0h${index}`,
|
||||
file: 'src/a.ts',
|
||||
status: 'modified',
|
||||
header: '@@ -1 +1 @@',
|
||||
text: hunkPatch(index),
|
||||
truncated: false,
|
||||
}),
|
||||
)
|
||||
const stops = manyHunks.map((hunk, index) => ({
|
||||
title: `Stop ${index}`,
|
||||
explanation: 'e'.repeat(WALKTHROUGH_TEXT_MAX_CHARS + 50),
|
||||
hunkIds: [hunk.id],
|
||||
}))
|
||||
const parsed = parseWalkthroughResponse(
|
||||
modelReply(stops, 's'.repeat(WALKTHROUGH_TEXT_MAX_CHARS + 50)),
|
||||
manyHunks,
|
||||
)
|
||||
|
||||
const modelStops = parsed!.stops.filter((stop) => stop.title !== 'Remaining changes')
|
||||
expect(modelStops).toHaveLength(WALKTHROUGH_MAX_STOPS)
|
||||
expect(parsed!.summary.length).toBeLessThanOrEqual(WALKTHROUGH_TEXT_MAX_CHARS)
|
||||
expect(modelStops[0]!.explanation.length).toBeLessThanOrEqual(WALKTHROUGH_TEXT_MAX_CHARS)
|
||||
})
|
||||
|
||||
it('returns null when the response is unparseable', () => {
|
||||
expect(parseWalkthroughResponse('not json at all', hunks)).toBeNull()
|
||||
expect(parseWalkthroughResponse('{not json', hunks)).toBeNull()
|
||||
expect(parseWalkthroughResponse('{"summary":"x"}', hunks)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when no model stop survives', () => {
|
||||
expect(parseWalkthroughResponse(modelReply([{ title: 'A', explanation: 'x', hunkIds: ['nope'] }]), hunks)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ChangeWalkthroughService', () => {
|
||||
let db: Database
|
||||
let sessions: Record<string, FakeSession>
|
||||
let fake: ReturnType<typeof createFakeClient>
|
||||
let service: ChangeWalkthroughService
|
||||
|
||||
const threeHunks: FileDiffInfo[] = [
|
||||
change('src/a.ts', `${hunkPatch(1)}\n${hunkPatch(10)}`),
|
||||
change('src/b.ts', hunkPatch(1)),
|
||||
]
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
sessions = { [SESSION_ID]: { changes: threeHunks } }
|
||||
fake = createFakeClient(sessions)
|
||||
service = new ChangeWalkthroughService(db, fake.client)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('throws 404 for a missing session on GET', async () => {
|
||||
await expect(service.getState('ses_missing')).rejects.toMatchObject({ status: 404 })
|
||||
})
|
||||
|
||||
it('reports no walkthrough and a current hash on GET', async () => {
|
||||
const state = await service.getState(SESSION_ID)
|
||||
|
||||
expect(state.walkthrough).toBeNull()
|
||||
expect(state.stale).toBe(false)
|
||||
expect(state.currentDiffHash).toBe(computeChangesHash(threeHunks))
|
||||
})
|
||||
|
||||
it('reports stale when the changes differ from the stored hash', async () => {
|
||||
fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: ['f0h0', 'f0h1', 'f1h0'] }]))
|
||||
await service.generate(SESSION_ID, {})
|
||||
|
||||
sessions[SESSION_ID]!.changes = [change('src/a.ts', hunkPatch(99))]
|
||||
|
||||
const state = await service.getState(SESSION_ID)
|
||||
expect(state.stale).toBe(true)
|
||||
expect(state.currentDiffHash).toBe(computeChangesHash([change('src/a.ts', hunkPatch(99))]))
|
||||
})
|
||||
|
||||
it('reports a null current hash when changes cannot be read', async () => {
|
||||
sessions[SESSION_ID]!.changes = new Error('diff failed')
|
||||
|
||||
const state = await service.getState(SESSION_ID)
|
||||
expect(state.currentDiffHash).toBeNull()
|
||||
expect(state.stale).toBe(false)
|
||||
})
|
||||
|
||||
it('stores stops covering every hunk exactly once', async () => {
|
||||
fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: ['f0h0', 'f1h0'] }]))
|
||||
|
||||
const { walkthrough, created } = await service.generate(SESSION_ID, {})
|
||||
|
||||
expect(created).toBe(true)
|
||||
const ids = walkthrough.stops.flatMap((stop) => stop.hunkIds)
|
||||
expect(new Set(ids).size).toBe(ids.length)
|
||||
expect(new Set(ids)).toEqual(new Set(['f0h0', 'f0h1', 'f1h0']))
|
||||
expect(walkthrough.stops.at(-1)!.title).toBe('Remaining changes')
|
||||
})
|
||||
|
||||
it('returns the stored walkthrough without a model call when changes are unchanged', async () => {
|
||||
fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: ['f0h0', 'f0h1', 'f1h0'] }]))
|
||||
const first = await service.generate(SESSION_ID, {})
|
||||
|
||||
const second = await service.generate(SESSION_ID, {})
|
||||
|
||||
expect(second.created).toBe(false)
|
||||
expect(second.walkthrough).toEqual(first.walkthrough)
|
||||
expect(fake.generateCalls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('calls the model again when regenerate is set', async () => {
|
||||
fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: ['f0h0', 'f0h1', 'f1h0'] }]))
|
||||
await service.generate(SESSION_ID, {})
|
||||
|
||||
await service.generate(SESSION_ID, { regenerate: true })
|
||||
|
||||
expect(fake.generateCalls).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('coalesces concurrent generation into one model call', async () => {
|
||||
let resolveGenerate: (text: string) => void = () => {}
|
||||
const gate = new Promise<string>((resolve) => {
|
||||
resolveGenerate = resolve
|
||||
})
|
||||
fake.setGenerateImpl(() => gate)
|
||||
|
||||
const first = service.generate(SESSION_ID, {})
|
||||
const second = service.generate(SESSION_ID, {})
|
||||
resolveGenerate(modelReply([{ title: 'A', explanation: 'x', hunkIds: ['f0h0', 'f0h1', 'f1h0'] }]))
|
||||
|
||||
const [firstResult, secondResult] = await Promise.all([first, second])
|
||||
expect(firstResult).toBe(secondResult)
|
||||
expect(fake.generateCalls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('rejects with 409 when the session has no changes', async () => {
|
||||
sessions[SESSION_ID]!.changes = []
|
||||
|
||||
await expect(service.generate(SESSION_ID, {})).rejects.toMatchObject({
|
||||
status: 409,
|
||||
code: 'WALKTHROUGH_NO_CHANGES',
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects with 409 when every change is binary', async () => {
|
||||
sessions[SESSION_ID]!.changes = [
|
||||
change('assets/logo.png', 'diff --git a/assets/logo.png b/assets/logo.png\nBinary files differ'),
|
||||
]
|
||||
|
||||
await expect(service.generate(SESSION_ID, {})).rejects.toMatchObject({
|
||||
status: 409,
|
||||
code: 'WALKTHROUGH_NO_TEXT_CHANGES',
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects with 413 and the omitted files when a text file exceeds the context budget', async () => {
|
||||
const file = 'src/huge.ts'
|
||||
const patch = Array.from({ length: 10 }, (_, index) => bigHunk(index)).join('\n')
|
||||
sessions[SESSION_ID]!.changes = [change(file, patch)]
|
||||
|
||||
await expect(service.generate(SESSION_ID, {})).rejects.toMatchObject({
|
||||
status: 413,
|
||||
code: 'WALKTHROUGH_CONTEXT_LIMIT',
|
||||
details: { omittedFiles: [{ file, reason: 'budget' }] },
|
||||
})
|
||||
expect(fake.generateCalls).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('rejects with 502 when the model response is unparseable', async () => {
|
||||
fake.setGenerateImpl(async () => 'not json')
|
||||
|
||||
await expect(service.generate(SESSION_ID, {})).rejects.toMatchObject({
|
||||
status: 502,
|
||||
code: 'WALKTHROUGH_UNPARSEABLE',
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects with 504 when generation times out', async () => {
|
||||
const timingOut = new ChangeWalkthroughService(db, fake.client, { timeoutMs: 5 })
|
||||
fake.setGenerateImpl(() => new Promise<string>(() => {}))
|
||||
|
||||
await expect(timingOut.generate(SESSION_ID, {})).rejects.toMatchObject({
|
||||
status: 504,
|
||||
code: 'WALKTHROUGH_TIMEOUT',
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects with 502 when the model call fails', async () => {
|
||||
fake.setGenerateImpl(async () => {
|
||||
throw new Error('model unavailable')
|
||||
})
|
||||
|
||||
await expect(service.generate(SESSION_ID, {})).rejects.toMatchObject({ status: 502 })
|
||||
})
|
||||
|
||||
it('rejects with 502 when reading changes fails', async () => {
|
||||
sessions[SESSION_ID]!.changes = new Error('diff failed')
|
||||
|
||||
await expect(service.generate(SESSION_ID, {})).rejects.toMatchObject({
|
||||
status: 502,
|
||||
code: 'WALKTHROUGH_CHANGES_UNAVAILABLE',
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects with 404 when generating for a missing session', async () => {
|
||||
await expect(service.generate('ses_missing', {})).rejects.toBeInstanceOf(ChangeWalkthroughError)
|
||||
await expect(service.generate('ses_missing', {})).rejects.toMatchObject({ status: 404 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,555 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
FileDiffInfo,
|
||||
SessionInfo,
|
||||
SessionMessageInfo,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { FUSION_PROMPT_MAX_LENGTH } from '@opencode-manager/shared/schemas'
|
||||
import type { MultiRunEntryRecord } from '../../src/db/multi-runs'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import {
|
||||
FUSION_MIN_SOURCE_CONTEXT,
|
||||
FusionContextLimitError,
|
||||
buildFusionPrompt,
|
||||
collectFusionSources,
|
||||
type CollectedFusionSource,
|
||||
} from '../../src/services/multi-run-fusion'
|
||||
import { SESSION_REPLY_TRUNCATION_MARKER } from '../../src/services/session-reply'
|
||||
import { assistantMessage } from '../helpers/stub-schedule-api'
|
||||
|
||||
function entry(overrides: Partial<MultiRunEntryRecord> = {}): MultiRunEntryRecord {
|
||||
return {
|
||||
id: 1,
|
||||
model: 'openai/gpt-5',
|
||||
status: 'started',
|
||||
sessionId: 'ses-1',
|
||||
directory: '/worktrees/run-1',
|
||||
isolated: true,
|
||||
error: null,
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function sessionInfo(overrides: Partial<SessionInfo> = {}): SessionInfo {
|
||||
return { id: 'ses-1', outcome: 'succeeded', ...overrides } as SessionInfo
|
||||
}
|
||||
|
||||
function userMessage(id: string): SessionMessageInfo {
|
||||
return { id, type: 'user', time: { created: 0 }, text: id } as SessionMessageInfo
|
||||
}
|
||||
|
||||
interface FakeSession {
|
||||
info?: SessionInfo | Error
|
||||
busy?: boolean
|
||||
activeError?: Error
|
||||
messages?: SessionMessageInfo[] | Error
|
||||
firstUser?: SessionMessageInfo
|
||||
lastUser?: SessionMessageInfo
|
||||
diff?: FileDiffInfo[] | Error
|
||||
}
|
||||
|
||||
function createFakeClient(sessions: Record<string, FakeSession>) {
|
||||
const sessionGet = vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
const config = sessions[sessionID]
|
||||
if (config?.info instanceof Error) {
|
||||
throw config.info
|
||||
}
|
||||
return config?.info ?? sessionInfo({ id: sessionID })
|
||||
})
|
||||
|
||||
const sessionActive = vi.fn(async () => {
|
||||
const active: Record<string, unknown> = {}
|
||||
for (const [id, config] of Object.entries(sessions)) {
|
||||
if (config.activeError) {
|
||||
throw config.activeError
|
||||
}
|
||||
if (config.busy) {
|
||||
active[id] = { type: 'running' }
|
||||
}
|
||||
}
|
||||
return active
|
||||
})
|
||||
|
||||
const messageList = vi.fn(async (input: { sessionID: string; type?: string; order?: 'asc' | 'desc' }) => {
|
||||
const config = sessions[input.sessionID]
|
||||
if (input.type === 'user') {
|
||||
const message = input.order === 'asc' ? config?.firstUser : config?.lastUser
|
||||
return { data: message ? [message] : [], cursor: {} }
|
||||
}
|
||||
if (config?.messages instanceof Error) {
|
||||
throw config.messages
|
||||
}
|
||||
return { data: config?.messages ?? [], cursor: {} }
|
||||
})
|
||||
|
||||
const sessionDiff = vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
const config = sessions[sessionID]
|
||||
if (config?.diff instanceof Error) {
|
||||
throw config.diff
|
||||
}
|
||||
return config?.diff ?? []
|
||||
})
|
||||
|
||||
const sessionPrompt = vi.fn(async () => ({}))
|
||||
const sessionCreate = vi.fn(async () => ({}))
|
||||
const sessionInterrupt = vi.fn(async () => ({}))
|
||||
|
||||
const client = {
|
||||
api: {
|
||||
session: {
|
||||
get: sessionGet,
|
||||
active: sessionActive,
|
||||
diff: sessionDiff,
|
||||
prompt: sessionPrompt,
|
||||
create: sessionCreate,
|
||||
interrupt: sessionInterrupt,
|
||||
},
|
||||
message: { list: messageList },
|
||||
},
|
||||
forwardRaw: vi.fn(),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return { client, sessionGet, sessionActive, messageList, sessionDiff, sessionPrompt, sessionCreate, sessionInterrupt }
|
||||
}
|
||||
|
||||
function notFoundError(): Error {
|
||||
return Object.assign(new Error('Session not found'), { _tag: 'SessionNotFoundError' })
|
||||
}
|
||||
|
||||
function fusionSource(overrides: Partial<CollectedFusionSource> = {}): CollectedFusionSource {
|
||||
return {
|
||||
entryId: 1,
|
||||
model: 'openai/gpt-5',
|
||||
sessionId: 'ses-1',
|
||||
directory: '/worktrees/run-1',
|
||||
outcome: 'succeeded',
|
||||
replyText: 'Final reply',
|
||||
changes: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function fileDiff(file: string, patch: string, overrides: Partial<FileDiffInfo> = {}): FileDiffInfo {
|
||||
return { file, patch, additions: 1, deletions: 1, status: 'modified', ...overrides }
|
||||
}
|
||||
|
||||
describe('collectFusionSources', () => {
|
||||
it('returns a completed idle session in ready with its reply, outcome and changes', async () => {
|
||||
const changes: FileDiffInfo[] = [
|
||||
{ file: 'src/a.ts', patch: '@@ -1 +1 @@', additions: 1, deletions: 1, status: 'modified' },
|
||||
]
|
||||
const { client, sessionDiff } = createFakeClient({
|
||||
'ses-1': {
|
||||
info: sessionInfo({ id: 'ses-1', outcome: 'succeeded' }),
|
||||
messages: [assistantMessage('Final answer', { completed: true })],
|
||||
firstUser: userMessage('msg-first'),
|
||||
lastUser: userMessage('msg-last'),
|
||||
diff: changes,
|
||||
},
|
||||
})
|
||||
|
||||
const result = await collectFusionSources(client, [entry()])
|
||||
|
||||
expect(result.unavailable).toEqual([])
|
||||
expect(result.ready).toEqual([
|
||||
{
|
||||
entryId: 1,
|
||||
model: 'openai/gpt-5',
|
||||
sessionId: 'ses-1',
|
||||
directory: '/worktrees/run-1',
|
||||
outcome: 'succeeded',
|
||||
replyText: 'Final answer',
|
||||
changes,
|
||||
},
|
||||
])
|
||||
expect(sessionDiff).toHaveBeenCalledWith({
|
||||
sessionID: 'ses-1',
|
||||
from: 'msg-first',
|
||||
to: 'msg-last',
|
||||
context: 3,
|
||||
})
|
||||
})
|
||||
|
||||
it('reports a null outcome for a session that never settled', async () => {
|
||||
const { client } = createFakeClient({
|
||||
'ses-1': {
|
||||
info: sessionInfo({ id: 'ses-1', outcome: undefined }),
|
||||
messages: [assistantMessage('Done', { completed: true })],
|
||||
diff: [],
|
||||
},
|
||||
})
|
||||
|
||||
const result = await collectFusionSources(client, [entry()])
|
||||
|
||||
expect(result.ready[0]?.outcome).toBeNull()
|
||||
})
|
||||
|
||||
it('classifies entries that have not started as not-started without reading them', async () => {
|
||||
const { client, sessionGet } = createFakeClient({})
|
||||
|
||||
const result = await collectFusionSources(client, [
|
||||
entry({ id: 1, status: 'failed', sessionId: null }),
|
||||
entry({ id: 2, status: 'discarded', sessionId: 'ses-2' }),
|
||||
])
|
||||
|
||||
expect(result.ready).toEqual([])
|
||||
expect(result.unavailable.map((source) => source.reason)).toEqual(['not-started', 'not-started'])
|
||||
expect(result.unavailable.map((source) => source.entryId)).toEqual([1, 2])
|
||||
expect(sessionGet).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('classifies a deleted session as missing', async () => {
|
||||
const { client } = createFakeClient({ 'ses-1': { info: notFoundError() } })
|
||||
|
||||
const result = await collectFusionSources(client, [entry()])
|
||||
|
||||
expect(result.ready).toEqual([])
|
||||
expect(result.unavailable).toEqual([
|
||||
{ entryId: 1, model: 'openai/gpt-5', reason: 'missing', message: expect.any(String) },
|
||||
])
|
||||
})
|
||||
|
||||
it('classifies a busy session as running without reading its reply', async () => {
|
||||
const { client, messageList } = createFakeClient({
|
||||
'ses-1': {
|
||||
info: sessionInfo({ id: 'ses-1' }),
|
||||
busy: true,
|
||||
messages: [assistantMessage('Still going', { completed: true })],
|
||||
},
|
||||
})
|
||||
|
||||
const result = await collectFusionSources(client, [entry()])
|
||||
|
||||
expect(result.unavailable).toEqual([
|
||||
{ entryId: 1, model: 'openai/gpt-5', reason: 'running', message: expect.any(String) },
|
||||
])
|
||||
expect(messageList).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('classifies a session without an assistant reply as incomplete', async () => {
|
||||
const { client } = createFakeClient({ 'ses-1': { info: sessionInfo({ id: 'ses-1' }), messages: [] } })
|
||||
|
||||
const result = await collectFusionSources(client, [entry()])
|
||||
|
||||
expect(result.unavailable).toEqual([
|
||||
{ entryId: 1, model: 'openai/gpt-5', reason: 'incomplete', message: expect.any(String) },
|
||||
])
|
||||
})
|
||||
|
||||
it('classifies an unfinished assistant reply as incomplete', async () => {
|
||||
const { client } = createFakeClient({
|
||||
'ses-1': {
|
||||
info: sessionInfo({ id: 'ses-1' }),
|
||||
messages: [assistantMessage('Partial output', { completed: false })],
|
||||
},
|
||||
})
|
||||
|
||||
const result = await collectFusionSources(client, [entry()])
|
||||
|
||||
expect(result.unavailable).toEqual([
|
||||
{ entryId: 1, model: 'openai/gpt-5', reason: 'incomplete', message: expect.any(String) },
|
||||
])
|
||||
})
|
||||
|
||||
it('classifies a failed session as failed and includes the error text', async () => {
|
||||
const { client } = createFakeClient({
|
||||
'ses-1': {
|
||||
info: sessionInfo({ id: 'ses-1', outcome: 'failed' }),
|
||||
messages: [assistantMessage('', { completed: true, error: 'Provider exploded' })],
|
||||
},
|
||||
})
|
||||
|
||||
const result = await collectFusionSources(client, [entry()])
|
||||
|
||||
expect(result.unavailable).toEqual([
|
||||
{
|
||||
entryId: 1,
|
||||
model: 'openai/gpt-5',
|
||||
reason: 'failed',
|
||||
message: expect.stringContaining('Provider exploded'),
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('classifies an interrupted session as failed', async () => {
|
||||
const { client } = createFakeClient({
|
||||
'ses-1': {
|
||||
info: sessionInfo({ id: 'ses-1', outcome: 'interrupted' }),
|
||||
messages: [assistantMessage('Stopped early', { completed: true })],
|
||||
},
|
||||
})
|
||||
|
||||
const result = await collectFusionSources(client, [entry()])
|
||||
|
||||
expect(result.unavailable).toEqual([
|
||||
{
|
||||
entryId: 1,
|
||||
model: 'openai/gpt-5',
|
||||
reason: 'failed',
|
||||
message: expect.stringContaining('interrupted'),
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('classifies a session read error as unavailable with the error message', async () => {
|
||||
const { client } = createFakeClient({ 'ses-1': { info: new Error('connection reset') } })
|
||||
|
||||
const result = await collectFusionSources(client, [entry()])
|
||||
|
||||
expect(result.unavailable).toEqual([
|
||||
{ entryId: 1, model: 'openai/gpt-5', reason: 'unavailable', message: 'connection reset' },
|
||||
])
|
||||
})
|
||||
|
||||
it('classifies a busy-check error as unavailable', async () => {
|
||||
const { client } = createFakeClient({
|
||||
'ses-1': { info: sessionInfo({ id: 'ses-1' }), activeError: new Error('active boom') },
|
||||
})
|
||||
|
||||
const result = await collectFusionSources(client, [entry()])
|
||||
|
||||
expect(result.unavailable).toEqual([
|
||||
{ entryId: 1, model: 'openai/gpt-5', reason: 'unavailable', message: 'active boom' },
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps a source ready with changes null when the diff read fails', async () => {
|
||||
const { client } = createFakeClient({
|
||||
'ses-1': {
|
||||
info: sessionInfo({ id: 'ses-1' }),
|
||||
messages: [assistantMessage('Done', { completed: true })],
|
||||
firstUser: userMessage('msg-first'),
|
||||
lastUser: userMessage('msg-last'),
|
||||
diff: new Error('turn range invalid'),
|
||||
},
|
||||
})
|
||||
|
||||
const result = await collectFusionSources(client, [entry()])
|
||||
|
||||
expect(result.unavailable).toEqual([])
|
||||
expect(result.ready).toEqual([
|
||||
expect.objectContaining({ entryId: 1, replyText: 'Done', changes: null }),
|
||||
])
|
||||
})
|
||||
|
||||
it('collects every entry concurrently and splits ready from unavailable', async () => {
|
||||
const { client } = createFakeClient({
|
||||
'ses-ready': {
|
||||
info: sessionInfo({ id: 'ses-ready' }),
|
||||
messages: [assistantMessage('Ready reply', { completed: true })],
|
||||
diff: [],
|
||||
},
|
||||
'ses-busy': { info: sessionInfo({ id: 'ses-busy' }), busy: true },
|
||||
})
|
||||
|
||||
const result = await collectFusionSources(client, [
|
||||
entry({ id: 1, model: 'openai/a', sessionId: 'ses-ready' }),
|
||||
entry({ id: 2, model: 'openai/b', sessionId: 'ses-busy' }),
|
||||
entry({ id: 3, model: 'openai/c', sessionId: null, status: 'starting' }),
|
||||
])
|
||||
|
||||
expect(result.ready.map((source) => source.entryId)).toEqual([1])
|
||||
expect(result.unavailable.map((source) => source.entryId)).toEqual([2, 3])
|
||||
expect(result.unavailable.map((source) => source.reason)).toEqual(['running', 'not-started'])
|
||||
})
|
||||
|
||||
it('reads the active-session map once for multiple started sources', async () => {
|
||||
const { client, sessionActive } = createFakeClient({
|
||||
'ses-a': {
|
||||
info: sessionInfo({ id: 'ses-a' }),
|
||||
messages: [assistantMessage('Reply A', { completed: true })],
|
||||
diff: [],
|
||||
},
|
||||
'ses-b': {
|
||||
info: sessionInfo({ id: 'ses-b' }),
|
||||
messages: [assistantMessage('Reply B', { completed: true })],
|
||||
diff: [],
|
||||
},
|
||||
})
|
||||
|
||||
const result = await collectFusionSources(client, [
|
||||
entry({ id: 1, model: 'openai/a', sessionId: 'ses-a' }),
|
||||
entry({ id: 2, model: 'openai/b', sessionId: 'ses-b' }),
|
||||
])
|
||||
|
||||
expect(result.ready.map((source) => source.entryId)).toEqual([1, 2])
|
||||
expect(sessionActive).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('classifies every started source as unavailable when the active-session read fails', async () => {
|
||||
const { client, sessionActive } = createFakeClient({
|
||||
'ses-a': { info: sessionInfo({ id: 'ses-a' }), activeError: new Error('active boom') },
|
||||
'ses-b': { info: sessionInfo({ id: 'ses-b' }), activeError: new Error('active boom') },
|
||||
})
|
||||
|
||||
const result = await collectFusionSources(client, [
|
||||
entry({ id: 1, model: 'openai/a', sessionId: 'ses-a' }),
|
||||
entry({ id: 2, model: 'openai/b', sessionId: 'ses-b' }),
|
||||
])
|
||||
|
||||
expect(result.ready).toEqual([])
|
||||
expect(result.unavailable).toEqual([
|
||||
{ entryId: 1, model: 'openai/a', reason: 'unavailable', message: 'active boom' },
|
||||
{ entryId: 2, model: 'openai/b', reason: 'unavailable', message: 'active boom' },
|
||||
])
|
||||
expect(sessionActive).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('only calls read endpoints and never writes to source sessions', async () => {
|
||||
const { client, sessionPrompt, sessionCreate, sessionInterrupt } = createFakeClient({
|
||||
'ses-1': {
|
||||
info: sessionInfo({ id: 'ses-1' }),
|
||||
messages: [assistantMessage('Done', { completed: true })],
|
||||
firstUser: userMessage('msg-first'),
|
||||
lastUser: userMessage('msg-last'),
|
||||
diff: [],
|
||||
},
|
||||
})
|
||||
|
||||
await collectFusionSources(client, [entry()])
|
||||
|
||||
expect(sessionPrompt).not.toHaveBeenCalled()
|
||||
expect(sessionCreate).not.toHaveBeenCalled()
|
||||
expect(sessionInterrupt).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildFusionPrompt', () => {
|
||||
it('includes the objective, instructions and every source with untruncated content', () => {
|
||||
const result = buildFusionPrompt({
|
||||
runName: 'Refactor auth',
|
||||
objective: 'Refactor the authentication flow.',
|
||||
instructions: 'Prefer the smallest possible change.',
|
||||
sources: [
|
||||
fusionSource({
|
||||
entryId: 1,
|
||||
model: 'openai/a',
|
||||
sessionId: 'ses-a',
|
||||
replyText: 'Reply from A',
|
||||
changes: [fileDiff('src/a.ts', '@@ -1 +1 @@\n-old\n+new')],
|
||||
}),
|
||||
fusionSource({
|
||||
entryId: 2,
|
||||
model: 'anthropic/b',
|
||||
sessionId: 'ses-b',
|
||||
replyText: 'Reply from B',
|
||||
changes: [fileDiff('src/b.ts', '@@ -2 +2 @@\n-x\n+y')],
|
||||
}),
|
||||
],
|
||||
})
|
||||
|
||||
expect(result.prompt).toContain('Refactor the authentication flow.')
|
||||
expect(result.prompt).toContain('Prefer the smallest possible change.')
|
||||
expect(result.prompt).toContain('## Source 1 — openai/a')
|
||||
expect(result.prompt).toContain('## Source 2 — anthropic/b')
|
||||
expect(result.prompt).toContain('ses-a')
|
||||
expect(result.prompt).toContain('ses-b')
|
||||
expect(result.prompt).toContain('Reply from A')
|
||||
expect(result.prompt).toContain('Reply from B')
|
||||
expect(result.prompt).toContain('@@ -1 +1 @@')
|
||||
expect(result.prompt).toContain('@@ -2 +2 @@')
|
||||
expect(result.prompt).toContain('src/a.ts (modified, +1/-1)')
|
||||
expect(result.prompt).not.toContain(SESSION_REPLY_TRUNCATION_MARKER)
|
||||
expect(result.prompt.length).toBeLessThanOrEqual(FUSION_PROMPT_MAX_LENGTH)
|
||||
expect(result.sources).toEqual([
|
||||
{ entryId: 1, sessionId: 'ses-a', model: 'openai/a', truncated: false },
|
||||
{ entryId: 2, sessionId: 'ses-b', model: 'anthropic/b', truncated: false },
|
||||
])
|
||||
})
|
||||
|
||||
it('omits the additional instructions section when none are given', () => {
|
||||
const result = buildFusionPrompt({
|
||||
runName: 'Run',
|
||||
objective: 'Objective.',
|
||||
sources: [
|
||||
fusionSource({ entryId: 1 }),
|
||||
fusionSource({ entryId: 2, model: 'openai/b', sessionId: 'ses-b' }),
|
||||
],
|
||||
})
|
||||
|
||||
expect(result.prompt).not.toContain('## Additional instructions')
|
||||
expect(result.prompt).toContain('## Rules')
|
||||
})
|
||||
|
||||
it('truncates oversized replies and diffs, flags the source and stays within the limit', () => {
|
||||
const result = buildFusionPrompt({
|
||||
runName: 'Large',
|
||||
objective: 'Synthesize the results.',
|
||||
sources: [
|
||||
fusionSource({
|
||||
entryId: 1,
|
||||
model: 'openai/a',
|
||||
sessionId: 'ses-a',
|
||||
replyText: 'r'.repeat(100_000),
|
||||
changes: [],
|
||||
}),
|
||||
fusionSource({
|
||||
entryId: 2,
|
||||
model: 'openai/b',
|
||||
sessionId: 'ses-b',
|
||||
replyText: 'short reply',
|
||||
changes: [fileDiff('src/b.ts', `@@ -1 +1 @@\n${'p'.repeat(200_000)}`)],
|
||||
}),
|
||||
fusionSource({ entryId: 3, model: 'openai/c', sessionId: 'ses-c', replyText: 'small reply', changes: [] }),
|
||||
],
|
||||
})
|
||||
|
||||
expect(result.sources).toEqual([
|
||||
{ entryId: 1, sessionId: 'ses-a', model: 'openai/a', truncated: true },
|
||||
{ entryId: 2, sessionId: 'ses-b', model: 'openai/b', truncated: true },
|
||||
{ entryId: 3, sessionId: 'ses-c', model: 'openai/c', truncated: false },
|
||||
])
|
||||
expect(result.prompt).toContain(SESSION_REPLY_TRUNCATION_MARKER)
|
||||
expect(result.prompt.length).toBeLessThanOrEqual(FUSION_PROMPT_MAX_LENGTH)
|
||||
})
|
||||
|
||||
it('renders a changes-could-not-be-read line when the diff is unavailable', () => {
|
||||
const result = buildFusionPrompt({
|
||||
runName: 'Run',
|
||||
objective: 'Objective.',
|
||||
sources: [
|
||||
fusionSource({ entryId: 1, changes: null }),
|
||||
fusionSource({ entryId: 2, model: 'openai/b', sessionId: 'ses-b' }),
|
||||
],
|
||||
})
|
||||
|
||||
expect(result.prompt).toContain('Changes could not be read.')
|
||||
expect(result.sources[0]?.truncated).toBe(false)
|
||||
})
|
||||
|
||||
it('returns only the preamble when there are no sources', () => {
|
||||
const result = buildFusionPrompt({ runName: 'Run', objective: 'Objective.', sources: [] })
|
||||
|
||||
expect(result.sources).toEqual([])
|
||||
expect(result.prompt).toContain('## Original objective')
|
||||
expect(result.prompt).not.toContain('## Source')
|
||||
})
|
||||
|
||||
it('throws FusionContextLimitError when the fixed sections leave too little room per source', () => {
|
||||
let error: unknown
|
||||
try {
|
||||
buildFusionPrompt({
|
||||
runName: 'Oversized',
|
||||
objective: 'o'.repeat(55_000),
|
||||
instructions: 'i'.repeat(4_000),
|
||||
sources: [
|
||||
fusionSource({ entryId: 1 }),
|
||||
fusionSource({ entryId: 2, model: 'openai/b', sessionId: 'ses-b' }),
|
||||
],
|
||||
})
|
||||
} catch (caught) {
|
||||
error = caught
|
||||
}
|
||||
|
||||
expect(error).toBeInstanceOf(FusionContextLimitError)
|
||||
const limitError = error as FusionContextLimitError
|
||||
expect(limitError.status).toBe(413)
|
||||
expect(limitError.code).toBe('FUSION_CONTEXT_LIMIT')
|
||||
expect(limitError.details).toEqual({
|
||||
requiredPerSource: FUSION_MIN_SOURCE_CONTEXT,
|
||||
availablePerSource: expect.any(Number),
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -4,11 +4,15 @@ import { createRepo, deleteRepo } from '../../src/db/queries'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { createMultiRunWithEntries } from '../../src/db/multi-runs'
|
||||
import { FusionContextLimitError } from '../../src/services/multi-run-fusion'
|
||||
import { MultiRunError, MultiRunService } from '../../src/services/multi-runs'
|
||||
import { RepoWorkspaceError } from '../../src/services/repo'
|
||||
import type { RepoWorkspaceService } from '../../src/services/repo-workspace'
|
||||
import type { Repo } from '../../src/types/repo'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { assistantMessage } from '../helpers/stub-schedule-api'
|
||||
|
||||
const FUSE_REQUEST_ID = '11111111-1111-4111-8111-111111111111'
|
||||
|
||||
const REPO_DIR = '/repos/repo-a'
|
||||
|
||||
@@ -38,13 +42,29 @@ vi.mock('../../src/utils/process', () => ({
|
||||
executeCommand: mocks.executeCommand,
|
||||
}))
|
||||
|
||||
interface FakeSessionConfig {
|
||||
busy?: boolean
|
||||
missing?: boolean
|
||||
reply?: string
|
||||
outcome?: 'succeeded' | 'failed' | 'interrupted'
|
||||
hasUserMessage?: boolean
|
||||
}
|
||||
|
||||
interface FakeMultiRunClient {
|
||||
client: OpenCodeClient
|
||||
sessionCreate: ReturnType<typeof vi.fn>
|
||||
sessionPrompt: ReturnType<typeof vi.fn>
|
||||
sessionGet: ReturnType<typeof vi.fn>
|
||||
sessionActive: ReturnType<typeof vi.fn>
|
||||
messageList: ReturnType<typeof vi.fn>
|
||||
sessionDiff: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
function createClient(): FakeMultiRunClient {
|
||||
function notFoundError(): Error {
|
||||
return Object.assign(new Error('Session not found'), { _tag: 'SessionNotFoundError' })
|
||||
}
|
||||
|
||||
function createClient(sessions: Record<string, FakeSessionConfig> = {}): FakeMultiRunClient {
|
||||
let sessionCounter = 0
|
||||
|
||||
const sessionCreate = vi.fn(async (input: { title?: string }) => {
|
||||
@@ -53,13 +73,56 @@ function createClient(): FakeMultiRunClient {
|
||||
})
|
||||
const sessionPrompt = vi.fn(async () => ({}))
|
||||
|
||||
const sessionGet = vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
const config = sessions[sessionID]
|
||||
if (config?.missing) {
|
||||
throw notFoundError()
|
||||
}
|
||||
return { id: sessionID, outcome: config?.outcome ?? 'succeeded' }
|
||||
})
|
||||
|
||||
const sessionActive = vi.fn(async () => {
|
||||
const active: Record<string, unknown> = {}
|
||||
for (const [id, config] of Object.entries(sessions)) {
|
||||
if (config.busy) {
|
||||
active[id] = { type: 'running' }
|
||||
}
|
||||
}
|
||||
return active
|
||||
})
|
||||
|
||||
const messageList = vi.fn(async (input: { sessionID: string; type?: string; order?: 'asc' | 'desc' }) => {
|
||||
if (input.type === 'user') {
|
||||
if (sessions[input.sessionID]?.hasUserMessage === false) {
|
||||
return { data: [], cursor: {} }
|
||||
}
|
||||
return {
|
||||
data: [{ id: `${input.sessionID}-user-${input.order}`, type: 'user', time: { created: 0 }, text: 'hi' }],
|
||||
cursor: {},
|
||||
}
|
||||
}
|
||||
return {
|
||||
data: [assistantMessage(sessions[input.sessionID]?.reply ?? 'Fusion source reply', { completed: true })],
|
||||
cursor: {},
|
||||
}
|
||||
})
|
||||
|
||||
const sessionDiff = vi.fn(async () => [])
|
||||
|
||||
const client = {
|
||||
api: {
|
||||
session: { create: sessionCreate, prompt: sessionPrompt },
|
||||
session: {
|
||||
create: sessionCreate,
|
||||
prompt: sessionPrompt,
|
||||
get: sessionGet,
|
||||
active: sessionActive,
|
||||
diff: sessionDiff,
|
||||
},
|
||||
message: { list: messageList },
|
||||
},
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return { client, sessionCreate, sessionPrompt }
|
||||
return { client, sessionCreate, sessionPrompt, sessionGet, sessionActive, messageList, sessionDiff }
|
||||
}
|
||||
|
||||
interface FakeRepoWorkspaces {
|
||||
@@ -405,6 +468,7 @@ describe('MultiRunService', () => {
|
||||
expect(entry.status).toBe('failed')
|
||||
expect(entry.directory).toBe('/worktrees/Sweep-1')
|
||||
expect(entry.error).toContain('prompt boom')
|
||||
expect(entry.sessionId).toBe('ses_1')
|
||||
|
||||
const discarded = await service.discard(run.id, entry.id)
|
||||
|
||||
@@ -516,6 +580,420 @@ describe('MultiRunService', () => {
|
||||
expect(runs.map((run) => run.name)).toEqual(['Second', 'First'])
|
||||
})
|
||||
|
||||
it('fuses completed entries into one new session and records the sources', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, sessionCreate, sessionPrompt } = createClient()
|
||||
const repoWorkspaces = createRepoWorkspaces()
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
|
||||
const run = await service.launch({
|
||||
repoId,
|
||||
name: 'Sweep',
|
||||
prompt: 'do the thing',
|
||||
models: ['openai/a', 'openai/b'],
|
||||
isolate: true,
|
||||
})
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
const sessionIds = run.entries.map((entry) => entry.sessionId)
|
||||
const before = run.entries.map((entry) => ({
|
||||
status: entry.status,
|
||||
sessionId: entry.sessionId,
|
||||
directory: entry.directory,
|
||||
}))
|
||||
sessionCreate.mockClear()
|
||||
sessionPrompt.mockClear()
|
||||
|
||||
const { run: fused, created } = await service.fuse(run.id, {
|
||||
requestId: FUSE_REQUEST_ID,
|
||||
entryIds,
|
||||
model: 'openai/c',
|
||||
isolate: true,
|
||||
baseRef: 'develop',
|
||||
})
|
||||
|
||||
expect(created).toBe(true)
|
||||
const fusion = fused.fusions[0]!
|
||||
expect(fusion.status).toBe('started')
|
||||
expect(fusion.model).toBe('openai/c')
|
||||
expect(fusion.sessionId).toBeTruthy()
|
||||
expect(fusion.directory).toBe('/worktrees/Sweep-fusion-1')
|
||||
expect(fusion.sources.map((source) => source.entryId)).toEqual(entryIds)
|
||||
expect(fusion.sources.map((source) => source.sessionId)).toEqual(sessionIds)
|
||||
expect(fusion.baseRef).toBe('develop')
|
||||
|
||||
const fusionWorkspaceCall = repoWorkspaces.create.mock.calls.find(
|
||||
(call) => call[1].name === 'Sweep-fusion-1',
|
||||
)
|
||||
expect(fusionWorkspaceCall?.[1].ref).toBe('develop')
|
||||
|
||||
const fusionPrompt = sessionPrompt.mock.calls.at(-1)![0].text
|
||||
expect(fusionPrompt).toContain('do the thing')
|
||||
expect(fusionPrompt).toContain('openai/a')
|
||||
expect(fusionPrompt).toContain('openai/b')
|
||||
expect(sessionCreate).toHaveBeenCalledTimes(1)
|
||||
|
||||
expect(
|
||||
fused.entries.map((entry) => ({
|
||||
status: entry.status,
|
||||
sessionId: entry.sessionId,
|
||||
directory: entry.directory,
|
||||
})),
|
||||
).toEqual(before)
|
||||
})
|
||||
|
||||
it('returns the same fusion for a repeated requestId and launches once', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, sessionCreate } = createClient()
|
||||
const repoWorkspaces = createRepoWorkspaces()
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
|
||||
const run = await service.launch({
|
||||
repoId,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a', 'openai/b'],
|
||||
isolate: true,
|
||||
})
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
sessionCreate.mockClear()
|
||||
|
||||
const request = { requestId: FUSE_REQUEST_ID, entryIds, model: 'openai/c', isolate: false }
|
||||
const first = await service.fuse(run.id, request)
|
||||
const second = await service.fuse(run.id, request)
|
||||
|
||||
expect(first.created).toBe(true)
|
||||
expect(second.created).toBe(false)
|
||||
expect(second.run.fusions).toHaveLength(1)
|
||||
expect(second.run.fusions[0]!.id).toBe(first.run.fusions[0]!.id)
|
||||
expect(second.run.fusions[0]!.sessionId).toBe(first.run.fusions[0]!.sessionId)
|
||||
expect(sessionCreate).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('rejects fusion when a selected result is still running', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, sessionCreate } = createClient({ ses_2: { busy: true } })
|
||||
const repoWorkspaces = createRepoWorkspaces()
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
|
||||
const run = await service.launch({
|
||||
repoId,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a', 'openai/b'],
|
||||
isolate: true,
|
||||
})
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
sessionCreate.mockClear()
|
||||
|
||||
const error = await service
|
||||
.fuse(run.id, { requestId: FUSE_REQUEST_ID, entryIds, model: 'openai/c', isolate: false })
|
||||
.catch((caught: unknown) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(MultiRunError)
|
||||
expect(error).toMatchObject({ status: 409, code: 'FUSION_SOURCES_UNAVAILABLE' })
|
||||
expect((error as MultiRunError).details).toEqual({
|
||||
unavailableSources: [expect.objectContaining({ reason: 'running' })],
|
||||
})
|
||||
expect(sessionCreate).not.toHaveBeenCalled()
|
||||
expect(service.list(repoId)[0]!.fusions).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects fusion when the prompt exceeds the context limit', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, sessionCreate } = createClient()
|
||||
const repoWorkspaces = createRepoWorkspaces()
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
|
||||
const run = await service.launch({
|
||||
repoId,
|
||||
name: 'Huge',
|
||||
prompt: 'o'.repeat(60_000),
|
||||
models: ['openai/a', 'openai/b'],
|
||||
isolate: true,
|
||||
})
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
sessionCreate.mockClear()
|
||||
|
||||
const error = await service
|
||||
.fuse(run.id, { requestId: FUSE_REQUEST_ID, entryIds, model: 'openai/c', isolate: false })
|
||||
.catch((caught: unknown) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(FusionContextLimitError)
|
||||
expect(error).toMatchObject({ status: 413, code: 'FUSION_CONTEXT_LIMIT' })
|
||||
expect(sessionCreate).not.toHaveBeenCalled()
|
||||
expect(service.list(repoId)[0]!.fusions).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects fusion with an unavailable synthesis model before creating a fusion', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, sessionCreate } = createClient()
|
||||
const repoWorkspaces = createRepoWorkspaces()
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
|
||||
const run = await service.launch({
|
||||
repoId,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a', 'openai/b'],
|
||||
isolate: true,
|
||||
})
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
sessionCreate.mockClear()
|
||||
|
||||
const error = await service
|
||||
.fuse(run.id, { requestId: FUSE_REQUEST_ID, entryIds, model: 'openai/retired', isolate: false })
|
||||
.catch((caught: unknown) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(MultiRunError)
|
||||
expect(error).toMatchObject({ status: 400 })
|
||||
expect((error as Error).message).toContain('not available')
|
||||
expect(sessionCreate).not.toHaveBeenCalled()
|
||||
expect(service.list(repoId)[0]!.fusions).toEqual([])
|
||||
})
|
||||
|
||||
it('records a failed fusion with the workspace directory when the launch fails', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, sessionCreate } = createClient()
|
||||
const repoWorkspaces = createRepoWorkspaces()
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
|
||||
const run = await service.launch({
|
||||
repoId,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a', 'openai/b'],
|
||||
isolate: false,
|
||||
})
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
sessionCreate.mockClear()
|
||||
sessionCreate.mockRejectedValueOnce(new Error('fusion boom'))
|
||||
|
||||
const { run: fused, created } = await service.fuse(run.id, {
|
||||
requestId: FUSE_REQUEST_ID,
|
||||
entryIds,
|
||||
model: 'openai/c',
|
||||
isolate: true,
|
||||
})
|
||||
|
||||
expect(created).toBe(true)
|
||||
const fusion = fused.fusions[0]!
|
||||
expect(fusion.status).toBe('failed')
|
||||
expect(fusion.error).toContain('fusion boom')
|
||||
expect(fusion.directory).toBe('/worktrees/Sweep-fusion-1')
|
||||
})
|
||||
|
||||
it('records the created session id on a failed fusion when the prompt is rejected', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, sessionCreate, sessionPrompt } = createClient()
|
||||
const repoWorkspaces = createRepoWorkspaces()
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
|
||||
const run = await service.launch({
|
||||
repoId,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a', 'openai/b'],
|
||||
isolate: true,
|
||||
})
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
sessionCreate.mockClear()
|
||||
sessionPrompt.mockRejectedValueOnce(new Error('prompt boom'))
|
||||
|
||||
const { run: fused, created } = await service.fuse(run.id, {
|
||||
requestId: FUSE_REQUEST_ID,
|
||||
entryIds,
|
||||
model: 'openai/c',
|
||||
isolate: false,
|
||||
})
|
||||
|
||||
expect(created).toBe(true)
|
||||
const fusion = fused.fusions[0]!
|
||||
expect(fusion.status).toBe('failed')
|
||||
expect(fusion.error).toContain('prompt boom')
|
||||
expect(fusion.sessionId).toBe('ses_3')
|
||||
expect(sessionCreate).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('recovers an uncertain fusion when the session already admitted the prompt', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, sessionCreate, sessionPrompt } = createClient()
|
||||
const repoWorkspaces = createRepoWorkspaces()
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
|
||||
const run = await service.launch({
|
||||
repoId,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a', 'openai/b'],
|
||||
isolate: true,
|
||||
})
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
sessionPrompt.mockRejectedValueOnce(new Error('prompt boom'))
|
||||
|
||||
const { run: firstFused } = await service.fuse(run.id, {
|
||||
requestId: FUSE_REQUEST_ID,
|
||||
entryIds,
|
||||
model: 'openai/c',
|
||||
isolate: false,
|
||||
})
|
||||
const failedFusion = firstFused.fusions[0]!
|
||||
expect(failedFusion.status).toBe('failed')
|
||||
expect(failedFusion.sessionId).toBe('ses_3')
|
||||
|
||||
sessionCreate.mockClear()
|
||||
|
||||
const error = await service
|
||||
.fuse(run.id, {
|
||||
requestId: '22222222-2222-4222-8222-222222222222',
|
||||
entryIds,
|
||||
model: 'openai/c',
|
||||
isolate: false,
|
||||
})
|
||||
.catch((caught: unknown) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(MultiRunError)
|
||||
expect(error).toMatchObject({ status: 409, code: 'FUSION_ATTEMPT_RECOVERED' })
|
||||
expect((error as MultiRunError).details).toEqual({
|
||||
fusions: [{ fusionId: failedFusion.id, sessionId: 'ses_3' }],
|
||||
})
|
||||
expect(sessionCreate).not.toHaveBeenCalled()
|
||||
|
||||
const recovered = service.list(repoId)[0]!.fusions[0]!
|
||||
expect(recovered.status).toBe('started')
|
||||
expect(recovered.error).toBeNull()
|
||||
})
|
||||
|
||||
it('proceeds with a new fusion when the failed attempt never admitted the prompt', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, sessionCreate, sessionPrompt } = createClient({ ses_3: { hasUserMessage: false } })
|
||||
const repoWorkspaces = createRepoWorkspaces()
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
|
||||
const run = await service.launch({
|
||||
repoId,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a', 'openai/b'],
|
||||
isolate: true,
|
||||
})
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
sessionPrompt.mockRejectedValueOnce(new Error('prompt boom'))
|
||||
|
||||
const { run: firstFused } = await service.fuse(run.id, {
|
||||
requestId: FUSE_REQUEST_ID,
|
||||
entryIds,
|
||||
model: 'openai/c',
|
||||
isolate: false,
|
||||
})
|
||||
expect(firstFused.fusions[0]!.status).toBe('failed')
|
||||
|
||||
sessionCreate.mockClear()
|
||||
|
||||
const { run: fused, created } = await service.fuse(run.id, {
|
||||
requestId: '33333333-3333-4333-8333-333333333333',
|
||||
entryIds,
|
||||
model: 'openai/c',
|
||||
isolate: false,
|
||||
})
|
||||
|
||||
expect(created).toBe(true)
|
||||
expect(sessionCreate).toHaveBeenCalledTimes(1)
|
||||
expect(fused.fusions.map((fusion) => fusion.status)).toEqual(['failed', 'started'])
|
||||
})
|
||||
|
||||
it('rejects a non-isolated fusion when a selected result ran in the repository checkout', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, sessionCreate } = createClient()
|
||||
const repoWorkspaces = createRepoWorkspaces()
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
|
||||
const run = await service.launch({
|
||||
repoId,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a', 'openai/b'],
|
||||
isolate: false,
|
||||
})
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
sessionCreate.mockClear()
|
||||
|
||||
const error = await service
|
||||
.fuse(run.id, {
|
||||
requestId: FUSE_REQUEST_ID,
|
||||
entryIds,
|
||||
model: 'openai/c',
|
||||
isolate: false,
|
||||
})
|
||||
.catch((caught: unknown) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(MultiRunError)
|
||||
expect(error).toMatchObject({ status: 409, code: 'FUSION_DESTINATION_OVERLAPS_SOURCE' })
|
||||
expect((error as MultiRunError).details).toEqual({ entryIds })
|
||||
expect(sessionCreate).not.toHaveBeenCalled()
|
||||
expect(service.list(repoId)[0]!.fusions).toEqual([])
|
||||
})
|
||||
|
||||
it('allows an isolated fusion when the selected results ran in the repository checkout', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, sessionCreate } = createClient()
|
||||
const repoWorkspaces = createRepoWorkspaces()
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
|
||||
const run = await service.launch({
|
||||
repoId,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a', 'openai/b'],
|
||||
isolate: false,
|
||||
})
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
sessionCreate.mockClear()
|
||||
|
||||
const { run: fused, created } = await service.fuse(run.id, {
|
||||
requestId: FUSE_REQUEST_ID,
|
||||
entryIds,
|
||||
model: 'openai/c',
|
||||
isolate: true,
|
||||
})
|
||||
|
||||
expect(created).toBe(true)
|
||||
expect(fused.fusions[0]!.status).toBe('started')
|
||||
expect(fused.fusions[0]!.directory).toBe('/worktrees/Sweep-fusion-1')
|
||||
expect(sessionCreate).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('rejects fusion with an entry id that does not belong to the run', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, sessionCreate } = createClient()
|
||||
const repoWorkspaces = createRepoWorkspaces()
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
|
||||
const run = await service.launch({
|
||||
repoId,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a', 'openai/b'],
|
||||
isolate: false,
|
||||
})
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
sessionCreate.mockClear()
|
||||
|
||||
const error = await service
|
||||
.fuse(run.id, {
|
||||
requestId: FUSE_REQUEST_ID,
|
||||
entryIds: [entryIds[0]!, 9999],
|
||||
model: 'openai/c',
|
||||
isolate: false,
|
||||
})
|
||||
.catch((caught: unknown) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(MultiRunError)
|
||||
expect(error).toMatchObject({ status: 400 })
|
||||
expect((error as Error).message).toBe('Unknown multi-run entry 9999')
|
||||
expect(sessionCreate).not.toHaveBeenCalled()
|
||||
expect(service.list(repoId)[0]!.fusions).toEqual([])
|
||||
})
|
||||
|
||||
it('persists the group and its entries in one transaction', () => {
|
||||
const repoId = readyRepo()
|
||||
db.run(`CREATE TRIGGER fail_entry BEFORE INSERT ON multi_run_entries BEGIN SELECT RAISE(ABORT, 'nope'); END`)
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import type { ModelRef } from '@opencode-manager/shared/opencode'
|
||||
import type { OpenCodeClient } from '../../../src/services/opencode/client'
|
||||
import { GenerateTextTimeoutError, generateTextWithTimeout } from '../../../src/services/opencode/generate-text'
|
||||
|
||||
interface GenerateCall {
|
||||
input: { prompt: string; model?: ModelRef }
|
||||
signal: AbortSignal | undefined
|
||||
}
|
||||
|
||||
function makeClient(impl: (call: GenerateCall) => Promise<{ text: string }>): {
|
||||
client: OpenCodeClient
|
||||
calls: GenerateCall[]
|
||||
} {
|
||||
const calls: GenerateCall[] = []
|
||||
const client = {
|
||||
api: {
|
||||
generate: {
|
||||
text: async (input: GenerateCall['input'], options?: { signal?: AbortSignal }) => {
|
||||
const call: GenerateCall = { input, signal: options?.signal }
|
||||
calls.push(call)
|
||||
return impl(call)
|
||||
},
|
||||
},
|
||||
},
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return { client, calls }
|
||||
}
|
||||
|
||||
describe('generateTextWithTimeout', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('returns the generated text and passes the prompt with an abort signal', async () => {
|
||||
const { client, calls } = makeClient(async () => ({ text: 'hello' }))
|
||||
|
||||
await expect(generateTextWithTimeout(client, { prompt: 'write' }, 1000)).resolves.toBe('hello')
|
||||
|
||||
expect(calls).toHaveLength(1)
|
||||
expect(calls[0]?.input).toEqual({ prompt: 'write' })
|
||||
expect(calls[0]?.signal).toBeInstanceOf(AbortSignal)
|
||||
})
|
||||
|
||||
it('forwards the model when provided', async () => {
|
||||
const { client, calls } = makeClient(async () => ({ text: 'hello' }))
|
||||
const model: ModelRef = { providerID: 'anthropic', id: 'claude-sonnet-4' }
|
||||
|
||||
await generateTextWithTimeout(client, { prompt: 'write', model }, 1000)
|
||||
|
||||
expect(calls[0]?.input).toEqual({ prompt: 'write', model })
|
||||
})
|
||||
|
||||
it('rejects with GenerateTextTimeoutError and aborts the request after the timeout', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { client, calls } = makeClient(() => new Promise<never>(() => {}))
|
||||
|
||||
const promise = generateTextWithTimeout(client, { prompt: 'slow' }, 50)
|
||||
const assertion = expect(promise).rejects.toBeInstanceOf(GenerateTextTimeoutError)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50)
|
||||
await assertion
|
||||
|
||||
expect(calls[0]?.signal?.aborted).toBe(true)
|
||||
})
|
||||
|
||||
it('propagates a client error without waiting for the timeout', async () => {
|
||||
const { client } = makeClient(async () => {
|
||||
throw new Error('model unavailable')
|
||||
})
|
||||
|
||||
await expect(generateTextWithTimeout(client, { prompt: 'write' }, 1000)).rejects.toThrow('model unavailable')
|
||||
})
|
||||
|
||||
it('clears the timeout once the client resolves', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { client, calls } = makeClient(async () => ({ text: 'done' }))
|
||||
|
||||
await expect(generateTextWithTimeout(client, { prompt: 'write' }, 50)).resolves.toBe('done')
|
||||
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
|
||||
expect(calls[0]?.signal?.aborted).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { FileDiffInfo, SessionMessageInfo } from '@opencode-manager/shared/opencode'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { readSessionChanges } from '../../src/services/session-changes'
|
||||
|
||||
function userMessage(id: string): SessionMessageInfo {
|
||||
return { id, type: 'user', time: { created: 0 }, text: id } as SessionMessageInfo
|
||||
}
|
||||
|
||||
interface FakeClientOptions {
|
||||
asc?: SessionMessageInfo[]
|
||||
desc?: SessionMessageInfo[]
|
||||
diff?: FileDiffInfo[] | Error
|
||||
}
|
||||
|
||||
function createFakeClient(options: FakeClientOptions = {}) {
|
||||
const list = vi.fn(async (input: { order?: 'asc' | 'desc' }) => ({
|
||||
data: input.order === 'asc' ? (options.asc ?? []) : (options.desc ?? []),
|
||||
cursor: {},
|
||||
}))
|
||||
const diff = vi.fn(async () => {
|
||||
if (options.diff instanceof Error) {
|
||||
throw options.diff
|
||||
}
|
||||
return options.diff ?? []
|
||||
})
|
||||
|
||||
const client = {
|
||||
api: { message: { list }, session: { diff } },
|
||||
forwardRaw: vi.fn(),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return { client, list, diff }
|
||||
}
|
||||
|
||||
describe('readSessionChanges', () => {
|
||||
it('diffs from the first to the last user message with the context window', async () => {
|
||||
const changes: FileDiffInfo[] = [
|
||||
{ file: 'src/a.ts', patch: '@@ -1 +1 @@', additions: 1, deletions: 1, status: 'modified' },
|
||||
]
|
||||
const { client, diff } = createFakeClient({
|
||||
asc: [userMessage('msg-first')],
|
||||
desc: [userMessage('msg-last')],
|
||||
diff: changes,
|
||||
})
|
||||
|
||||
await expect(readSessionChanges(client, 'ses-1')).resolves.toEqual(changes)
|
||||
expect(diff).toHaveBeenCalledWith({
|
||||
sessionID: 'ses-1',
|
||||
from: 'msg-first',
|
||||
to: 'msg-last',
|
||||
context: 3,
|
||||
})
|
||||
})
|
||||
|
||||
it('looks up the first and last user messages with limit one in both orders', async () => {
|
||||
const { client, list } = createFakeClient({
|
||||
asc: [userMessage('msg-first')],
|
||||
desc: [userMessage('msg-last')],
|
||||
})
|
||||
|
||||
await readSessionChanges(client, 'ses-1')
|
||||
|
||||
expect(list).toHaveBeenCalledWith({ sessionID: 'ses-1', type: 'user', order: 'asc', limit: 1 })
|
||||
expect(list).toHaveBeenCalledWith({ sessionID: 'ses-1', type: 'user', order: 'desc', limit: 1 })
|
||||
})
|
||||
|
||||
it('returns an empty list without diffing when the session has no user messages', async () => {
|
||||
const { client, diff } = createFakeClient({ asc: [], desc: [] })
|
||||
|
||||
await expect(readSessionChanges(client, 'ses-1')).resolves.toEqual([])
|
||||
expect(diff).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns an empty list without diffing when only the last lookup is empty', async () => {
|
||||
const { client, diff } = createFakeClient({ asc: [userMessage('msg-first')], desc: [] })
|
||||
|
||||
await expect(readSessionChanges(client, 'ses-1')).resolves.toEqual([])
|
||||
expect(diff).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('propagates OpenCode diff errors unchanged', async () => {
|
||||
const error = Object.assign(new Error('turn range invalid'), { _tag: 'TurnRangeError' })
|
||||
const { client } = createFakeClient({
|
||||
asc: [userMessage('msg-first')],
|
||||
desc: [userMessage('msg-last')],
|
||||
diff: error,
|
||||
})
|
||||
|
||||
await expect(readSessionChanges(client, 'ses-1')).rejects.toBe(error)
|
||||
})
|
||||
})
|
||||
@@ -23,12 +23,15 @@ interface FakeLaunchClient {
|
||||
prompt: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
function createClient(overrides: { createError?: Error } = {}): FakeLaunchClient {
|
||||
function createClient(overrides: { createError?: Error; promptError?: Error } = {}): FakeLaunchClient {
|
||||
const create = vi.fn(async (input: { title?: string }) => {
|
||||
if (overrides.createError) throw overrides.createError
|
||||
return { id: 'ses_new', title: input?.title }
|
||||
})
|
||||
const prompt = vi.fn(async () => ({}))
|
||||
const prompt = vi.fn(async () => {
|
||||
if (overrides.promptError) throw overrides.promptError
|
||||
return {}
|
||||
})
|
||||
|
||||
const client = {
|
||||
api: {
|
||||
@@ -206,10 +209,31 @@ describe('SessionLauncher', () => {
|
||||
status: 502,
|
||||
message: 'boom (workspace: /worktrees/feature-x)',
|
||||
workspaceDirectory: '/worktrees/feature-x',
|
||||
sessionId: null,
|
||||
})
|
||||
expect(createWorkspace).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the created session id when prompting the session fails', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client, create } = createClient({ promptError: new Error('prompt boom') })
|
||||
const { service } = createRepoWorkspaces({ directory: '/worktrees/feature-x' })
|
||||
const launcher = new SessionLauncher(db, client, service)
|
||||
|
||||
const error = await launcher.launch({ repoId, prompt: 'hello', workspace: { name: 'feature-x' } }).catch(
|
||||
(caught: unknown) => caught,
|
||||
)
|
||||
|
||||
expect(create).toHaveBeenCalled()
|
||||
expect(error).toBeInstanceOf(SessionLaunchError)
|
||||
expect(error).toMatchObject({
|
||||
status: 502,
|
||||
message: 'prompt boom (workspace: /worktrees/feature-x)',
|
||||
workspaceDirectory: '/worktrees/feature-x',
|
||||
sessionId: 'ses_new',
|
||||
})
|
||||
})
|
||||
|
||||
it('exposes no workspace when workspace creation fails', async () => {
|
||||
const repoId = readyRepo()
|
||||
const { client } = createClient()
|
||||
|
||||
@@ -5,10 +5,12 @@ import {
|
||||
SESSION_REPLY_MAX_LENGTH,
|
||||
getLatestAssistantReplyState,
|
||||
isSessionBusy,
|
||||
isSessionBusyIn,
|
||||
readLatestAssistantReply,
|
||||
sessionSettleSignal,
|
||||
truncateSessionReply,
|
||||
waitForSessionSettled,
|
||||
type ActiveSessions,
|
||||
} from '../../src/services/session-reply'
|
||||
import { assistantMessage } from '../helpers/stub-schedule-api'
|
||||
|
||||
@@ -114,6 +116,16 @@ describe('isSessionBusy', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('isSessionBusyIn', () => {
|
||||
it('is true when the session appears in the fetched active set', () => {
|
||||
expect(isSessionBusyIn({ 'ses-1': { type: 'running' } } as unknown as ActiveSessions, 'ses-1')).toBe(true)
|
||||
})
|
||||
|
||||
it('is false when the session is absent from the fetched active set', () => {
|
||||
expect(isSessionBusyIn({} as unknown as ActiveSessions, 'ses-1')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('truncateSessionReply', () => {
|
||||
it('returns short replies unchanged', () => {
|
||||
expect(truncateSessionReply('short reply')).toBe('short reply')
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { extractFirstJsonObject } from '../../src/utils/json-extract'
|
||||
|
||||
describe('extractFirstJsonObject', () => {
|
||||
it('returns a plain JSON object', () => {
|
||||
expect(extractFirstJsonObject('{"a":1}')).toBe('{"a":1}')
|
||||
})
|
||||
|
||||
it('returns the first object when several are present', () => {
|
||||
expect(extractFirstJsonObject('prefix {"a":1} middle {"b":2} suffix')).toBe('{"a":1}')
|
||||
})
|
||||
|
||||
it('ignores prose before and after the object', () => {
|
||||
expect(extractFirstJsonObject('Here you go:\n{"a":1}\nThanks')).toBe('{"a":1}')
|
||||
})
|
||||
|
||||
it('matches nested braces', () => {
|
||||
expect(extractFirstJsonObject('{"a":{"b":{"c":1}},"d":2}')).toBe('{"a":{"b":{"c":1}},"d":2}')
|
||||
})
|
||||
|
||||
it('ignores braces inside strings', () => {
|
||||
expect(extractFirstJsonObject('{"a":"}{","b":1}')).toBe('{"a":"}{","b":1}')
|
||||
})
|
||||
|
||||
it('handles escaped quotes inside strings', () => {
|
||||
expect(extractFirstJsonObject('{"a":"a \\" b","c":2}')).toBe('{"a":"a \\" b","c":2}')
|
||||
})
|
||||
|
||||
it('returns null when there is no object', () => {
|
||||
expect(extractFirstJsonObject('no object here')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for an unterminated object', () => {
|
||||
expect(extractFirstJsonObject('{"a":1')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when a string is left open', () => {
|
||||
expect(extractFirstJsonObject('{"a":"unterminated}')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { truncateText } from '../../src/utils/text-truncate'
|
||||
|
||||
describe('truncateText', () => {
|
||||
it('returns text unchanged when it is within the limit', () => {
|
||||
expect(truncateText('hello', 10, '[cut]')).toEqual({ text: 'hello', truncated: false })
|
||||
})
|
||||
|
||||
it('returns text unchanged when it is exactly at the limit', () => {
|
||||
expect(truncateText('hello', 5, '[cut]')).toEqual({ text: 'hello', truncated: false })
|
||||
})
|
||||
|
||||
it('slices to the limit, appends the marker and reports truncation', () => {
|
||||
expect(truncateText('hello world', 5, '…')).toEqual({ text: 'hello…', truncated: true })
|
||||
})
|
||||
|
||||
it('supports a zero limit', () => {
|
||||
expect(truncateText('hello', 0, '[cut]')).toEqual({ text: '[cut]', truncated: true })
|
||||
})
|
||||
|
||||
it('leaves empty text untouched', () => {
|
||||
expect(truncateText('', 5, '[cut]')).toEqual({ text: '', truncated: false })
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user