The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(agent): the run survives what used to kill it
purple63b48dcfee3b
diff --git a/src/api/__tests__/orphan-sweep.test.ts b/src/api/__tests__/orphan-sweep.test.tsnew file mode 100644index 00000000..588a7e19--- /dev/null+++ b/src/api/__tests__/orphan-sweep.test.ts@@ -0,0 +1,110 @@+/**+ * A dead LU session must not keep the GPU burning (G19-3, R32/G18 witness+ * 2026-08-07: a killed app left its ComfyUI render running and queued four+ * deep; nothing anywhere owned or showed it). Every LU submission now carries+ * an `lu-` client id, and each handoff sweeps jobs wearing that prefix under a+ * DIFFERENT id than the live session's before submitting its own.+ *+ * Run: npx vitest run src/api/__tests__/orphan-sweep.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++const calls: { url: string; init?: any }[] = []+let queueFixture: any = {}++vi.mock('../backend', () => ({+ comfyuiUrl: (p: string) => p,+ localFetch: vi.fn(async (url: string, init?: any) => {+ calls.push({ url, init })+ if (url === '/queue' && (!init || !init.method)) {+ return { ok: true, json: async () => queueFixture }+ }+ return { ok: true, json: async () => ({}), text: async () => '' }+ }),+ fetchLocalhostBytes: vi.fn(),+ isTauri: () => false,+ backendCall: vi.fn(),+ comfyuiWsUrl: () => 'ws://x',+}))++import { sweepOrphanedLuJobs } from '../comfyui'+import { CLIENT_ID, LU_CLIENT_PREFIX } from '../comfyui-ws'++const entry = (id: string, owner?: string) => [0, id, {}, owner ? { client_id: owner } : {}, []]++beforeEach(() => {+ calls.length = 0+ queueFixture = { queue_running: [], queue_pending: [] }+})++describe('sweepOrphanedLuJobs', () => {+ it('deletes a dead session\'s pending jobs and interrupts its running one', async () => {+ queueFixture = {+ queue_running: [entry('run1', 'lu-dead-session')],+ queue_pending: [entry('pen1', 'lu-dead-session'), entry('pen2', 'lu-dead-session')],+ }+ const cleaned = await sweepOrphanedLuJobs(CLIENT_ID)+ expect(cleaned).toBe(3)+ const del = calls.find((c) => c.url === '/queue' && c.init?.method === 'POST')+ expect(JSON.parse(del!.init.body)).toEqual({ delete: ['pen1', 'pen2'] })+ expect(calls.some((c) => c.url === '/interrupt')).toBe(true)+ })++ it('NEGATIVE CONTROL: the live session\'s own job is never touched', async () => {+ queueFixture = { queue_running: [entry('mine', CLIENT_ID)], queue_pending: [] }+ expect(await sweepOrphanedLuJobs(CLIENT_ID)).toBe(0)+ expect(calls.some((c) => c.init?.method === 'POST')).toBe(false)+ })++ it('NEGATIVE CONTROL: foreign clients without the lu- prefix are never touched', async () => {+ queueFixture = {+ queue_running: [entry('user1', 'aabbccdd-plain-uuid')],+ queue_pending: [entry('user2'), entry('user3', 'someone-else')],+ }+ expect(await sweepOrphanedLuJobs(CLIENT_ID)).toBe(0)+ expect(calls.some((c) => c.init?.method === 'POST')).toBe(false)+ expect(calls.some((c) => c.url === '/interrupt')).toBe(false)+ })++ it('returns 0 on an unreachable queue instead of throwing', async () => {+ const { localFetch } = await import('../backend')+ ;(localFetch as any).mockRejectedValueOnce(new Error('down'))+ expect(await sweepOrphanedLuJobs(CLIENT_ID)).toBe(0)+ })+})++describe('ownership marker and wiring', () => {+ const here = dirname(fileURLToPath(import.meta.url))+ const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')++ it('the live session id itself wears the prefix', () => {+ expect(CLIENT_ID.startsWith(LU_CLIENT_PREFIX)).toBe(true)+ })++ it('every agent-path submission carries the id, so its jobs are sweepable later', () => {+ const handoff = read('../vram-handoff.ts')+ expect(handoff.match(/await submitWorkflow\(workflow, CLIENT_ID\)/g)?.length).toBe(4)+ expect(handoff).not.toContain('await submitWorkflow(workflow)')+ })++ it('the sweep runs each handoff, after ComfyUI is up and before our submit', () => {+ const handoff = read('../vram-handoff.ts')+ const sweepAt = handoff.indexOf('await sweepOrphanedLuJobs(CLIENT_ID)')+ expect(sweepAt).toBeGreaterThan(handoff.indexOf('const up = await ensureComfyRunning()'))+ expect(sweepAt).toBeLessThan(handoff.indexOf("emitHandoff('generating'"))+ })++ it('NEGATIVE CONTROL: the Create tab still submits under the same live id', () => {+ expect(read('../../hooks/useCreate.ts')).toContain('submitWorkflow(workflow, CLIENT_ID)')+ })++ it('NEGATIVE CONTROL: the user Stop path and the G19-1 budget path are untouched', () => {+ const handoff = read('../vram-handoff.ts')+ expect(handoff).toContain('if (_activeHandoffs > 0) {')+ // pace verdict, G24 warm-up verdict, flat deadline+ expect(handoff.match(/await abandonPrompt\(promptId\)/g)?.length).toBe(3)+ })+})diff --git a/src/api/__tests__/vram-handoff.test.ts b/src/api/__tests__/vram-handoff.test.tsindex df48678b..45ca1a7a 100644--- a/src/api/__tests__/vram-handoff.test.ts+++ b/src/api/__tests__/vram-handoff.test.ts@@ -82,6 +82,14 @@ vi.mock('../agent-context', () => ({getActiveAgentModel: () => getActiveAgentModel(),}))+// The real WS client would call isTauri()/WebSocket at connect time, which a+// unit test has no business doing. Disconnected here, so the pace tracker and+// the G24 warm-up guard stay silent and only the flat deadline applies.+vi.mock('../comfyui-ws', () => ({+ comfyWS: { on: () => () => {}, connect: () => Promise.resolve(), connected: false },+ CLIENT_ID: 'lu-test-client',+}))+// settingsStore is the real module — pure, no services. The orchestrator reads// settings.exclusiveVramMode through it; default DEFAULT_SETTINGS = 'auto'.diff --git a/src/api/agent-context.ts b/src/api/agent-context.tsindex 2b27b1e4..96ff91ad 100644--- a/src/api/agent-context.ts+++ b/src/api/agent-context.ts@@ -45,6 +45,12 @@ export interface CapturedArtifact {}interface AgentCtxState {chatId: string | null+ /** The conversation this loop belongs to, VERBATIM. Distinct from `chatId`,+ * which is a filesystem-safe workspace SLUG derived from id + title. Any UI+ * state a tool writes (the todo_write plan) has to be keyed by the real id,+ * because that is what the components read from chatStore. Keying it by the+ * slug means the tool writes somewhere nothing ever looks. */+ conversationId: string | nullworkspace: AgentWorkspace | nullmodel: ActiveAgentModel | null/** Chat-tools artifact mode: when true, file_write captures instead of@@ -53,7 +59,7 @@ interface AgentCtxState {artifacts: CapturedArtifact[]}const _g = globalThis as typeof globalThis & { __LU_AGENT_CTX?: AgentCtxState }-const ctx: AgentCtxState = _g.__LU_AGENT_CTX ?? (_g.__LU_AGENT_CTX = { chatId: null, workspace: null, model: null, artifactMode: false, artifacts: [] })+const ctx: AgentCtxState = _g.__LU_AGENT_CTX ?? (_g.__LU_AGENT_CTX = { chatId: null, conversationId: null, workspace: null, model: null, artifactMode: false, artifacts: [] })/*** The text model driving the current agent loop. Pinned by useAgentChat right@@ -83,6 +89,14 @@ export function getActiveChatId(): string | null {return ctx.chatId}+export function setActiveConversationId(id: string | null | undefined): void {+ ctx.conversationId = id ? String(id) : null+}++export function getActiveConversationId(): string | null {+ return ctx.conversationId+}+export function setActiveAgentModel(model: ActiveAgentModel | null | undefined): void {ctx.model = model && model.name ? { name: model.name, providerId: model.providerId, remote: !!model.remote } : null}@@ -93,6 +107,7 @@ export function getActiveAgentModel(): ActiveAgentModel | null {export function clearActiveChatId(): void {ctx.chatId = null+ ctx.conversationId = nullctx.workspace = nullctx.model = nullctx.artifactMode = falsediff --git a/src/api/agents/__tests__/args-validator.test.ts b/src/api/agents/__tests__/args-validator.test.tsindex e07799ba..801c4d3a 100644--- a/src/api/agents/__tests__/args-validator.test.ts+++ b/src/api/agents/__tests__/args-validator.test.ts@@ -167,3 +167,106 @@ describe('args-validator — formatValidationErrors', () => {expect(out).toBe('top-level not object')})})++// ── Nested schemas + array arguments (2026-08-05) ────────────────+//+// Every tool with an object-in-array parameter goes through here, on every+// provider and every transport: the native OpenAI channel, the Hermes prompt+// path small local models use, and the cloud prompt transport. `todo_write` is+// the first such tool, so its shape is the fixture.++const planSchema: JsonSchema = {+ type: 'object',+ properties: {+ todos: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ content: { type: 'string' },+ status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] },+ },+ required: ['content', 'status'],+ },+ },+ },+ required: ['todos'],+}++describe('args-validator — nested object schemas', () => {+ it('accepts a well-formed nested list', () => {+ const r = validateToolArgs(+ { todos: [{ content: 'read the file', status: 'completed' }, { content: 'fix it', status: 'in_progress' }] },+ planSchema,+ )+ expect(r.valid).toBe(true)+ })++ it('reports a missing required field inside an item', () => {+ const r = validateToolArgs({ todos: [{ status: 'pending' }] }, planSchema)+ expect(r.valid).toBe(false)+ expect(formatValidationErrors(r.errors)).toMatch(/todos\[0\]\.content/)+ })++ it('reports a status the model invented, so it can correct itself', () => {+ // Silently accepting 'donezo' is how a plan ends up showing work as not+ // started with no explanation the model can act on.+ const r = validateToolArgs({ todos: [{ content: 'x', status: 'donezo' }] }, planSchema)+ expect(r.valid).toBe(false)+ expect(formatValidationErrors(r.errors)).toMatch(/todos\[0\]\.status/)+ expect(formatValidationErrors(r.errors)).toMatch(/pending/)+ })++ it('reports a wrong type inside an item', () => {+ const r = validateToolArgs({ todos: [{ content: 42, status: 'pending' }] }, planSchema)+ expect(r.valid).toBe(false)+ expect(formatValidationErrors(r.errors)).toMatch(/todos\[0\]\.content/)+ })++ it('coerces inside a nested object the way it does at the top level', () => {+ const schema: JsonSchema = {+ type: 'object',+ properties: {+ opts: { type: 'object', properties: { retries: { type: 'integer' }, force: { type: 'boolean' } } },+ },+ }+ const r = validateToolArgs({ opts: { retries: '3', force: 'false' } }, schema)+ expect(r.valid).toBe(true)+ expect(r.coerced?.opts).toEqual({ retries: 3, force: false })+ })++ it('keeps the coerced value of an array item instead of dropping it', () => {+ const schema: JsonSchema = {+ type: 'object',+ properties: { sizes: { type: 'array', items: { type: 'number' } } },+ }+ const r = validateToolArgs({ sizes: ['1', '2'] }, schema)+ expect(r.valid).toBe(true)+ expect(r.coerced?.sizes).toEqual([1, 2])+ })+})++describe('args-validator — an array sent as a JSON string', () => {+ it('parses it instead of wrapping it in a one-element array', () => {+ const r = validateToolArgs(+ { todos: '[{"content": "step one", "status": "pending"}]' },+ planSchema,+ )+ expect(r.valid).toBe(true)+ expect(r.coerced?.todos).toEqual([{ content: 'step one', status: 'pending' }])+ })++ it('surfaces a broken JSON array rather than smuggling the text through', () => {+ const r = validateToolArgs({ todos: '[{"content": "step one"' }, planSchema)+ expect(r.valid).toBe(false)+ expect(formatValidationErrors(r.errors)).toMatch(/todos/)+ })++ it('still wraps a plain single value, which is a different mistake', () => {+ const schema: JsonSchema = {+ type: 'object',+ properties: { tags: { type: 'array', items: { type: 'string' } } },+ }+ expect(validateToolArgs({ tags: 'only-one' }, schema).coerced?.tags).toEqual(['only-one'])+ })+})diff --git a/src/api/agents/__tests__/in-turn-cache.test.ts b/src/api/agents/__tests__/in-turn-cache.test.tsindex 0ce2dbfb..5e22815b 100644--- a/src/api/agents/__tests__/in-turn-cache.test.ts+++ b/src/api/agents/__tests__/in-turn-cache.test.ts@@ -209,3 +209,50 @@ describe('in-turn-cache — serves the FULL result, not the panel preview (#9)',expect(lookup(req('r2', 'file_read', args), stableArgsHash(args))).toBeUndefined()})})++// ── A write is never served from cache, but only disk writes go stale ──+//+// The two ideas used to be one set, which held while every non-cacheable tool+// also touched disk. todo_write broke that: it must always really run (it+// writes the plan the user is watching) while changing no file at all.++describe('in-turn-cache — todo_write', () => {+ beforeEach(() => {+ useToolAuditStore.getState().clearAll()+ })++ const recordDone = (toolName: string, args: Record<string, any>, at: number, result: string) => {+ const s = useToolAuditStore.getState()+ const id = s.record({ convId: 'c1', toolCallId: `prior-${toolName}-${at}`, toolName, args, startedAt: at })+ s.complete(id, { status: 'completed', completedAt: at + 10, resultPreview: result })+ }++ it('is never served from cache, even on an identical repeat', () => {+ const args = { todos: [{ content: 'step', status: 'pending' }] }+ recordDone('todo_write', args, 1000, 'stale summary')++ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })+ expect(lookup(req('new', 'todo_write', args), stableArgsHash(args))).toBeUndefined()+ })++ it('does not invalidate a cached file_read the way a real write does', () => {+ // The plan updates after every step. If it counted as a workspace mutation+ // it would throw away every cached read on each update, which is the+ // opposite of what this cache is for.+ const readArgs = { path: 'src/app.ts' }+ recordDone('file_read', readArgs, 1000, 'file contents')+ recordDone('todo_write', { todos: [] }, 2000, 'Plan cleared.')++ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })+ expect(lookup(req('new', 'file_read', readArgs), stableArgsHash(readArgs))).toBe('file contents')+ })++ it('a real write still invalidates that same cached read', () => {+ const readArgs = { path: 'src/app.ts' }+ recordDone('file_read', readArgs, 1000, 'file contents')+ recordDone('file_write', { path: 'src/app.ts', content: 'x' }, 2000, 'written')++ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })+ expect(lookup(req('new', 'file_read', readArgs), stableArgsHash(readArgs))).toBeUndefined()+ })+})diff --git a/src/api/agents/args-validator.ts b/src/api/agents/args-validator.tsindex 8e2b9206..3305806d 100644--- a/src/api/agents/args-validator.ts+++ b/src/api/agents/args-validator.ts@@ -143,14 +143,41 @@ function validatePropertyValue(}}- // Array item validation (shallow).+ // Array items. The item result is written BACK: an item schema can coerce+ // just like a top-level one ("5" → 5), and dropping that meant an array of+ // numbers arrived downstream as an array of strings, validated and wrong.if (matchesType(coerced, 'array') && schema.items && Array.isArray(coerced)) {- const itemErrs: ValidationError[] = []+ const next = [...coerced]coerced.forEach((item, i) => {const r = validatePropertyValue(`${path}[${i}]`, item, schema.items as JsonSchema)- itemErrs.push(...r.errors)+ errors.push(...r.errors)+ if (r.errors.length === 0) next[i] = r.coerced})- errors.push(...itemErrs)+ coerced = next+ }++ // Nested objects. Without this a schema could declare `properties`, `required`+ // and `enum` one level down and none of it was ever read — the model got no+ // correction for a wrong field, only whatever the executor made of it. The+ // first tool to nest is `todo_write` (each plan item is {content, status}),+ // and its status enum is exactly the kind of mistake a small model makes and+ // needs told about.+ if (matchesType(coerced, 'object') && schema.properties) {+ const nested: Record<string, any> = { ...coerced }+ if (Array.isArray(schema.required)) {+ for (const key of schema.required) {+ if (nested[key] === undefined || nested[key] === null) {+ errors.push({ path: `${path}.${key}`, message: `required property '${key}' is missing` })+ }+ }+ }+ for (const [key, propSchema] of Object.entries(schema.properties)) {+ if (!(key in nested)) continue+ const r = validatePropertyValue(`${path}.${key}`, nested[key], propSchema)+ errors.push(...r.errors)+ if (r.errors.length === 0) nested[key] = r.coerced+ }+ coerced = nested}return { errors, coerced }@@ -222,6 +249,22 @@ function tryCoerce(return { ok: false }}if (type === 'array') {+ // A model that means an array often sends it as a JSON string — the same+ // class of mistake as "true" for a boolean, and the cloud prompt transport+ // already parses it (lib/chat/prompt-tools.ts). Wrapping it instead would+ // hand the executor a one-element array holding JSON text, which reads as+ // a valid array everywhere and is wrong everywhere.+ if (typeof value === 'string' && value.trim().startsWith('[')) {+ try {+ const parsed = JSON.parse(value.trim())+ if (Array.isArray(parsed)) return { ok: true, value: parsed }+ } catch {+ // Fall through to the error rather than wrapping: a broken array is+ // something the model has to be told about, not something to smuggle+ // past as `['[{"content": ...']`.+ }+ return { ok: false }+ }// Allow single value → one-element array for array-typed params.if (value !== undefined && value !== null) return { ok: true, value: [value] }return { ok: false }diff --git a/src/api/agents/in-turn-cache.ts b/src/api/agents/in-turn-cache.tsindex a1a57964..1c9967aa 100644--- a/src/api/agents/in-turn-cache.ts+++ b/src/api/agents/in-turn-cache.ts@@ -48,6 +48,29 @@ const NON_CACHEABLE_TOOLS = new Set<string>(['shell_execute_background','code_execute','run_tests',+ // Writes the plan the user watches. Today it is idempotent, so a cache hit+ // would do no visible harm, but a write served from cache never reaches the+ // store — and a plan that silently stops updating is the one failure mode+ // that makes the whole feature untrustworthy.+ 'todo_write',+])++/**+ * Of the non-cacheable tools, the ones that touch the WORKSPACE. Only these+ * invalidate a cached read.+ *+ * The two sets used to be one, which was right while every non-cacheable tool+ * also wrote to disk. todo_write broke that: it must always really run, but it+ * changes no file. Folding it into one set would throw away every cached+ * file_read on each plan update — and the plan updates after every step.+ */+const WORKSPACE_MUTATING_TOOLS = new Set<string>([+ 'file_write',+ 'file_edit',+ 'shell_execute',+ 'shell_execute_background',+ 'code_execute',+ 'run_tests',])/** Reads whose cached payload is invalidated by a later workspace mutation. */@@ -57,9 +80,9 @@ function isNonCacheableTool(name: string): boolean {return NON_CACHEABLE_TOOLS.has(name) || name.startsWith('git_')}-/** A workspace-mutating call — same set that is non-cacheable, plus git_*. */+/** A workspace-mutating call — the disk-touching subset, plus git_*. */function isMutatingTool(name: string): boolean {- return NON_CACHEABLE_TOOLS.has(name) || name.startsWith('git_')+ return WORKSPACE_MUTATING_TOOLS.has(name) || name.startsWith('git_')}/**diff --git a/src/api/comfyui-ws.ts b/src/api/comfyui-ws.tsindex 8b351e78..be29716c 100644--- a/src/api/comfyui-ws.ts+++ b/src/api/comfyui-ws.ts@@ -43,8 +43,14 @@ export const DECODE_NODES = new Set(['VAEDecode', 'VAEDecodeTiled',])+/** Every LU submission carries a client id with this prefix, so a later LU+ * session can recognise a dead session's job in ComfyUI's queue and clean it+ * up (G19-3: a killed app left its render burning the GPU, queued four deep).+ * Foreign clients (a user's own ComfyUI tab) never carry it. */+export const LU_CLIENT_PREFIX = 'lu-'+/** Shared client ID used for both WS connection and workflow submission */-export const CLIENT_ID = uuid()+export const CLIENT_ID = `${LU_CLIENT_PREFIX}${uuid()}`class ComfyWSClient {private ws: WebSocket | null = nulldiff --git a/src/api/comfyui.ts b/src/api/comfyui.tsindex 8f4991dd..f109a90f 100644--- a/src/api/comfyui.ts+++ b/src/api/comfyui.ts@@ -1,5 +1,6 @@import { comfyuiUrl, localFetch, fetchLocalhostBytes, isTauri, backendCall } from "./backend"import { log } from "../lib/logger"+import { LU_CLIENT_PREFIX } from "./comfyui-ws"// ─── Control-plane fetch timeouts ───//@@ -1111,6 +1112,76 @@ export async function clearComfyQueue(): Promise<void> {} catch { /* best effort */ }}+/**+ * Abandon ONE prompt without touching anyone else's work (G19-1). A blanket+ * /interrupt kills whatever is CURRENTLY executing, which is the wrong job+ * whenever ours still sits in the pending queue (R32: our render was number 4+ * in line). So: delete ours from pending first, then interrupt only if ours is+ * the one running. Best-effort on every leg.+ */+export async function abandonPrompt(promptId: string): Promise<void> {+ try {+ await localFetch(comfyuiUrl('/queue'), {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ delete: [promptId] }),+ timeoutMs: COMFY_STATS_TIMEOUT_MS,+ })+ } catch { /* best effort */ }+ try {+ const res = await localFetch(comfyuiUrl('/queue'), { timeoutMs: COMFY_STATS_TIMEOUT_MS })+ if (!res.ok) return+ const q = await res.json()+ const running = Array.isArray(q.queue_running)+ && q.queue_running.some((e: unknown) => Array.isArray(e) && e[1] === promptId)+ if (running) await cancelGeneration()+ } catch { /* best effort */ }+}++/**+ * Clean up jobs a DEAD LU session left in ComfyUI (G19-3): a killed app cannot+ * cancel its render, so the job keeps burning the GPU with no owner and every+ * new generation queues behind it (R32 sat at queue position 4). Every LU+ * submission carries an `lu-` client id; anything wearing that prefix under a+ * DIFFERENT id than ours belongs to a session that no longer exists. Pending+ * orphans are deleted, a running orphan is interrupted. Foreign clients (a+ * user's own ComfyUI tab) never carry the prefix and are never touched.+ * Returns how many jobs were cleaned, 0 on any error (best effort).+ */+export async function sweepOrphanedLuJobs(currentClientId: string): Promise<number> {+ try {+ const res = await localFetch(comfyuiUrl('/queue'), { timeoutMs: COMFY_STATS_TIMEOUT_MS })+ if (!res.ok) return 0+ const q = await res.json()+ // Queue entries are [number, prompt_id, prompt, extra_data, ...] tuples.+ const staleId = (e: unknown): string | null => {+ if (!Array.isArray(e) || typeof e[1] !== 'string') return null+ const owner = (e[3] as Record<string, unknown> | undefined)?.client_id+ return typeof owner === 'string' && owner.startsWith(LU_CLIENT_PREFIX) && owner !== currentClientId+ ? e[1]+ : null+ }+ const pending = (Array.isArray(q.queue_pending) ? q.queue_pending : [])+ .map(staleId)+ .filter((id: string | null): id is string => id !== null)+ if (pending.length > 0) {+ await localFetch(comfyuiUrl('/queue'), {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ delete: pending }),+ timeoutMs: COMFY_STATS_TIMEOUT_MS,+ })+ }+ const runningStale = (Array.isArray(q.queue_running) ? q.queue_running : []).some((e: unknown) => staleId(e) !== null)+ if (runningStale) await cancelGeneration()+ const cleaned = pending.length + (runningStale ? 1 : 0)+ if (cleaned > 0) log.info('comfyui.orphan_sweep', { cleaned, pending: pending.length, runningStale })+ return cleaned+ } catch {+ return 0+ }+}+export async function freeMemory(): Promise<void> {try {await localFetch(comfyuiUrl('/free'), {diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.tsindex 963dc11d..4409cbb0 100644--- a/src/api/vram-handoff.ts+++ b/src/api/vram-handoff.ts@@ -57,6 +57,8 @@ import {freeMemory,cancelGeneration,clearComfyQueue,+ abandonPrompt,+ sweepOrphanedLuJobs,extractComfyOutputFiles,getImageUrl,classifyModel,@@ -70,6 +72,8 @@ import {} from './comfyui'import type { ModelCapabilities } from './comfyui-nodes'import { getActiveAgentModel } from './agent-context'+import { comfyWS, CLIENT_ID } from './comfyui-ws'+import { PaceTracker, overBudget, renderBudgetNotice, renderTimeoutNotice, warmupExceeded, swapWarmupNotice } from '../lib/render-budget'import { log } from '../lib/logger'/**@@ -873,6 +877,12 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs, seq: nreturn 'Error: ComfyUI did not start within 90s. Start it from the Create tab and try again.'}+ // A dead LU session cannot cancel its render, so clean its leftovers out+ // of the queue BEFORE we submit ours (G19-3): otherwise our job waits+ // behind an ownerless render burning the GPU (R32 sat at position 4).+ // Best effort and cheap (one GET /queue when nothing is stale).+ await sweepOrphanedLuJobs(CLIENT_ID)+emitHandoff('generating', { kind, detail: targetModel })// Race the WHOLE generation against the cancel signal — not just the poll@@ -1022,7 +1032,7 @@ async function generateImage(prompt: string, model: string, args: VramHandoffArg// (/prompt). Both are now timeout-bounded, so neither can strand the// hand-off with the text model unloaded — these logs just pinpoint where.log.info('vram_handoff.image.submit', { model, i2i: !!inputImage })- const promptId = await submitWorkflow(workflow)+ const promptId = await submitWorkflow(workflow, CLIENT_ID)log.info('vram_handoff.image.submitted', { promptId })const result = await pollAndExtract(promptId, prompt, label('image'), getImageTimeoutMs())// Remember the produced filename so a follow-up "animate it" video call can@@ -1123,7 +1133,7 @@ async function generateVideo(type,)log.info('vram_handoff.video.submit', { model, mode: inputImage ? 'i2v' : 't2v', wan22: true, steps: tunSteps, cfg: tunCfg })- const promptId = await submitWorkflow(workflow)+ const promptId = await submitWorkflow(workflow, CLIENT_ID)log.info('vram_handoff.video.submitted', { promptId })return await pollAndExtract(promptId, prompt, label('video'), getVideoTimeoutMs())}@@ -1192,7 +1202,7 @@ async function generateVideo(type,)log.info('vram_handoff.video.submit', { model, i2v: true })- const promptId = await submitWorkflow(workflow)+ const promptId = await submitWorkflow(workflow, CLIENT_ID)log.info('vram_handoff.video.submitted', { promptId })return await pollAndExtract(promptId, prompt, label('video'), getVideoTimeoutMs())}@@ -1230,7 +1240,7 @@ async function generateVideo(backend,)log.info('vram_handoff.video.submit', { model, i2v: false, backend })- const promptId = await submitWorkflow(workflow)+ const promptId = await submitWorkflow(workflow, CLIENT_ID)log.info('vram_handoff.video.submitted', { promptId })return await pollAndExtract(promptId, prompt, label('video'), getVideoTimeoutMs())} catch (err) {@@ -1246,44 +1256,85 @@ async function generateVideo(*/async function pollAndExtract(promptId: string, prompt: string, kindLabel: string, timeoutMs: number): Promise<string> {const deadline = Date.now() + timeoutMs- while (Date.now() < deadline) {- // User hit the in-chat cancel button — ComfyUI was already sent /interrupt- // + queue-clear by requestGenerationCancel(); stop polling so runHandoff's- // finally can restore the text model into VRAM instead of waiting out the- // timeout. RACE both the sleep AND the getHistory against the cancel signal- // (bug B): a cold checkpoint load makes getHistory block for up to its 15 s- // cap, so a between-ticks-only check kept "stopping…" on screen for seconds.- if (_genCancelRequested) return `${kindLabel} generation cancelled.`- if ((await raceCancel(sleep(1000))) === CANCELLED) return `${kindLabel} generation cancelled.`- const history = await raceCancel(getHistory(promptId))- if (history === CANCELLED) return `${kindLabel} generation cancelled.`- if (history?.status?.completed) {- const outputs = history.outputs ?? {}- for (const nodeId of Object.keys(outputs)) {- const files = extractComfyOutputFiles(outputs[nodeId])- if (files.length > 0) {- const f = files[0]- const url = getImageUrl(f.filename, f.subfolder ?? '', f.type ?? 'output')- return `${kindLabel} generated: ${f.filename} (prompt: "${prompt}")\n${url}`- }+ // G19-1 render budget: read the pace off ComfyUI's own progress events and+ // give up EARLY, with the job cancelled, once the projection says the render+ // cannot land inside the budget (R32: a 30 to 60 minute Wan job burned the+ // GPU for the full deadline and was then orphaned by the timeout). No WS is+ // fine: the pace stays empty and only the flat deadline applies.+ const pace = new PaceTracker()+ // G24: the swap/model-load phase emits NO progress events, so the pace+ // tracker stays silent through it and a generous user timeout never ends it+ // (R17c: 19 minutes of "loading model into VRAM"). Track whether ANY prompt+ // progressed; if the WS is alive and nothing on the GPU has moved for the+ // whole warm-up budget, the load is wedged and the job gets abandoned.+ const startedAt = Date.now()+ let sawAnyProgress = false+ const offProgress = comfyWS.on((ev) => {+ if (ev.type === 'progress') {+ sawAnyProgress = true+ if (ev.data.prompt_id === promptId) {+ pace.tick(ev.data.value, ev.data.max, Date.now())}- return `${kindLabel} generation completed but no output produced.`}- if (history?.status?.status_str === 'error') {- // Pull the richest detail ComfyUI gives us: an execution_error carries- // node_type + exception_type + exception_message (the plain `message`- // field is usually empty for node errors — David 2026-06-11, FramePack).- const errEntry = history.status.messages?.find((m: any) => m?.[0] === 'execution_error')?.[1]- const rawMsg = errEntry?.exception_message- || history.status.messages?.map((m: any) => m?.[1]?.message).filter(Boolean).join(' | ')- || history.status.messages?.[0]?.[1]?.message- || 'Unknown ComfyUI error'- const hint = comfyErrorHint(errEntry?.node_type, errEntry?.exception_type, String(rawMsg))- return `${kindLabel} generation failed: ${rawMsg}${hint ? `\n\n${hint}` : ''}`+ })+ void comfyWS.connect().catch(() => { /* degrade to the flat deadline */ })+ try {+ while (Date.now() < deadline) {+ // User hit the in-chat cancel button — ComfyUI was already sent /interrupt+ // + queue-clear by requestGenerationCancel(); stop polling so runHandoff's+ // finally can restore the text model into VRAM instead of waiting out the+ // timeout. RACE both the sleep AND the getHistory against the cancel signal+ // (bug B): a cold checkpoint load makes getHistory block for up to its 15 s+ // cap, so a between-ticks-only check kept "stopping…" on screen for seconds.+ if (_genCancelRequested) return `${kindLabel} generation cancelled.`+ if ((await raceCancel(sleep(1000))) === CANCELLED) return `${kindLabel} generation cancelled.`+ const history = await raceCancel(getHistory(promptId))+ if (history === CANCELLED) return `${kindLabel} generation cancelled.`+ if (history?.status?.completed) {+ const outputs = history.outputs ?? {}+ for (const nodeId of Object.keys(outputs)) {+ const files = extractComfyOutputFiles(outputs[nodeId])+ if (files.length > 0) {+ const f = files[0]+ const url = getImageUrl(f.filename, f.subfolder ?? '', f.type ?? 'output')+ return `${kindLabel} generated: ${f.filename} (prompt: "${prompt}")\n${url}`+ }+ }+ return `${kindLabel} generation completed but no output produced.`+ }+ if (history?.status?.status_str === 'error') {+ // Pull the richest detail ComfyUI gives us: an execution_error carries+ // node_type + exception_type + exception_message (the plain `message`+ // field is usually empty for node errors — David 2026-06-11, FramePack).+ const errEntry = history.status.messages?.find((m: any) => m?.[0] === 'execution_error')?.[1]+ const rawMsg = errEntry?.exception_message+ || history.status.messages?.map((m: any) => m?.[1]?.message).filter(Boolean).join(' | ')+ || history.status.messages?.[0]?.[1]?.message+ || 'Unknown ComfyUI error'+ const hint = comfyErrorHint(errEntry?.node_type, errEntry?.exception_type, String(rawMsg))+ return `${kindLabel} generation failed: ${rawMsg}${hint ? `\n\n${hint}` : ''}`+ }+ const projected = pace.projectedTotalMs()+ if (overBudget(projected, timeoutMs)) {+ log.warn('vram_handoff.render_budget_abort', { promptId, projectedMs: Math.round(projected!), budgetMs: timeoutMs })+ await abandonPrompt(promptId)+ return renderBudgetNotice(kindLabel, projected!, timeoutMs)+ }+ const warmupElapsed = Date.now() - startedAt+ if (warmupExceeded(sawAnyProgress, comfyWS.connected, warmupElapsed)) {+ log.warn('vram_handoff.swap_warmup_abort', { promptId, elapsedMs: warmupElapsed })+ await abandonPrompt(promptId)+ return swapWarmupNotice(kindLabel, warmupElapsed)+ }}+ // Deadline reached: the wait ends AND the job ends. The old return here+ // walked away and left the render burning the GPU with no owner.+ log.warn('vram_handoff.render_timeout_abort', { promptId, budgetMs: timeoutMs })+ await abandonPrompt(promptId)+ return renderTimeoutNotice(kindLabel, timeoutMs)+ } finally {+ offProgress()}- const mins = Math.round(timeoutMs / 60000)- return `${kindLabel} generation timed out after ${mins} minutes.`}// ── Small helpers ─────────────────────────────────────────────────diff --git a/src/components/chat/ApprovalDialog.tsx b/src/components/chat/ApprovalDialog.tsxindex 6fa0c41c..188d45f6 100644--- a/src/components/chat/ApprovalDialog.tsx+++ b/src/components/chat/ApprovalDialog.tsx@@ -1,5 +1,5 @@import { motion, AnimatePresence } from 'framer-motion'-import { useEffect, useState } from 'react'+import { useState } from 'react'import { ChevronDown } from 'lucide-react'import type { AgentToolCall } from '../../types/agent-mode'@@ -19,27 +19,16 @@ interface Props {* focus into a modal — readable at a glance, dismissible without breaking* flow.*- * Keyboard shortcuts: Enter → approve, Escape → reject. Args expand inline- * via the chevron button if the user wants to inspect what the agent is- * about to run.+ * Keyboard shortcuts (Enter approves, Escape rejects) are NOT bound here.+ * ChatView owns that layer so the shortcuts also work while the inline+ * buttons on the tool block are off screen; a second listener here would+ * answer TWO queued approvals on one keypress, silently approving a tool the+ * user never saw. Args expand inline via the chevron button if the user wants+ * to inspect what the agent is about to run.*/export function ApprovalDialog({ toolCall, onApprove, onReject }: Props) {const [argsOpen, setArgsOpen] = useState(false)- useEffect(() => {- const handler = (e: KeyboardEvent) => {- if (e.key === 'Enter' && !e.shiftKey) {- e.preventDefault()- onApprove()- } else if (e.key === 'Escape') {- e.preventDefault()- onReject()- }- }- window.addEventListener('keydown', handler)- return () => window.removeEventListener('keydown', handler)- }, [onApprove, onReject])-return (<AnimatePresence mode="wait"><motion.div@@ -76,7 +65,6 @@ export function ApprovalDialog({ toolCall, onApprove, onReject }: Props) {</button><buttononClick={onApprove}- autoFocusclassName="px-2 py-0.5 rounded text-[0.6rem] text-gray-800 dark:text-gray-100 bg-gray-100 dark:bg-white/10 hover:bg-gray-200 dark:hover:bg-white/15 border border-gray-300 dark:border-white/15 transition-colors font-medium">Approvediff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsxindex c8e669b4..a649495a 100644--- a/src/components/chat/ChatInput.tsx+++ b/src/components/chat/ChatInput.tsx@@ -3,6 +3,7 @@ import { motion } from 'framer-motion'import { Send, Square, Paperclip, X, Brain, Terminal } from 'lucide-react'import { matchAgentCommands, type AgentCommand } from '../../lib/agent-commands'import { VoiceButton } from './VoiceButton'+import { ApprovalDialog } from './ApprovalDialog'import { useVoiceStore } from '../../stores/voiceStore'import { useSettingsStore } from '../../stores/settingsStore'import { useModelStore } from '../../stores/modelStore'@@ -286,6 +287,17 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onAppinstruction that steers every turn is never invisible. */}{composerAbove}+ {/* G31: the run is STOPPED until this is answered, so the answer has to+ be where the user's eyes already are. The inline buttons on the tool+ block are still there and still the nicer place to decide from, but+ the list does not scroll to them, so on R01c (Mac, 2026-08-07) a run+ sat waiting 7 minutes with nothing but a clock icon far below the+ fold. An approval has no timeout by design, which makes being seen+ the only thing that ends it. */}+ {pendingApproval && onApprove && onReject && (+ <ApprovalDialog toolCall={pendingApproval} onApprove={onApprove} onReject={onReject} />+ )}+{/* Prompt area — hints, image previews, then the textarea (buttons livein the action bar below, web-parity two-row composer). */}<div className="px-3 pt-2.5">diff --git a/src/components/chat/PlanBar.tsx b/src/components/chat/PlanBar.tsxnew file mode 100644index 00000000..d88b7f50--- /dev/null+++ b/src/components/chat/PlanBar.tsx@@ -0,0 +1,109 @@+// The model's own plan for the current task, above the composer in Code and in+// Agent (audit C4).+//+// On a long run the transcript scrolls away and the user is left guessing which+// step the agent is on and whether it still remembers the goal. The agent writes+// this list through `todo_write` and keeps it current, so progress is one glance+// instead of a scroll back through twenty tool calls.+//+// Collapsed to the current step by default: this sits directly above the+// composer and a ten-item list would push the input off screen. Expanded state+// is per session, not persisted, because a plan is short-lived.++import { useState } from 'react'+import { CheckCircle2, Circle, ChevronDown, ChevronRight, Loader2, ListTodo, X } from 'lucide-react'+import { useTodoStore } from '../../stores/todoStore'+import { useChatStore } from '../../stores/chatStore'++export function PlanBar() {+ const activeConversationId = useChatStore((s) => s.activeConversationId)+ const todos = useTodoStore((s) =>+ activeConversationId ? s.byConversation[activeConversationId] : undefined,+ )+ const clearTodos = useTodoStore((s) => s.clearTodos)+ const [expanded, setExpanded] = useState(false)++ if (!activeConversationId || !todos || todos.length === 0) return null++ const done = todos.filter((t) => t.status === 'completed').length+ const current = todos.find((t) => t.status === 'in_progress')+ const allDone = done === todos.length+ // Collapsed, the one line that matters is what is happening NOW. With nothing+ // in progress (plan written but not started, or everything finished) fall back+ // to the first item that is still open, and only then to the last one.+ const headline = current ?? todos.find((t) => t.status === 'pending') ?? todos[todos.length - 1]++ return (+ <div className="w-full max-w-[70%] mx-auto px-3 pb-1 flex justify-center">+ <div className="w-full rounded-md border border-blue-500/20 bg-blue-500/[0.04]">+ <div className="flex items-center gap-1.5 px-2 py-1">+ <button+ onClick={() => setExpanded((v) => !v)}+ title={expanded ? 'Collapse the plan' : 'Show every step'}+ className="flex items-center gap-1.5 min-w-0 flex-1 text-left"+ >+ {expanded ? (+ <ChevronDown size={9} className="text-blue-400 shrink-0" />+ ) : (+ <ChevronRight size={9} className="text-blue-400 shrink-0" />+ )}+ <ListTodo size={9} className="text-blue-400 shrink-0" />+ <span className="text-[0.55rem] uppercase tracking-wider text-gray-500 shrink-0">+ plan {done}/{todos.length}+ </span>+ {!expanded && (+ <span+ className="flex-1 min-w-0 truncate text-[0.6rem] text-gray-700 dark:text-gray-300"+ title={headline.content}+ >+ {headline.content}+ </span>+ )}+ </button>+ <button+ onClick={() => clearTodos(activeConversationId)}+ title="Clear the plan"+ className="flex items-center justify-center w-4 h-4 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 transition-colors shrink-0"+ >+ <X size={10} />+ </button>+ </div>++ {expanded && (+ // Capped so a fifteen-step plan cannot push the composer off screen.+ <ul className="px-2 pb-1.5 space-y-0.5 max-h-40 overflow-y-auto">+ {todos.map((t, i) => (+ <li key={`${i}-${t.content}`} className="flex items-start gap-1.5">+ {t.status === 'completed' ? (+ <CheckCircle2 size={10} className="text-emerald-400 shrink-0 mt-[1px]" />+ ) : t.status === 'in_progress' ? (+ <Loader2 size={10} className="text-blue-400 shrink-0 mt-[1px] animate-spin" />+ ) : (+ <Circle size={10} className="text-gray-600 shrink-0 mt-[1px]" />+ )}+ <span+ className={`text-[0.6rem] leading-snug ${+ t.status === 'completed'+ ? 'text-gray-500 line-through'+ : t.status === 'in_progress'+ ? 'text-gray-800 dark:text-gray-100 font-medium'+ : 'text-gray-600 dark:text-gray-400'+ }`}+ >+ {t.content}+ </span>+ </li>+ ))}+ </ul>+ )}++ {!expanded && allDone && (+ <div className="px-2 pb-1 flex items-center gap-1.5">+ <CheckCircle2 size={9} className="text-emerald-400 shrink-0" />+ <span className="text-[0.55rem] text-emerald-400/80">every step done</span>+ </div>+ )}+ </div>+ </div>+ )+}diff --git a/src/components/chat/__tests__/approval-stays-visible.test.ts b/src/components/chat/__tests__/approval-stays-visible.test.tsnew file mode 100644index 00000000..b9dc2eda--- /dev/null+++ b/src/components/chat/__tests__/approval-stays-visible.test.ts@@ -0,0 +1,77 @@+/**+ * G31 (R01c, Mac, 2026-08-07): an agent run sat waiting SEVEN MINUTES on an+ * approval. The Approve/Reject buttons were rendered the whole time, on the+ * tool block, far below the fold, and the list never scrolled to them. All the+ * user saw was a clock icon and a composer offering an empty message box.+ *+ * A waiting approval has no timeout, on purpose: awaitApproval sits OUTSIDE+ * raceWithToolTimeout, because a human may legitimately take a while. That+ * makes being seen the only thing that ever ends the wait, which is why these+ * are guards and not preferences.+ *+ * Run: npx vitest run src/components/chat/__tests__/approval-stays-visible.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++const here = dirname(fileURLToPath(import.meta.url))+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')+const chatInput = read('../ChatInput.tsx')+const approvalDialog = read('../ApprovalDialog.tsx')+const messageList = read('../MessageList.tsx')+const chatView = read('../ChatView.tsx')+const codexView = read('../CodexView.tsx')++describe('a pending approval is always reachable', () => {+ it('the composer renders the strip, so the decision cannot scroll away', () => {+ // The component existed and was imported by nobody: defined, styled,+ // documented as "rendered directly above the ChatInput", and dead. That is+ // exactly how this bug survived.+ expect(chatInput).toContain("import { ApprovalDialog } from './ApprovalDialog'")+ expect(chatInput).toMatch(/pendingApproval && onApprove && onReject && \(/)+ expect(chatInput).toContain('<ApprovalDialog toolCall={pendingApproval}')+ })++ it('the strip is wired to the same callbacks the chat passes down', () => {+ expect(chatInput).toContain('onApprove={onApprove}')+ expect(chatInput).toContain('onReject={onReject}')+ expect(chatView).toContain('pendingApproval={pendingApproval}')+ expect(chatView).toContain('onApprove={approveToolCall}')+ expect(chatView).toContain('onReject={rejectToolCall}')+ })++ it('a new approval pulls the list down with it', () => {+ // The call shape changed with G33 (resumeKey + content wrapper); the+ // approval id staying in the trigger string is what this guard pins.+ expect(messageList).toContain('`${lastMessage?.content ?? \'\'}|${pendingApprovalId ?? \'\'}`')+ })++ // ── Negative controls ────────────────────────────────────────────────────++ it('EXACTLY ONE keyboard layer answers an approval', () => {+ // Both listeners firing on one Enter would pop TWO entries off the queue:+ // the tool the user saw, plus the next one, approved without ever being+ // shown. ChatView keeps the layer because it works off screen too.+ expect(approvalDialog).not.toContain('addEventListener')+ expect(chatView).toContain("window.addEventListener('keydown', handler)")+ })++ it('the strip does not steal focus from the message box', () => {+ // autoFocus on Approve made sense while this was a modal. In the composer+ // it would yank the caret out of a half-typed message, and it would put+ // Enter on a focused button while ChatView's handler is also listening.+ expect(approvalDialog).not.toContain('autoFocus')+ })++ it('the list still scrolls on plain streaming content', () => {+ // The trigger must keep the content in it, or an ordinary chat answer+ // stops following the stream.+ expect(messageList).toContain('lastMessage?.content')+ })++ it('the Code tab is untouched: it has its own staging queue', () => {+ expect(codexView).not.toContain('pendingApproval=')+ })+})diff --git a/src/hooks/__tests__/agent-shell-gate.test.ts b/src/hooks/__tests__/agent-shell-gate.test.tsnew file mode 100644index 00000000..bb7057fb--- /dev/null+++ b/src/hooks/__tests__/agent-shell-gate.test.ts@@ -0,0 +1,79 @@+/**+ * One cloud shell policy for both surfaces (G15a, decided 2026-08-07): the+ * Code tab confirms shell_execute / code_execute / shell_execute_background on+ * an LU Cloud model, and R23 proved Agent mode ran the same tools on the same+ * model unattended. Agent now lifts an exec tool to pending_approval when the+ * shared gate's cloud arm says so, on top of its per-tool permission levels.+ *+ * Run: npx vitest run src/hooks/__tests__/agent-shell-gate.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++import { CODEX_CONFIRM_TOOLS, codexConfirmEnabled } from '../codexShellGate'++const here = dirname(fileURLToPath(import.meta.url))+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')+const agent = read('../useAgentChat.ts')++describe('the shared policy, as Agent mode consumes it', () => {+ const agentArm = (providerId: string, cloudConfirmShell: boolean) =>+ codexConfirmEnabled({ confirmShell: false, cloudConfirmShell, providerId })++ it('a cloud model must ask before running local shell', () => {+ expect(agentArm('lu-cloud', true)).toBe(true)+ })++ it('NEGATIVE CONTROL: a local model the user chose to trust stays unattended', () => {+ expect(agentArm('ollama', true)).toBe(false)+ expect(agentArm('openai', true)).toBe(false)+ })++ it('NEGATIVE CONTROL: the visible switch really turns it off', () => {+ expect(agentArm('lu-cloud', false)).toBe(false)+ })++ it('only the arbitrary-exec tools are gated, never the jailed file tools', () => {+ expect(CODEX_CONFIRM_TOOLS.has('shell_execute')).toBe(true)+ expect(CODEX_CONFIRM_TOOLS.has('code_execute')).toBe(true)+ expect(CODEX_CONFIRM_TOOLS.has('shell_execute_background')).toBe(true)+ expect(CODEX_CONFIRM_TOOLS.has('file_write')).toBe(false)+ expect(CODEX_CONFIRM_TOOLS.has('web_fetch')).toBe(false)+ })+})++describe('wiring in useAgentChat', () => {+ it('the cloud arm rides ON TOP of the permission level, never replaces it', () => {+ expect(agent).toContain("const needsApproval = permLevel !== 'auto' || cloudShellConfirm")+ })++ it('the gate reads the SAME shared helper and setting as the Code tab', () => {+ expect(agent).toContain("import { CODEX_CONFIRM_TOOLS, codexConfirmEnabled } from './codexShellGate'")+ expect(agent).toContain('cloudConfirmShell: settings.codexCloudConfirmShell')+ expect(agent).toContain('CODEX_CONFIRM_TOOLS.has(tc.function.name)')+ })++ it('a gated call lands in the EXISTING approval flow, not a new dialog', () => {+ // pending_approval blocks enqueue through waitForApproval; the gate only+ // flips needsApproval, so the run pauses in the same inline approve UI.+ expect(agent).toContain("status: needsApproval ? 'pending_approval' : 'running'")+ // The conversation id joined the call with G29b (the queue moved to module+ // scope so an approval survives the view being torn down); the gate itself+ // still goes through this one flow.+ expect(agent).toContain('await waitForApproval(convId!, entry.ac, abort.signal)')+ })++ it('NEGATIVE CONTROL: the Codex side of the gate is untouched', () => {+ const codex = read('../useCodex.ts')+ expect(codex).toContain('confirmShell: settings.codexConfirmShell')+ expect(codex).toContain('cloudConfirmShell: settings.codexCloudConfirmShell')+ })++ it('the settings toggle is always visible now, since it governs Agent too', () => {+ const page = read('../../components/settings/SettingsPage.tsx')+ expect(page).toContain('Also confirm when Agent or Coding runs on an LU Cloud model')+ expect(page).not.toContain('{!settings.codexConfirmShell && (')+ })+})diff --git a/src/hooks/codexShellGate.ts b/src/hooks/codexShellGate.tsindex 7aa93925..10687597 100644--- a/src/hooks/codexShellGate.ts+++ b/src/hooks/codexShellGate.ts@@ -1,5 +1,11 @@// H2 security gate — shared, pure, testable.//+// Consumed by BOTH loops since G15a (2026-08-07): useCodex gates on it+// directly, and useAgentChat lifts an exec tool to pending_approval when+// the cloud arm says so, on top of its per-tool permission levels. Before+// that, the same cloud model that had to ask in the Code tab ran+// shell_execute unattended on the Agent surface (R23).+//// The coding agent (useCodex) auto-runs tools unattended by design. These are// the arbitrary-code-execution tools — the prompt-injection RCE surface (a tool// result or a read file steering the model into running a command). When thediff --git a/src/lib/__tests__/approval-queue.test.ts b/src/lib/__tests__/approval-queue.test.tsnew file mode 100644index 00000000..d3d4504a--- /dev/null+++ b/src/lib/__tests__/approval-queue.test.ts@@ -0,0 +1,120 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'+import {+ subscribeApprovals,+ headApproval,+ enqueueApproval,+ dequeueApproval,+ removeApproval,+ drainApprovals,+ resetApprovals,+ type ApprovalEntry,+} from '../approval-queue'+import type { AgentToolCall } from '../../types/agent-mode'++const call = (id: string): AgentToolCall =>+ ({ id, toolName: 'file_edit', args: {}, status: 'pending_approval' }) as AgentToolCall++const entry = (id: string): ApprovalEntry & { answered: boolean[] } => {+ const answered: boolean[] = []+ return { toolCall: call(id), resolve: (ok) => answered.push(ok), answered }+}++describe('G29b: an approval outlives the view that asked for it', () => {+ beforeEach(() => resetApprovals())++ it('a fresh reader finds the approval a torn-down view left behind', () => {+ // The run enqueues while the chat view is being replaced by Settings.+ enqueueApproval('conv-1', entry('tc-1'))+ // The remounted hook asks the module, not its own empty ref.+ expect(headApproval('conv-1')?.id).toBe('tc-1')+ })++ it('keeps FIFO order, so a parallel batch cannot deadlock its first asker', () => {+ // The Phase 5 rule this queue exists for: a single slot would let the+ // second asker overwrite the first, whose promise then never settles.+ const first = entry('tc-1')+ const second = entry('tc-2')+ enqueueApproval('conv-1', first)+ enqueueApproval('conv-1', second)++ expect(headApproval('conv-1')?.id).toBe('tc-1')+ dequeueApproval('conv-1')?.resolve(true)+ expect(first.answered).toEqual([true])+ expect(headApproval('conv-1')?.id).toBe('tc-2')+ })++ it('answers every waiter when the turn ends or Stop is pressed', () => {+ const a = entry('tc-1')+ const b = entry('tc-2')+ enqueueApproval('conv-1', a)+ enqueueApproval('conv-1', b)++ drainApprovals('conv-1')++ expect(a.answered).toEqual([false])+ expect(b.answered).toEqual([false])+ expect(headApproval('conv-1')).toBeNull()+ })++ it('an abort after a click does not answer the same tool twice', () => {+ // waitForApproval only resolves on abort when removeApproval says the+ // entry was still queued. A second resolve would settle nothing but would+ // hide a real double-answer bug from us.+ const e = entry('tc-1')+ enqueueApproval('conv-1', e)+ dequeueApproval('conv-1')?.resolve(true)++ expect(removeApproval('conv-1', e)).toBe(false)+ expect(e.answered).toEqual([true])+ })++ it('notifies subscribers on every change and stops after unsubscribe', () => {+ const seen = vi.fn()+ const off = subscribeApprovals(seen)+ enqueueApproval('conv-1', entry('tc-1'))+ dequeueApproval('conv-1')+ expect(seen).toHaveBeenCalledTimes(2)+ off()+ enqueueApproval('conv-1', entry('tc-2'))+ expect(seen).toHaveBeenCalledTimes(2)+ })++ // ── Negative controls ────────────────────────────────────────────────────++ it('an approval never surfaces in a different conversation', () => {+ // The queue outlives the view, so without the key a run continuing in one+ // chat would ask the user about it while they are reading another.+ enqueueApproval('conv-2', entry('tc-1'))+ expect(headApproval('conv-1')).toBeNull()+ expect(dequeueApproval('conv-1')).toBeUndefined()+ expect(headApproval('conv-2')?.id).toBe('tc-1')+ })++ it('a conversation with nothing pending shows nothing', () => {+ expect(headApproval('conv-1')).toBeNull()+ expect(headApproval(null)).toBeNull()+ expect(headApproval(undefined)).toBeNull()+ expect(dequeueApproval(null)).toBeUndefined()+ })++ it('draining an idle conversation answers nobody', () => {+ const seen = vi.fn()+ subscribeApprovals(seen)+ drainApprovals('conv-1')+ drainApprovals(null)+ expect(headApproval('conv-1')).toBeNull()+ })++ it('leaves no empty queue behind once a conversation is answered', () => {+ // The map outlives every view, so an entry per conversation ever opened+ // would be a slow leak.+ enqueueApproval('conv-1', entry('tc-1'))+ dequeueApproval('conv-1')?.resolve(false)+ expect(headApproval('conv-1')).toBeNull()++ const aborted = entry('tc-2')+ enqueueApproval('conv-2', aborted)+ expect(removeApproval('conv-2', aborted)).toBe(true)+ expect(headApproval('conv-2')).toBeNull()+ })+})diff --git a/src/lib/__tests__/compaction-keeps-progress.test.ts b/src/lib/__tests__/compaction-keeps-progress.test.tsnew file mode 100644index 00000000..ecb5d161--- /dev/null+++ b/src/lib/__tests__/compaction-keeps-progress.test.ts@@ -0,0 +1,138 @@+/**+ * Compaction pinned the task and dropped the progress, so a long run started+ * the task over from the top.+ *+ * Measured on the installed 2.6.2 Windows build, Coding surface, Ollama with+ * the hermes schema, 2026-08-06. A 30 step plan, one step per tool. The run+ * walked steps 1 to 18 in order and then, in the very next call, did this:+ *+ * … git_status, git_diff, git_commit, git_log,+ * todo_write, get_current_time, system_info, process_list, file_list, …+ *+ * That second half is steps 1 to 5 again. David, watching it: "es wiederholt+ * sich die ganze Zeit ... das fängt so ab, ruft neu an. Und er sagt immer+ * dasselbe."+ *+ * The cause is the shape of the compacted prompt. `PINNED_TASK` (audit C5)+ * keeps the instruction alive forever, the suffix window keeps the newest few+ * messages, and everything between them is replaced by a notice that says a+ * trim happened but never says WHAT already ran. The model is left holding a+ * 30 step plan and no evidence of having started it, so starting at step 1 is+ * the only reasonable thing it can do.+ *+ * Run: npx vitest run src/lib/__tests__/compaction-keeps-progress.test.ts+ */+import { describe, it, expect } from 'vitest'+import { compactMessages } from '../context-compaction'++type Msg = Parameters<typeof compactMessages>[0][number]++const big = (n: number) => 'x'.repeat(n)++/** One hermes round: the assistant asks, the user carries the result back. */+const hermesRound = (tool: string, resultSize = 1200): Msg[] => [+ {+ role: 'assistant',+ content: `<tool_call>\n{"name": "${tool}", "arguments": {"path": "src/math.js", "name": "inner-key-that-must-not-win"}}\n</tool_call>`,+ } as Msg,+ { role: 'user', content: `<tool_response>\n${big(resultSize)}\n</tool_response>` } as Msg,+]++/** The same round on the native transport. */+const nativeRound = (tool: string, resultSize = 1200): Msg[] => [+ { role: 'assistant', content: '', tool_calls: [{ function: { name: tool } }] } as unknown as Msg,+ { role: 'tool', content: big(resultSize) } as Msg,+]++const PLAN_TOOLS = [+ 'todo_write', 'get_current_time', 'system_info', 'process_list', 'file_list',+ 'file_read', 'file_search', 'file_write', 'file_edit', 'shell_execute',+ 'run_tests', 'code_execute', 'project_init', 'git_status', 'git_diff',+ 'git_commit', 'git_log',+]++const buildRun = (round: (t: string, n?: number) => Msg[]): Msg[] => [+ { role: 'system', content: 'You are a function calling AI model. ' + big(4000) } as Msg,+ { role: 'user', content: 'Work through this plan: 1. todo_write 2. get_current_time 3. …' } as Msg,+ ...PLAN_TOOLS.flatMap((t) => round(t)),+]++const noticeOf = (msgs: Msg[]): string => {+ const n = msgs.find(+ (m) => m.role === 'system' && typeof m.content === 'string' && m.content.startsWith('['),+ )+ return n && typeof n.content === 'string' ? n.content : ''+}++describe('the trim notice carries the trail of what already ran', () => {+ it('hermes: it names the dropped calls in order', () => {+ const out = compactMessages(buildRun(hermesRound), 3000)+ const notice = noticeOf(out)+ expect(notice).toContain('Already done in this run, in order')+ expect(notice).toMatch(/todo_write, get_current_time, system_info, process_list, file_list/)+ })++ it('native: same trail from tool_calls', () => {+ const out = compactMessages(buildRun(nativeRound), 3000)+ expect(noticeOf(out)).toMatch(/todo_write, get_current_time, system_info/)+ })++ it('it says outright not to start over, which is the failure it prevents', () => {+ const notice = noticeOf(compactMessages(buildRun(hermesRound), 3000))+ expect(notice).toMatch(/do not start the task again from the beginning/i)+ })++ it('a "name" inside the ARGUMENTS never wins over the tool name', () => {+ const notice = noticeOf(compactMessages(buildRun(hermesRound), 3000))+ expect(notice).not.toContain('inner-key-that-must-not-win')+ })++ it('the anti-re-read wording from the earlier fix survives', () => {+ const notice = noticeOf(compactMessages(buildRun(hermesRound), 3000))+ expect(notice).toMatch(/never repeat a call that already ran/)+ })++ it('a very long trail is bounded and says so instead of silently cutting', () => {+ const many = [+ { role: 'system', content: 'sys ' + big(4000) } as Msg,+ { role: 'user', content: 'the plan' } as Msg,+ ...Array.from({ length: 60 }, (_, i) => hermesRound(`tool_${i}`)).flat(),+ ]+ const out = compactMessages(many, 3000)+ const notice = noticeOf(out)+ expect(notice).toMatch(/\d+ earlier calls omitted/)+ // The trail covers the DROPPED calls and stops there. The newest rounds+ // are not in it because they are still in the window verbatim, which is+ // the whole point: the notice fills the gap, it does not duplicate what+ // the model can already read.+ expect(notice).toContain('tool_54')+ expect(notice).not.toContain('tool_59')+ const kept = JSON.stringify(out.filter((m) => m.role !== 'system'))+ expect(kept).toContain('tool_59')+ })+})++describe('what must not change', () => {+ it('NEGATIVE CONTROL: nothing was dropped, so there is no notice and no trail', () => {+ const short: Msg[] = [+ { role: 'system', content: 'sys' } as Msg,+ { role: 'user', content: 'hi' } as Msg,+ ...hermesRound('file_list', 10),+ ]+ const out = compactMessages(short, 100000)+ expect(out).toEqual(short)+ expect(noticeOf(out)).toBe('')+ })++ it('the task itself is still pinned, that fix is not undone', () => {+ const out = compactMessages(buildRun(hermesRound), 3000)+ const user = out.find((m) => m.role === 'user' && typeof m.content === 'string' && m.content.includes('Work through this plan'))+ expect(user).toBeTruthy()+ })++ it('the system prompt is still first', () => {+ const out = compactMessages(buildRun(hermesRound), 3000)+ expect(out[0].role).toBe('system')+ expect(out[0].content).toContain('function calling AI model')+ })+})diff --git a/src/lib/__tests__/loop-guard-failing-rounds.test.ts b/src/lib/__tests__/loop-guard-failing-rounds.test.tsnew file mode 100644index 00000000..73e4f9e3--- /dev/null+++ b/src/lib/__tests__/loop-guard-failing-rounds.test.ts@@ -0,0 +1,213 @@+/**+ * A run of rounds that only ever fail is a stall, and nothing caught it.+ *+ * Measured on the installed 2.6.2 Windows build, Coding surface, Ollama with+ * the hermes schema, 2026-08-06. One git command failed with "dubious+ * ownership" and the model then fired 18 shell_execute calls in a row trying+ * to repair file permissions, alternating between two spellings:+ *+ * icacls "…\lu-matrix-sandbox" /grant Everyone=RX+ * icacls "…\lu-matrix-sandbox" /grant Everyone=R,X+ * icacls "…\lu-matrix-sandbox" /grant Everyone=(RX)+ * …+ *+ * Six minutes of a nine-minute run, and the plan never got past step 19.+ *+ * Why the four existing detectors all missed it:+ * 1 needs three byte-identical batches BACK TO BACK, the spelling wobbled+ * 2 and 3 are scoped to READ_ONLY_TOOLS, and shell_execute is not one+ * 4 needs byte-identical narration, and the thinking text differed each time+ *+ * The signal they all lack is the result. A failing command changes nothing,+ * so the next round starts where the last one did.+ *+ * Run: npx vitest run src/lib/__tests__/loop-guard-failing-rounds.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++import { AgentLoopGuard } from '../agent-loop-guard'++const read = (p: string) =>+ readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), p), 'utf8')++const fail = (name = 'shell_execute', error = 'Access is denied.') => [{ name, failed: true, error }]+const ok = (name = 'shell_execute') => [{ name, failed: false }]++describe('the icacls run from the R26 measurement', () => {+ // The real argument sequence, so the test fails if someone ever makes the+ // detector depend on the arguments again.+ const REAL_ARGS = [+ 'icacls C:\\\\…\\\\lu-matrix-sandbox /grant Everyone=F',+ 'icacls C:\\\\…\\\\lu-matrix-sandbox /grant Everyone=(RX)',+ 'icacls "C:\\\\…\\\\lu-matrix-sandbox" /grant Everyone=RX',+ 'icacls "C:\\\\…\\\\lu-matrix-sandbox" /grant Everyone=R,X',+ 'icacls "C:\\\\…\\\\lu-matrix-sandbox" /grant Everyone=(RX)',+ 'icacls "C:\\\\…\\\\lu-matrix-sandbox" /grant Everyone=R,X',+ ]++ it('NEGATIVE CONTROL: the call-shape detectors never fire on it', () => {+ const g = new AgentLoopGuard()+ for (const args of REAL_ARGS) {+ expect(g.recordBatch([{ name: 'shell_execute', args }]).action).toBe('ok')+ }+ })++ it('but the result detector halts on the sixth failing round', () => {+ const g = new AgentLoopGuard()+ const verdicts = REAL_ARGS.map((args) => {+ g.recordBatch([{ name: 'shell_execute', args }])+ return g.recordResults(fail())+ })+ expect(verdicts.slice(0, 2).map((v) => v.action)).toEqual(['ok', 'ok'])+ expect(verdicts[2].action).toBe('steer')+ expect(verdicts[3].action).toBe('ok')+ expect(verdicts[4].action).toBe('ok')+ expect(verdicts[5].action).toBe('halt')+ expect(verdicts[5].action === 'halt' && verdicts[5].reason).toMatch(/6 rounds in a row/)+ })++ it('the steer quotes the error instead of just scolding', () => {+ const g = new AgentLoopGuard()+ g.recordResults(fail())+ g.recordResults(fail())+ const v = g.recordResults(fail('shell_execute', 'detected dubious ownership in repository'))+ expect(v.action).toBe('steer')+ expect(v.action === 'steer' && v.message).toMatch(/dubious ownership/)+ expect(v.action === 'steer' && v.message).toMatch(/move on to the next step/)+ })+})++describe('what it must NOT punish', () => {+ it('edit, test, edit, test survives even when every test fails', () => {+ const g = new AgentLoopGuard()+ for (let i = 0; i < 10; i++) {+ expect(g.recordResults(ok('file_edit')).action).toBe('ok')+ expect(g.recordResults(fail('run_tests', 'AssertionError')).action).toBe('ok')+ }+ })++ it('a model that fixes its command on the third try is never halted', () => {+ const g = new AgentLoopGuard()+ expect(g.recordResults(fail()).action).toBe('ok')+ expect(g.recordResults(fail()).action).toBe('ok')+ expect(g.recordResults(fail()).action).toBe('steer')+ expect(g.recordResults(ok()).action).toBe('ok')+ // and the budget is fully restored, not merely reduced+ expect(g.recordResults(fail()).action).toBe('ok')+ expect(g.recordResults(fail()).action).toBe('ok')+ expect(g.recordResults(fail()).action).toBe('steer')+ })++ it('a batch where one of several calls succeeded is progress', () => {+ const g = new AgentLoopGuard()+ for (let i = 0; i < 8; i++) {+ const v = g.recordResults([+ { name: 'shell_execute', failed: true, error: 'nope' },+ { name: 'file_read', failed: false },+ ])+ expect(v.action).toBe('ok')+ }+ })++ it('an empty round says nothing either way', () => {+ expect(new AgentLoopGuard().recordResults([]).action).toBe('ok')+ })+})++// ── G36 (R18b witness, 2026-08-07) ─────────────────────────────────────────+// Detector 5 resets on ANY success in the round, and the create-vite grind+// interleaved every failing retry with a file_list that worked: 15/30 minutes+// of circling, detector 5 at zero the whole time. Detector 6 keys failures on+// the executable itself and only lets a successful MUTATION clear them.+describe('G36: variants of the same failing executable', () => {+ const shellFail = (command: string, error = 'Operation cancelled') =>+ ({ name: 'shell_execute', failed: true, error, args: { command } })+ const readOk = () => ({ name: 'file_list', failed: false })++ // The real R18b shape: every failing npm variant rides with a read success.+ const R18B_VARIANTS = [+ 'npm init vite@latest . -- --template react-ts',+ 'npm install -g create-vite',+ 'npm exec create-vite scratch/demo',+ 'npm create vite@latest scratch/demo',+ 'npm init vite@latest scratch/demo --yes',+ 'npm create-vite . --template vanilla',+ ]++ it('steers on the 3rd and halts on the 6th failing variant despite read successes', () => {+ const g = new AgentLoopGuard()+ const verdicts = R18B_VARIANTS.map((cmd) => g.recordResults([shellFail(cmd), readOk()]))+ expect(verdicts.slice(0, 2).map((v) => v.action)).toEqual(['ok', 'ok'])+ expect(verdicts[2].action).toBe('steer')+ expect(verdicts[2].action === 'steer' && verdicts[2].message).toMatch(/'npm'/)+ expect(verdicts[2].action === 'steer' && verdicts[2].message).toMatch(/MOVE ON/)+ expect(verdicts[3].action).toBe('ok')+ expect(verdicts[4].action).toBe('ok')+ expect(verdicts[5].action).toBe('halt')+ expect(verdicts[5].action === 'halt' && verdicts[5].reason).toMatch(/6 failed 'npm' commands/)+ })++ it('pools path and extension spellings into one executable', () => {+ const g = new AgentLoopGuard()+ g.recordResults([shellFail('npm ci')])+ g.recordResults([shellFail('C:\\nodejs\\npm.CMD ci')])+ const v = g.recordResults([shellFail('/usr/local/bin/npm ci')])+ expect(v.action).toBe('steer')+ })++ it('different executables keep separate streaks', () => {+ const g = new AgentLoopGuard()+ expect(g.recordResults([shellFail('npm ci'), readOk()]).action).toBe('ok')+ expect(g.recordResults([shellFail('npx create-vite'), readOk()]).action).toBe('ok')+ expect(g.recordResults([shellFail('icacls . /grant x'), readOk()]).action).toBe('ok')+ expect(g.recordResults([shellFail('npm ci -f'), readOk()]).action).toBe('ok')+ })++ it('NEGATIVE CONTROL: a retry after a real fix starts a fresh streak', () => {+ // fail, EDIT (mutation succeeded), fail, EDIT, ... is a legitimate+ // edit-test cycle on the shell runner and must never steer or halt.+ const g = new AgentLoopGuard()+ for (let i = 0; i < 10; i++) {+ expect(g.recordResults([shellFail('node --test test/')]).action).toBe('ok')+ expect(g.recordResults([{ name: 'file_edit', failed: false }]).action).toBe('ok')+ }+ })++ it('NEGATIVE CONTROL: read-only successes do NOT reset the streak', () => {+ const g = new AgentLoopGuard()+ g.recordResults([shellFail('npm ci'), { name: 'file_read', failed: false }])+ g.recordResults([shellFail('npm ci --force'), { name: 'git_status', failed: false }])+ const v = g.recordResults([shellFail('npm ci --legacy-peer-deps'), readOk()])+ expect(v.action).toBe('steer')+ })++ it('NEGATIVE CONTROL: without a command in the args the detector stays out', () => {+ // The pre-G36 no-args behaviour is untouched: interleaved read successes+ // keep detector 5 quiet and nothing else may fire.+ const g = new AgentLoopGuard()+ for (let i = 0; i < 8; i++) {+ expect(g.recordResults([{ name: 'shell_execute', failed: true, error: 'x' }, readOk()]).action).toBe('ok')+ }+ })++ it('the hooks hand the dispatched args through', () => {+ for (const f of ['../../hooks/useCodex.ts', '../../hooks/useAgentChat.ts']) {+ expect(read(f)).toMatch(/error: r\.error, args: r\.dispatchedArgs/)+ }+ })+})++describe('both agent loops feed it', () => {+ for (const f of ['../../hooks/useCodex.ts', '../../hooks/useAgentChat.ts']) {+ it(`${f.split('/').pop()} calls recordResults with the real statuses`, () => {+ const src = read(f)+ expect(src).toMatch(/loopGuard\.recordResults\(/)+ expect(src).toMatch(/failed: r\.status === 'failed'/)+ expect(src).toMatch(/failVerdict\.action === 'halt'/)+ expect(src).toMatch(/failVerdict\.action === 'steer'/)+ })+ }+})diff --git a/src/lib/__tests__/orphan-run.test.ts b/src/lib/__tests__/orphan-run.test.tsnew file mode 100644index 00000000..e6b58e11--- /dev/null+++ b/src/lib/__tests__/orphan-run.test.ts@@ -0,0 +1,59 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { isOrphanRun } from '../orphan-run'+import { useGenerationStore } from '../../stores/generationStore'++describe('G29: a run that outlived the view that started it', () => {+ beforeEach(() => {+ useGenerationStore.setState({ generating: {}, aborters: {} })+ })++ it('is orphaned when the conversation is generating but no local run accounts for it', () => {+ // The remounted hook: useState(false) twice, store flag still set by the+ // run that is still going inside the unmounted instance's closure.+ expect(isOrphanRun(true, false, false)).toBe(true)+ })++ // ── Negative controls ────────────────────────────────────────────────────+ //+ // Each of these would show a Stop button on a chat that has nothing to stop,+ // and would block the composer for a user who is free to type.++ it('a plain chat run this instance owns is not orphaned', () => {+ expect(isOrphanRun(true, true, false)).toBe(false)+ })++ it('an agent run this instance owns is not orphaned', () => {+ expect(isOrphanRun(true, false, true)).toBe(false)+ })++ it('an idle conversation is not orphaned', () => {+ expect(isOrphanRun(false, false, false)).toBe(false)+ })++ it('a run in ANOTHER conversation does not orphan the one on screen', () => {+ // storeGenerating is read for the ACTIVE conversation, so a turn in flight+ // elsewhere reads false here even though the hook's global flag is true.+ expect(isOrphanRun(false, true, false)).toBe(false)+ })++ it('the way back works: Stop reaches the old run through the store', () => {+ const abortTheOldRun = vi.fn()+ // What sendAgentMessage registered before the view unmounted.+ useGenerationStore.getState().setGenerating('conv-1', true)+ useGenerationStore.getState().registerAborter('conv-1', abortTheOldRun)++ expect(isOrphanRun(!!useGenerationStore.getState().generating['conv-1'], false, false)).toBe(true)++ useGenerationStore.getState().abortConversation('conv-1')++ expect(abortTheOldRun).toHaveBeenCalledTimes(1)+ expect(useGenerationStore.getState().generating['conv-1']).toBeUndefined()+ expect(useGenerationStore.getState().aborters['conv-1']).toBeUndefined()+ })++ it('Stop still clears the flag when the run left no aborter behind', () => {+ useGenerationStore.getState().setGenerating('conv-2', true)+ useGenerationStore.getState().abortConversation('conv-2')+ expect(useGenerationStore.getState().generating['conv-2']).toBeUndefined()+ })+})diff --git a/src/lib/__tests__/plan-reconcile.test.ts b/src/lib/__tests__/plan-reconcile.test.tsnew file mode 100644index 00000000..d816f61c--- /dev/null+++ b/src/lib/__tests__/plan-reconcile.test.ts@@ -0,0 +1,89 @@+/**+ * A completion claim that contradicts the plan must not end the run.+ *+ * Measured on R31 (gpt-oss-120b, Coding, LU Cloud, 2026-08-07): the model+ * wrote "All steps completed as requested" while its own todo list, rendered+ * live in the PlanBar, read PLAN 13/30. The loop agreed and ended the run 17+ * steps early. The plan length and the current step are client-side state, so+ * the contradiction is detectable without asking the model anything.+ *+ * Run: npx vitest run src/lib/__tests__/plan-reconcile.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++import { openPlanGap, planReconcileSteer, PLAN_RECONCILE_BUDGET } from '../plan-reconcile'+import type { TodoItem } from '../../stores/todoStore'++const t = (content: string, status: TodoItem['status']): TodoItem => ({ content, status })++describe('the R31 shape: finished claim, unfinished plan', () => {+ const r31 = [+ ...Array.from({ length: 13 }, (_, i) => t(`step ${i + 1}`, 'completed' as const)),+ t('Scaffold a new empty project in the subfolder scratch/demo.', 'in_progress'),+ ...Array.from({ length: 16 }, (_, i) => t(`step ${i + 15}`, 'pending' as const)),+ ]++ it('detects the gap', () => {+ expect(openPlanGap(r31)).toEqual({+ done: 13,+ total: 30,+ next: 'Scaffold a new empty project in the subfolder scratch/demo.',+ })+ })++ it('the steer names the numbers and the next step', () => {+ const msg = planReconcileSteer(openPlanGap(r31)!)+ expect(msg).toContain('13 of 30')+ expect(msg).toContain('scratch/demo')+ expect(msg).toContain('todo_write')+ })++ it('prefers the in_progress item over a later pending one', () => {+ const gap = openPlanGap([t('a', 'completed'), t('b', 'pending'), t('c', 'in_progress')])+ expect(gap?.next).toBe('c')+ })+})++describe('NEGATIVE CONTROL: legitimate endings stay endings', () => {+ it('no plan written, no steer', () => {+ expect(openPlanGap([])).toBeNull()+ })++ it('every step completed, no steer', () => {+ expect(openPlanGap([t('a', 'completed'), t('b', 'completed')])).toBeNull()+ })++ it('a single-item plan that is done, no steer', () => {+ expect(openPlanGap([t('only', 'completed')])).toBeNull()+ })++ it('the budget is small on purpose', () => {+ // Two ignored contradictions mean the model will not move; anything+ // larger only burns tokens against a stubborn model.+ expect(PLAN_RECONCILE_BUDGET).toBe(2)+ })+})++describe('both loops are wired, with their local names', () => {+ const here = dirname(fileURLToPath(import.meta.url))+ const codex = readFileSync(resolve(here, '../../hooks/useCodex.ts'), 'utf8')+ const agent = readFileSync(resolve(here, '../../hooks/useAgentChat.ts'), 'utf8')++ it('useCodex steers before break-no-toolcalls and exempts read-only turns', () => {+ expect(codex).toContain('openPlanGap(useTodoStore.getState().getTodos(convId))')+ const steerAt = codex.indexOf('planReconcileSteer(gap)')+ const breakAt = codex.indexOf("diagLog('break-no-toolcalls'")+ expect(steerAt).toBeGreaterThan(0)+ expect(steerAt).toBeLessThan(breakAt)+ expect(codex).toMatch(/!readOnlyTurn && convId && planReconcilesRemaining > 0/)+ })++ it('useAgentChat steers through agentMessages, never through `messages`', () => {+ expect(agent).toContain('agentMessages.push({ role: \'user\', content: planReconcileSteer(gap) })')+ expect(agent).not.toMatch(/\bmessages\.push\(\{ role: 'user', content: planReconcileSteer/)+ expect(agent).toMatch(/!opts\?\.readOnly && planReconcilesRemaining > 0/)+ })+})diff --git a/src/lib/__tests__/plan-staleness.test.ts b/src/lib/__tests__/plan-staleness.test.tsnew file mode 100644index 00000000..a8ff0dc7--- /dev/null+++ b/src/lib/__tests__/plan-staleness.test.ts@@ -0,0 +1,98 @@+/**+ * PlanBar lag (measured 2026-08-07): PLAN 8/31 on the bar while the model+ * narrated step 17. The bar renders only what the model reports through+ * todo_write, so when batches of real work keep landing without one, the loop+ * asks the model ONCE (budgeted) to bring its own list current. The app never+ * invents plan state.+ *+ * Run: npx vitest run src/lib/__tests__/plan-staleness.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++import {+ PlanStaleness,+ planStalenessSteer,+ PLAN_STALE_BATCHES,+ PLAN_STALE_STEER_BUDGET,+} from '../plan-staleness'++const here = dirname(fileURLToPath(import.meta.url))+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')++const work = ['file_write', 'shell_execute']++describe('PlanStaleness', () => {+ it('fires after enough silent batches, then re-arms only after another stretch', () => {+ const s = new PlanStaleness()+ expect(s.recordBatch(work, true)).toBe(false)+ expect(s.recordBatch(work, true)).toBe(false)+ expect(s.recordBatch(work, true)).toBe(true)+ // counter reset: the very next batch is not stale again+ expect(s.recordBatch(work, true)).toBe(false)+ expect(s.recordBatch(work, true)).toBe(false)+ expect(s.recordBatch(work, true)).toBe(true)+ // budget of 2 is spent: silence forever after+ for (let i = 0; i < 10; i++) expect(s.recordBatch(work, true)).toBe(false)+ expect(PLAN_STALE_STEER_BUDGET).toBe(2)+ expect(PLAN_STALE_BATCHES).toBe(3)+ })++ it('NEGATIVE CONTROL: a todo_write in the batch resets the clock', () => {+ const s = new PlanStaleness()+ s.recordBatch(work, true)+ s.recordBatch(work, true)+ expect(s.recordBatch([...work, 'todo_write'], true)).toBe(false)+ // the two silent batches before the update no longer count+ expect(s.recordBatch(work, true)).toBe(false)+ expect(s.recordBatch(work, true)).toBe(false)+ expect(s.recordBatch(work, true)).toBe(true)+ })++ it('NEGATIVE CONTROL: no plan, no nagging, ever', () => {+ const s = new PlanStaleness()+ for (let i = 0; i < 10; i++) expect(s.recordBatch(work, false)).toBe(false)+ // a plan appearing later starts a FRESH count+ expect(s.recordBatch(work, true)).toBe(false)+ })++ it('NEGATIVE CONTROL: empty batches (no executed tools) do not accumulate', () => {+ const s = new PlanStaleness()+ for (let i = 0; i < 10; i++) expect(s.recordBatch([], true)).toBe(false)+ })++ it('the steer asks the model to report, never claims progress itself', () => {+ const msg = planStalenessSteer({ done: 8, total: 31, next: 'run the tests' })+ expect(msg).toContain('8 of 31')+ expect(msg).toContain('todo_write')+ expect(msg).toContain('"run the tests"')+ // it must not assert that any step IS done; the model decides that+ expect(msg).not.toMatch(/step \d+ is (now )?completed/i)+ })+})++describe('wiring in both loops', () => {+ it('Agent and Codex each own one tracker per run and steer after the batch', () => {+ for (const f of ['../../hooks/useAgentChat.ts', '../../hooks/useCodex.ts']) {+ const src = read(f)+ expect(src, f).toContain('const planStaleness = new PlanStaleness()')+ expect(src, f).toContain('planStaleness.recordBatch(')+ expect(src, f).toContain('planStalenessSteer(staleGap)')+ }+ })++ it('the steer rides the run transcript: agentMessages in Agent, messages in Codex', () => {+ expect(read('../../hooks/useAgentChat.ts')).toContain("agentMessages.push({ role: 'user', content: planStalenessSteer(staleGap) })")+ expect(read('../../hooks/useCodex.ts')).toContain("messages.push({ role: 'user', content: planStalenessSteer(staleGap) })")+ })++ it('NEGATIVE CONTROL: the G16 finish-time reconcile keeps its own budget', () => {+ for (const f of ['../../hooks/useAgentChat.ts', '../../hooks/useCodex.ts']) {+ const src = read(f)+ expect(src, f).toContain('planReconcilesRemaining = PLAN_RECONCILE_BUDGET')+ expect(src, f).toContain('planReconcileSteer(gap)')+ }+ })+})diff --git a/src/lib/__tests__/reasoning-round.test.ts b/src/lib/__tests__/reasoning-round.test.tsnew file mode 100644index 00000000..87cc5e0b--- /dev/null+++ b/src/lib/__tests__/reasoning-round.test.ts@@ -0,0 +1,69 @@+/**+ * A reasoning-only round must continue the run, not end it.+ *+ * R17 (Agent, Ollama, Qwen3-4B, 2026-08-07): step 1 of 31 fired, the next+ * round was all thought (the Qwen3 template puts the opening think tag in the+ * PROMPT, so whole rounds arrive as thinking), and the loop ended the run+ * with a stand-in sentence telling the USER to rephrase. The correct actor+ * was the LOOP, and the correct action was to continue.+ *+ * Run: npx vitest run src/lib/__tests__/reasoning-round.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++import { reasoningOnlyRound, REASONING_CONTINUE_BUDGET, REASONING_CONTINUE_STEER } from '../reasoning-round'++describe('the R17 shape', () => {+ it('thought, no words, no call: reasoning-only', () => {+ expect(reasoningOnlyRound('', 'I should now work through step 2 of the plan…')).toBe(true)+ })++ it('whitespace content is still reasoning-only', () => {+ expect(reasoningOnlyRound(' \n', 'planning…')).toBe(true)+ })+})++describe('NEGATIVE CONTROL: real endings stay endings', () => {+ it('an actual answer ends the run', () => {+ expect(reasoningOnlyRound('All 30 steps are done, results above.', 'final check…')).toBe(false)+ })++ it('an empty round with NO thinking is a dud, not a reasoning round', () => {+ // That case belongs to the dud-turn retry, not to this steer.+ expect(reasoningOnlyRound('', '')).toBe(false)+ })++ it('the budget is small on purpose', () => {+ expect(REASONING_CONTINUE_BUDGET).toBe(2)+ })++ it('the steer offers BOTH exits, act or answer, so a finished model is not trapped', () => {+ expect(REASONING_CONTINUE_STEER).toContain('tool call')+ expect(REASONING_CONTINUE_STEER).toContain('final answer')+ })+})++describe('the agent loop is wired in the right order', () => {+ const src = readFileSync(+ resolve(dirname(fileURLToPath(import.meta.url)), '../../hooks/useAgentChat.ts'),+ 'utf8',+ )++ it('fires only after work started, inside the final-turn block', () => {+ expect(src).toMatch(/executedCallKeys\.size > 0 &&\s*\n\s*reasoningContinuesRemaining > 0 &&\s*\n\s*reasoningOnlyRound\(turnContent, turnThinking\)/)+ })++ it('the G16 plan reconcile stays ahead of it', () => {+ const g16 = src.indexOf('planReconcileSteer(gap)')+ const g17 = src.indexOf("content: REASONING_CONTINUE_STEER")+ expect(g16).toBeGreaterThan(0)+ expect(g17).toBeGreaterThan(g16)+ })++ it('steers through agentMessages, the array this hook actually has', () => {+ expect(src).toContain("agentMessages.push({ role: 'user', content: REASONING_CONTINUE_STEER })")+ })+})diff --git a/src/lib/__tests__/render-budget.test.ts b/src/lib/__tests__/render-budget.test.tsnew file mode 100644index 00000000..1b0587c2--- /dev/null+++ b/src/lib/__tests__/render-budget.test.ts@@ -0,0 +1,157 @@+/**+ * Render budget for agent-triggered generations (G19-1, R32 witness 2026-08-07):+ * the app queued a 30 to 60 minute Wan render inside an interactive run, polled+ * it 354 times with nothing on screen, and the timeout would have walked away+ * leaving the job burning the GPU. The pace tracker projects the sampling pass+ * off ComfyUI's own progress events and gives up early, cancelling the job.+ *+ * Run: npx vitest run src/lib/__tests__/render-budget.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++import {+ PaceTracker,+ overBudget,+ renderBudgetNotice,+ renderTimeoutNotice,+ warmupExceeded,+ swapWarmupNotice,+ MIN_STEPS_FOR_VERDICT,+ HOPELESS_FACTOR,+ SWAP_WARMUP_BUDGET_MS,+} from '../render-budget'++const here = dirname(fileURLToPath(import.meta.url))+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')++describe('PaceTracker projection', () => {+ it('projects the R32 case: 30 steps at 80s each is a 40 minute job', () => {+ const t = new PaceTracker()+ // first tick anchors, three more ticks give a measurable pace+ t.tick(1, 30, 0)+ t.tick(2, 30, 80_000)+ t.tick(3, 30, 160_000)+ t.tick(4, 30, 240_000)+ expect(t.projectedTotalMs()).toBe(30 * 80_000)+ })++ it('NEGATIVE CONTROL: stays silent before enough steps are in', () => {+ const t = new PaceTracker()+ t.tick(1, 30, 0)+ t.tick(2, 30, 80_000)+ expect(t.projectedTotalMs()).toBeNull()+ // and a tracker that never saw a tick (no WS) never judges+ expect(new PaceTracker().projectedTotalMs()).toBeNull()+ })++ it('re-anchors when a second sampler pass starts (value moves backwards)', () => {+ const t = new PaceTracker()+ t.tick(28, 30, 0)+ t.tick(30, 30, 4_000)+ t.tick(1, 30, 10_000)+ t.tick(2, 30, 12_000)+ t.tick(3, 30, 14_000)+ t.tick(4, 30, 16_000)+ // pace comes from the NEW pass (2s per step), not the stale anchor+ expect(t.projectedTotalMs()).toBe(30 * 2_000)+ })+})++describe('the verdict', () => {+ it('a hopeless projection is over budget, a close one is not', () => {+ const budget = 10 * 60_000+ expect(overBudget(40 * 60_000, budget)).toBe(true)+ // NEGATIVE CONTROL: a render that lands a LITTLE late gets to finish+ expect(overBudget(11 * 60_000, budget)).toBe(false)+ expect(overBudget(null, budget)).toBe(false)+ expect(HOPELESS_FACTOR).toBeGreaterThan(1)+ expect(MIN_STEPS_FOR_VERDICT).toBeGreaterThanOrEqual(2)+ })++ it('both notices are honest and actionable, without inventing model prose', () => {+ const early = renderBudgetNotice('Video', 40 * 60_000, 10 * 60_000)+ expect(early).toContain('about 40 minutes')+ expect(early).toContain('10 minute budget')+ expect(early).toContain('cancelled')+ const flat = renderTimeoutNotice('Video', 10 * 60_000)+ expect(flat).toContain('10 minute budget')+ for (const msg of [early, flat]) {+ expect(msg).toContain('Settings')+ expect(msg).toMatch(/^Video generation/)+ }+ })+})++describe('the warm-up budget (G24, R17c witness)', () => {+ it('R17c: WS alive, nothing on the GPU ever progressed, budget spent, job dies', () => {+ expect(warmupExceeded(false, true, SWAP_WARMUP_BUDGET_MS + 1)).toBe(true)+ })++ it('the budget sits well above the promised 30 to 90 s swap', () => {+ expect(SWAP_WARMUP_BUDGET_MS).toBeGreaterThanOrEqual(3 * 60_000)+ })++ it('NEGATIVE CONTROL: without a WS we stay blind, only the flat deadline applies', () => {+ expect(warmupExceeded(false, false, SWAP_WARMUP_BUDGET_MS * 10)).toBe(false)+ })++ it('NEGATIVE CONTROL: a slow load that is still inside the budget gets to finish', () => {+ expect(warmupExceeded(false, true, SWAP_WARMUP_BUDGET_MS - 1)).toBe(false)+ })++ it('NEGATIVE CONTROL: progress on ANY prompt means busy, not wedged, no kill', () => {+ // A healthy job queued behind another client's render must not be punished.+ expect(warmupExceeded(true, true, SWAP_WARMUP_BUDGET_MS * 10)).toBe(false)+ })++ it('the notice says what was observed and how to get out of it', () => {+ const msg = swapWarmupNotice('Video', 5 * 60_000)+ expect(msg).toContain('5 minutes')+ expect(msg).toContain('still loading into VRAM')+ expect(msg).toContain('cancelled')+ expect(msg).toContain('Settings')+ expect(msg).toMatch(/^Video generation/)+ })+})++describe('wiring in the poll loop', () => {+ const handoff = read('../../api/vram-handoff.ts')++ it('the poll loop feeds progress events into the tracker and checks the budget', () => {+ expect(handoff).toContain("if (ev.type === 'progress') {")+ expect(handoff).toContain('pace.tick(ev.data.value, ev.data.max, Date.now())')+ expect(handoff).toContain('if (overBudget(projected, timeoutMs))')+ })++ it('ALL THREE exits abandon the job instead of orphaning it', () => {+ // pace verdict, warm-up verdict (G24), flat deadline+ expect(handoff.match(/await abandonPrompt\(promptId\)/g)?.length).toBe(3)+ expect(handoff).not.toContain('generation timed out after')+ })++ it('G24: the loop tracks warm-up with ANY-prompt progress and the live WS state', () => {+ expect(handoff).toContain('sawAnyProgress = true')+ expect(handoff).toContain('warmupExceeded(sawAnyProgress, comfyWS.connected, warmupElapsed)')+ // own-prompt ticks still feed the pace tracker underneath the any-progress flag+ expect(handoff).toContain("if (ev.data.prompt_id === promptId) {")+ })++ it('the WS listener is always released', () => {+ expect(handoff).toContain('offProgress()')+ })++ it('abandonPrompt kills only OUR job: pending delete first, interrupt only if ours runs', () => {+ const comfy = read('../../api/comfyui.ts')+ const fn = comfy.slice(comfy.indexOf('export async function abandonPrompt'))+ expect(fn.indexOf('delete: [promptId]')).toBeGreaterThan(-1)+ expect(fn.indexOf('delete: [promptId]')).toBeLessThan(fn.indexOf('cancelGeneration()'))+ expect(fn).toContain('if (running) await cancelGeneration()')+ })++ it('NEGATIVE CONTROL: the user cancel path is untouched', () => {+ expect(handoff).toContain('if (_genCancelRequested) return `${kindLabel} generation cancelled.`')+ })+})diff --git a/src/lib/__tests__/run-idle.test.ts b/src/lib/__tests__/run-idle.test.tsnew file mode 100644index 00000000..b081597f--- /dev/null+++ b/src/lib/__tests__/run-idle.test.ts@@ -0,0 +1,106 @@+/**+ * The backend selector never opens over a running run (G25, R17c witness+ * 2026-08-07): detection resolved seconds after startup, the agent run was+ * already streaming, and the "Multiple backends running" modal stood over the+ * chat for the rest of the 20 minute run.+ *+ * Run: npx vitest run src/lib/__tests__/run-idle.test.ts+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++import { anyRunActive, whenRunsIdle } from '../run-idle'+import { useGenerationStore } from '../../stores/generationStore'+import { useCodexStore } from '../../stores/codexStore'++const here = dirname(fileURLToPath(import.meta.url))+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')++describe('anyRunActive', () => {+ it('a generating chat/agent conversation counts as active', () => {+ expect(anyRunActive({ 'conv-1': true }, {})).toBe(true)+ })++ it('a running coding thread counts as active', () => {+ expect(anyRunActive({}, { 'conv-1': { status: 'running' } })).toBe(true)+ })++ it('NEGATIVE CONTROL: idle and errored threads do not block', () => {+ expect(anyRunActive({}, {})).toBe(false)+ expect(anyRunActive({}, { a: { status: 'idle' }, b: { status: 'error' } })).toBe(false)+ })+})++describe('whenRunsIdle against the real stores', () => {+ beforeEach(() => {+ // Reset both stores to a clean idle state.+ useGenerationStore.setState({ generating: {}, aborters: {} })+ useCodexStore.setState({ threads: {} })+ })++ it('idle → shows immediately', () => {+ let shown = 0+ whenRunsIdle(() => shown++)+ expect(shown).toBe(1)+ })++ it('R17c: an active agent run defers the dialog until the run ends', () => {+ useGenerationStore.getState().setGenerating('conv-1', true)+ let shown = 0+ whenRunsIdle(() => shown++)+ expect(shown).toBe(0)+ useGenerationStore.getState().setGenerating('conv-1', false)+ expect(shown).toBe(1)+ })++ it('a coding run defers it too, and it fires exactly once', () => {+ useCodexStore.getState().initThread('conv-c', '/tmp')+ useCodexStore.getState().setThreadStatus('conv-c', 'running')+ let shown = 0+ whenRunsIdle(() => shown++)+ expect(shown).toBe(0)+ useCodexStore.getState().setThreadStatus('conv-c', 'idle')+ expect(shown).toBe(1)+ // Further store churn must not re-fire the deferred show.+ useCodexStore.getState().setThreadStatus('conv-c', 'running')+ useCodexStore.getState().setThreadStatus('conv-c', 'idle')+ expect(shown).toBe(1)+ })++ it('waits for BOTH surfaces when both are busy', () => {+ useGenerationStore.getState().setGenerating('conv-1', true)+ useCodexStore.getState().initThread('conv-c', '/tmp')+ useCodexStore.getState().setThreadStatus('conv-c', 'running')+ let shown = 0+ whenRunsIdle(() => shown++)+ useGenerationStore.getState().setGenerating('conv-1', false)+ expect(shown).toBe(0)+ useCodexStore.getState().setThreadStatus('conv-c', 'idle')+ expect(shown).toBe(1)+ })++ it('NEGATIVE CONTROL: cancel withdraws a deferred show without firing it', () => {+ useGenerationStore.getState().setGenerating('conv-1', true)+ let shown = 0+ const cancel = whenRunsIdle(() => shown++)+ cancel()+ useGenerationStore.getState().setGenerating('conv-1', false)+ expect(shown).toBe(0)+ })+})++describe('wiring in AppShell', () => {+ const shell = read('../../components/layout/AppShell.tsx')++ it('the selector opens through the idle gate, never directly', () => {+ expect(shell).toContain('whenRunsIdle(() => {')+ const gated = shell.indexOf('whenRunsIdle(() => {')+ expect(shell.indexOf('setShowSelector(true)', gated)).toBeGreaterThan(gated)+ })++ it('NEGATIVE CONTROL: closing the dialog stays an immediate action', () => {+ expect(shell).toContain('onClose={() => setShowSelector(false)}')+ })+})diff --git a/src/lib/__tests__/turn-summary.test.ts b/src/lib/__tests__/turn-summary.test.tsindex 522874d9..f26ab27d 100644--- a/src/lib/__tests__/turn-summary.test.ts+++ b/src/lib/__tests__/turn-summary.test.ts@@ -117,3 +117,101 @@ describe('summarizeTurn', () => {})})})++// G27, witnessed on the fresh Mac build 2026-08-07 (R01b): the run stopped+// after three of thirty-one steps and the closing line read "Task completed:+// 3 operations completed." while the PlanBar right beside it read 1 of 31.+// The G16 reconcile steers the MODEL, with a budget of two; when that budget+// is spent the run ends anyway, and THIS function writes the sentence the+// user is left with.+describe('an open plan outranks a cheerful ending (G27)', () => {+ const threeOk: TurnToolCall[] = [+ { toolName: 'todo_write', status: 'completed' },+ { toolName: 'get_current_time', status: 'completed' },+ { toolName: 'system_info', status: 'completed' },+ ]+ const gap = { done: 1, total: 31, next: 'Use system_info to report the operating system' }++ it('R01b: never says completed while the plan says 1 of 31', () => {+ const text = summarizeTurn({+ calls: threeOk, imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false, planGap: gap,+ })+ expect(text).not.toContain('Task completed')+ expect(text).toContain('1 of 31')+ expect(text).toContain('Use system_info to report the operating system')+ expect(text).toContain('continue')+ })++ it('a picture that landed is still reported, with the caveat', () => {+ const text = summarizeTurn({+ calls: threeOk, imageGenDone: 1, videoGenDone: 0, visionFeedbackGiven: true, planGap: gap,+ })+ expect(text).toContain('your image is above')+ expect(text).toContain('1 of 31')+ })++ it('NEGATIVE CONTROL: no plan at all leaves every wording untouched', () => {+ const text = summarizeTurn({+ calls: threeOk, imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false, planGap: null,+ })+ expect(text).toBe('Task completed: 3 operations completed.')+ // omitting the field entirely behaves the same as passing null+ expect(summarizeTurn({+ calls: threeOk, imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false,+ })).toBe(text)+ })++ it('NEGATIVE CONTROL: a FINISHED plan is not a gap, so the run may say completed', () => {+ // openPlanGap returns null once every item is done; this asserts the+ // contract from this side, so a future caller cannot pass a done plan in.+ const text = summarizeTurn({+ calls: threeOk, imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false, planGap: null,+ })+ expect(text).toContain('Task completed')+ })++ it('NEGATIVE CONTROL: a failed picture still explains itself, plan or not', () => {+ const text = summarizeTurn({+ calls: [failedImage('Image generation failed: ComfyUI rejected workflow: 400 Bad Request')],+ imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false, planGap: null,+ })+ expect(text).toContain('400 Bad Request')+ })+})++// The plan note is a SUFFIX, never a replacement. Written after the first cut+// of the G27 fix returned the note ALONE for a failed picture, which would+// have re-opened D#81 (the user sees "the run stopped" and never learns the+// generation failed or why).+describe('G27 must not eat the D#81 explanation', () => {+ const gap = { done: 2, total: 10, next: 'Use video_generate for a two second clip' }++ it('a failed picture keeps its reason AND gains the plan note', () => {+ const text = summarizeTurn({+ calls: [failedImage('Image generation failed: ComfyUI rejected workflow: 400 Bad Request')],+ imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false, planGap: gap,+ })+ expect(text).toContain('400 Bad Request')+ expect(text).toContain('did not come out')+ expect(text).toContain('2 of 10')+ })++ it('a picture that landed but was not fed back still surfaces the open plan', () => {+ // Without a plan this case returns '' on purpose (the block shows the+ // picture). With one, the note is the only thing worth saying.+ const text = summarizeTurn({+ calls: [], imageGenDone: 1, videoGenDone: 0, visionFeedbackGiven: false, planGap: gap,+ })+ expect(text).toContain('2 of 10')+ expect(summarizeTurn({+ calls: [], imageGenDone: 1, videoGenDone: 0, visionFeedbackGiven: false, planGap: null,+ })).toBe('')+ })++ it('NEGATIVE CONTROL: nothing ran at all, plan open, the hint is not lost', () => {+ const text = summarizeTurn({+ calls: [], imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false, planGap: gap,+ })+ expect(text).toContain('2 of 10')+ })+})diff --git a/src/lib/agent-loop-guard.ts b/src/lib/agent-loop-guard.tsindex 0b4c906e..fce02e5a 100644--- a/src/lib/agent-loop-guard.ts+++ b/src/lib/agent-loop-guard.ts@@ -30,6 +30,27 @@* 4. Repeated narration: the model emitting the same non-trivial text 3×* in a row ("Let me check the rotation engine…") halts even when its* tool calls vary enough to dodge 1-3.+ *+ * 5. Rounds that only ever fail: detectors 1-4 look at what the model ASKED+ * for, never at what came back, and 2-3 are scoped to reads because a+ * side-effecting call may legitimately repeat. A shell command that FAILS+ * changes nothing, so a run of failing rounds with no success in between+ * is a stall no matter how the arguments wobble. Found on the installed+ * 2.6.2 build, Coding + Ollama + hermes: after one git error the model+ * fired 18 `icacls` calls in a row, alternating `Everyone=RX` and+ * `Everyone=R,X`. Detector 1 never saw three identical in a row, and 2 and+ * 3 skip shell entirely, so six minutes of the run burned untouched.+ *+ * 6. Variants of the same failing executable (G36, R18b witness 2026-08-07):+ * detector 5 resets the moment ANY call in the round succeeds, and a+ * model grinding on create-vite interleaved every retry with a file_list+ * that worked, so 15/30 circling minutes never tripped it. This detector+ * counts consecutive FAILURES per executable (first token of the shell+ * command, path and .exe/.cmd stripped, so `npm init vite@latest` and+ * `C:\nodejs\npm.cmd install -g create-vite` pool into one streak). Only+ * a successful MUTATING call resets the streaks, because only a mutation+ * can change what the retry will find; a read-only success proves+ * nothing. Steer at 3 per executable, halt at 6.*/export type LoopGuardVerdict =@@ -45,6 +66,37 @@ const READ_HALT_AT = 5const NARRATION_HALT_AT = 3/** Ignore trivial repeated lines ("Done.", "ok") — too easy to hit honestly. */const MIN_NARRATION_LEN = 12+/**+ * Failing rounds in a row, no success of any kind in between. Three is still+ * plausible probing (wrong flag, wrong quoting, wrong path), so that only+ * steers. Six is a model that has stopped reading its own error.+ */+const FAIL_STEER_AT = 3+const FAIL_HALT_AT = 6+/**+ * Consecutive failures of the SAME executable (detector 6). Three variants of+ * one command all failing is a model that argues with an error instead of+ * reading it; six is a stall. Matches detector 5's ladder on purpose.+ */+const EXEC_FAIL_STEER_AT = 3+const EXEC_FAIL_HALT_AT = 6++/** Tools whose args carry a shell command whose first token names the work. */+const EXEC_TOOLS = new Set<string>(['shell_execute', 'shell_execute_background'])++/**+ * `npm`, from any of: `npm init vite@latest`, `C:\nodejs\npm.cmd install -g+ * create-vite`, `/usr/bin/npm ci`. Null when there is no command to key on.+ */+function execKeyOf(name: string, args?: Record<string, any>): string | null {+ if (!EXEC_TOOLS.has(name)) return null+ const command = args?.command+ if (typeof command !== 'string') return null+ const first = command.trim().split(/\s+/)[0] ?? ''+ const base = first.replace(/["']/g, '').split(/[\\/]/).pop() ?? ''+ const key = base.toLowerCase().replace(/\.(exe|cmd|bat|com)$/, '')+ return key || null+}/*** Tools whose result is a pure function of the workspace state. Only these@@ -69,6 +121,11 @@ export class AgentLoopGuard {private steeredKeys = new Set<string>()private lastNarration = ''private narrationSeen = 0+ private failingRounds = 0+ private failSteered = false+ /** Detector 6: consecutive failures per executable, reset by mutations. */+ private execFailStreaks = new Map<string, number>()+ private execSteeredKeys = new Set<string>()/*** Record one iteration's tool-call batch BEFORE executing it. `args` must@@ -141,6 +198,84 @@ export class AgentLoopGuard {return steer ?? { action: 'ok' }}+ /**+ * Record what one iteration's tools actually RETURNED, after they ran.+ *+ * A round where every call failed moved nothing: the workspace is what it+ * was, and the next round starts from the same place. One success of any+ * kind clears the count, so edit → test → edit → test is never touched, and+ * neither is a model that fixes its command on the second or third try.+ */+ recordResults(+ results: Array<{ name: string; failed: boolean; error?: string; args?: Record<string, any> }>,+ ): LoopGuardVerdict {+ if (results.length === 0) return { action: 'ok' }++ // ── Detector 6: per-executable failure streaks ──+ // The reset runs BEFORE this round's failures are counted, so a retry+ // that follows a real fix (a successful file_edit, a successful other+ // command) starts a fresh streak. Read-only successes keep the streaks:+ // listing the directory again does not change what the retry will find.+ if (results.some((r) => !r.failed && !READ_ONLY_TOOLS.has(r.name))) {+ this.execFailStreaks.clear()+ }+ let execSteer: LoopGuardVerdict | null = null+ for (const r of results) {+ if (!r.failed) continue+ const key = execKeyOf(r.name, r.args)+ if (!key) continue+ const n = (this.execFailStreaks.get(key) ?? 0) + 1+ this.execFailStreaks.set(key, n)+ if (n >= EXEC_FAIL_HALT_AT) {+ return {+ action: 'halt',+ reason: `${n} failed '${key}' commands in a row with nothing changing the workspace in between`,+ }+ }+ if (n >= EXEC_FAIL_STEER_AT && !this.execSteeredKeys.has(key)) {+ this.execSteeredKeys.add(key)+ execSteer = {+ action: 'steer',+ message:+ `You have now tried ${n} variants of the '${key}' command and every attempt failed. ` ++ (r.error ? `The error is still: ${r.error.slice(0, 300)}. ` : '') ++ 'Another spelling of the same command will fail the same way. ' ++ 'Write down the exact error for this step and MOVE ON to the next step.',+ }+ }+ }++ // ── Detector 5: rounds where every call failed ──+ if (results.some((r) => !r.failed)) {+ this.failingRounds = 0+ this.failSteered = false+ return execSteer ?? { action: 'ok' }+ }++ this.failingRounds+++ const names = [...new Set(results.map((r) => r.name))].join(', ')+ if (this.failingRounds >= FAIL_HALT_AT) {+ return {+ action: 'halt',+ reason: `${this.failingRounds} rounds in a row where every tool call failed (${names}) and nothing changed in between`,+ }+ }+ if (execSteer) return execSteer+ if (this.failingRounds >= FAIL_STEER_AT && !this.failSteered) {+ this.failSteered = true+ const lastError = results.find((r) => r.error)?.error+ return {+ action: 'steer',+ message:+ `The last ${this.failingRounds} rounds all failed (${names}) and nothing in the workspace changed. ` ++ (lastError ? `The error is still: ${lastError.slice(0, 300)}. ` : '') ++ 'Retrying the same command with a slightly different spelling will not fix it. ' ++ 'Either solve the cause, or say plainly that this step cannot be done here and move on to the next step.',+ }+ }+ return { action: 'ok' }+ }+/** Record the assistant text of one iteration (before its tools run). */recordNarration(text: string): LoopGuardVerdict {const norm = text.trim().replace(/\s+/g, ' ').toLowerCase()diff --git a/src/lib/approval-queue.ts b/src/lib/approval-queue.tsnew file mode 100644index 00000000..3520ffaa--- /dev/null+++ b/src/lib/approval-queue.ts@@ -0,0 +1,91 @@+// Pending tool approvals, per conversation, at MODULE scope (G29b).+//+// Same lesson as agentLoopTimer in useAgentChat (audit A3): the chat view+// unmounts on a view switch, so anything the run needs after that point cannot+// live in a hook ref. The approval queue did, so a run that asked for approval+// after the switch pushed into the queue of the DEAD instance and told a+// component that no longer exists to show it. The remounted hook started with+// an empty queue, the user saw nothing to approve, and the run waited forever.+// G29 gave that user a Stop button back; this gives them the actual choice.+//+// Keyed by conversation because the queue outlives the view: a run continuing+// in one chat must never surface its approval in another chat the user has+// since opened.+//+// The FIFO itself is the older fix that must survive (Phase 5): parallel tool+// execution means several tools can ask in the same batch, and a single slot+// would be overwritten by the second asker, deadlocking the first.++import type { AgentToolCall } from '../types/agent-mode'++export interface ApprovalEntry {+ toolCall: AgentToolCall+ resolve: (approved: boolean) => void+}++const queues = new Map<string, ApprovalEntry[]>()+const listeners = new Set<() => void>()++function notify() {+ for (const fn of listeners) fn()+}++/** Subscribe to every queue change; returns the unsubscribe function. */+export function subscribeApprovals(fn: () => void): () => void {+ listeners.add(fn)+ return () => { listeners.delete(fn) }+}++/** The approval a conversation is currently waiting on, if any. */+export function headApproval(convId: string | null | undefined): AgentToolCall | null {+ if (!convId) return null+ return queues.get(convId)?.[0]?.toolCall ?? null+}++export function enqueueApproval(convId: string, entry: ApprovalEntry): void {+ const q = queues.get(convId)+ if (q) q.push(entry)+ else queues.set(convId, [entry])+ notify()+}++/** Take the head off and hand it back, so the caller can answer it. */+export function dequeueApproval(convId: string | null | undefined): ApprovalEntry | undefined {+ if (!convId) return undefined+ const q = queues.get(convId)+ if (!q?.length) return undefined+ const entry = q.shift()+ if (!q.length) queues.delete(convId)+ notify()+ return entry+}++/**+ * Drop one specific entry, used when its run aborts. Returns true when the+ * entry was still queued, false when a click already answered it.+ */+export function removeApproval(convId: string, entry: ApprovalEntry): boolean {+ const q = queues.get(convId)+ if (!q) return false+ const idx = q.indexOf(entry)+ if (idx < 0) return false+ q.splice(idx, 1)+ if (!q.length) queues.delete(convId)+ notify()+ return true+}++/** Answer every waiting tool with "no" and empty the queue (turn end, Stop). */+export function drainApprovals(convId: string | null | undefined): void {+ if (!convId) return+ const q = queues.get(convId)+ queues.delete(convId)+ if (q) for (const entry of q) entry.resolve(false)+ notify()+}++/** Test seam only. */+export function resetApprovals(): void {+ queues.clear()+ listeners.clear()+}diff --git a/src/lib/context-compaction.ts b/src/lib/context-compaction.tsindex ce2ceb25..b97f3083 100644--- a/src/lib/context-compaction.ts+++ b/src/lib/context-compaction.ts@@ -82,6 +82,34 @@ const KEEP_RECENT = 4 // Always keep at least the last N messages untouched* any real instruction; a pasted 200 KB file does not ride along forever. */const PINNED_TASK_MAX_CHARS = 8000+/** How many already-done tool names the trim notice carries. */+const DONE_TRAIL_MAX = 40++/**+ * The tool names one assistant message asked for, in order.+ *+ * Two shapes, because the transports differ: the native and OpenAI paths carry+ * `tool_calls`, the hermes path carries `<tool_call>{…}</tool_call>` in the+ * content. Reading only the first `"name"` INSIDE each block matters, since a+ * tool's own arguments routinely contain a `name` field of their own.+ */+function toolNamesIn(msg: OllamaChatMessage): string[] {+ const out: string[] = []+ const calls = (msg as { tool_calls?: Array<{ function?: { name?: string } }> }).tool_calls+ if (Array.isArray(calls)) {+ for (const tc of calls) {+ if (typeof tc?.function?.name === 'string') out.push(tc.function.name)+ }+ }+ if (msg.role === 'assistant' && typeof msg.content === 'string' && msg.content.includes('<tool_call>')) {+ for (const block of msg.content.matchAll(/<tool_call>\s*(\{[\s\S]*?\})\s*<\/tool_call>/g)) {+ const m = /"name"\s*:\s*"([a-zA-Z0-9_]+)"/.exec(block[1])+ if (m) out.push(m[1])+ }+ }+ return out+}+/*** True for a message that is a tool RESULT — either the native `tool` role or* a Hermes `<tool_response>` carried on a user message. Used to trim a leading@@ -192,13 +220,33 @@ export function compactMessages(compacted.push(pinnedTask)}if (droppedCount > 0) {+ // What was dropped is exactly the record of the work already done, while+ // the pin keeps the instruction alive forever. Measured on the installed+ // build 2026-08-06, Coding + Ollama + hermes, a 30 step plan: the run+ // walked steps 1 to 18, compaction fired, and the very next call was+ // todo_write followed by get_current_time, system_info, process_list,+ // file_list. It had started the plan over from the top, because the only+ // thing it could still see was the plan itself. David watching it: "es+ // wiederholt sich die ganze Zeit ... und er sagt immer dasselbe."+ //+ // So the notice carries the trail. Names only, no arguments and no+ // results: it is the cheapest thing that answers "where was I".+ const dropped = capped.slice(0, capped.length - kept.length)+ const done: string[] = []+ for (const m of dropped) done.push(...toolNamesIn(m))+ const omitted = Math.max(0, done.length - DONE_TRAIL_MAX)+ const trail = done.slice(done.length - DONE_TRAIL_MAX)+ const doneLine = done.length+ ? ` Already done in this run, in order${omitted ? ` (${omitted} earlier call${omitted === 1 ? '' : 's'} omitted)` : ''}: ${trail.join(', ')}. Carry on AFTER the last one, do not start the task again from the beginning.`+ : ''+// Wording matters here: the old notice ("Re-read any file you still need// with file_read.") actively FED a re-read loop — every iteration the// model was told to read again what it had just read. Keep the honest// recovery path but make it single-shot and anti-repeat.compacted.push({role: 'system',- content: `[${droppedCount} earlier message${droppedCount === 1 ? '' : 's'} were trimmed to fit the context window. The original task above still stands. Results you already saw still hold. If a detail is genuinely missing, re-read that specific file once; never repeat a call that already ran.]`,+ content: `[${droppedCount} earlier message${droppedCount === 1 ? '' : 's'} were trimmed to fit the context window. The original task above still stands. Results you already saw still hold.${doneLine} If a detail is genuinely missing, re-read that specific file once; never repeat a call that already ran.]`,})}compacted.push(...kept)diff --git a/src/lib/context-window.ts b/src/lib/context-window.tsindex 98b0588a..3d3818ba 100644--- a/src/lib/context-window.ts+++ b/src/lib/context-window.ts@@ -18,14 +18,56 @@*/export const DEFAULT_CONTEXT_CAP = 16384+/**+ * The cap for a turn that carries the TOOL CATALOGUE, which is every Agent and+ * Coding turn. A chat turn starts with a persona and a question. An agent turn+ * starts with every tool definition, in every round, and only then gets to the+ * work.+ *+ * Measured on the installed 2.6.2 build, 2026-08-06, Coding + Ollama + hermes:+ * the 30 builtin tools are 35087 characters of system prompt, and Ollama's own+ * `prompt_eval_count` put system plus user at 8488 tokens before a single+ * output token. Against DEFAULT_CONTEXT_CAP that is 52% of the window gone at+ * rest, so a run reached step 18 of a 30 step plan, compacted, and started the+ * plan again from step 1 because the pinned task survives compaction and the+ * progress does not. Twice, same shape both times.+ *+ * Why raising it is safe, measured on the RTX 3060 12 GB the cap was written+ * for, qwen2.5-coder:14b:+ * num_ctx 16384 -> 12 GB, `ollama ps` reports 16%/84% CPU/GPU+ * num_ctx 32768 -> 15 GB, `ollama ps` reports 34%/66% CPU/GPU+ * Neither OOMs. Ollama offloads layers to system RAM instead of failing, so+ * the cap was never buying the crash protection its comment promises. It buys+ * speed. For a chat that is the right trade and DEFAULT_CONTEXT_CAP keeps it.+ * For an agent run it is the wrong one: a slower run finishes, a run that+ * restarts its own plan at step 18 never does.+ *+ * The model's real maximum still wins downward, and a user override still wins+ * outright. Switching between a chat and an agent conversation on the same+ * model now changes num_ctx and costs one Ollama reload, which is the price of+ * the two surfaces having genuinely different needs. Within a run the value is+ * constant, which is the invariant `resolveAgentNumCtx` exists to hold.+ */+export const AGENT_CONTEXT_CAP = 32768+/*** @param modelMax the model's real/trained context length (0/undefined = unknown)* @param override user's explicit contextWindowOverride (0 = no override)+ * @param cap the ceiling to apply (DEFAULT_CONTEXT_CAP for chat,+ * AGENT_CONTEXT_CAP for a turn carrying the tool catalogue)* @returns the context window to actually use — never exceeds the model's real* max (when known), never silently sits at Ollama's 2048 default.*/-export function effectiveContextWindow(modelMax: number | undefined, override?: number): number {+export function effectiveContextWindow(+ modelMax: number | undefined,+ override?: number,+ cap: number = DEFAULT_CONTEXT_CAP,+): number {if (override && override > 0) return override+ // An UNKNOWN real maximum falls back to the conservative default, never to+ // `cap`. Asking a model for more room than it was trained on makes Ollama+ // extrapolate RoPE and costs quality, so the larger agent ceiling is only+ // ever reached by a model that has told us it can take it.const max = modelMax && modelMax > 0 ? modelMax : DEFAULT_CONTEXT_CAP- return Math.min(max, DEFAULT_CONTEXT_CAP)+ return Math.min(max, cap)}diff --git a/src/lib/orphan-run.ts b/src/lib/orphan-run.tsnew file mode 100644index 00000000..e99db5ff--- /dev/null+++ b/src/lib/orphan-run.ts@@ -0,0 +1,29 @@+// A turn that outlived the hook instance which started it (G29).+//+// The chat view unmounts on a view switch. useAgentChat already knows this and+// parks its /loop timer at module scope for exactly that reason (audit A3), but+// the run's own "am I running" state is still per instance: useState(false) in+// the remounted hook, while the old closure keeps going with its own controller.+//+// The two halves of the UI then disagree, because they read different sources:+// the three dots and the clock read the PER-CONVERSATION store flag, which the+// old run set and has not cleared, so the chat looks busy. Send vs Stop reads+// the hook's own state, which is false after the remount, so the composer+// offers Send. On the Mac run of 2026-08-07 that left a conversation with an+// animating clock, no request on the wire and no Stop button: no way back.+//+// The store already knows how to end such a run. The aborter the run registered+// closes over ITS AbortController, so it survives the remount, and+// abortConversation() calls it and clears the flag.++/**+ * True when the store says this conversation is generating but no run in the+ * current hook instance accounts for it.+ */+export function isOrphanRun(+ storeGenerating: boolean,+ localGenerating: boolean,+ localAgentRunning: boolean,+): boolean {+ return storeGenerating && !localGenerating && !localAgentRunning+}diff --git a/src/lib/plan-reconcile.ts b/src/lib/plan-reconcile.tsnew file mode 100644index 00000000..99e990fc--- /dev/null+++ b/src/lib/plan-reconcile.ts@@ -0,0 +1,49 @@+import type { TodoItem } from '../stores/todoStore'++/**+ * The loop's own answer to a false completion claim.+ *+ * Measured on R31 (gpt-oss-120b, Coding, LU Cloud, 2026-08-07): the model+ * wrote "All steps completed as requested" while the PlanBar, fed by the very+ * todo list the model maintains, read PLAN 13/30. The task text said "do not+ * stop early" in so many words. Nothing reconciled the two, so the run ended+ * and the claim stood.+ *+ * The plan length and the current step are already client-side state; whether+ * the run may end is therefore decidable without asking the model anything.+ * When the final turn arrives while the plan has open items, the loop gets a+ * bounded number of corrective steers naming the next open step. Bounded,+ * because a model that ignores two direct contradictions will ignore ten, and+ * an unbounded loop against a stubborn model is its own failure mode.+ */++export interface PlanGap {+ done: number+ total: number+ /** The first in_progress item, or the first pending one. */+ next: string+}++/** Steers per run. Two contradictions ignored means the model will not move. */+export const PLAN_RECONCILE_BUDGET = 2++/**+ * The gap between "the model stopped" and "the plan is done", or null when+ * ending now is legitimate: no plan was written, or every item is completed.+ */+export function openPlanGap(todos: TodoItem[]): PlanGap | null {+ if (todos.length === 0) return null+ const done = todos.filter((t) => t.status === 'completed').length+ if (done >= todos.length) return null+ const next = todos.find((t) => t.status === 'in_progress') ?? todos.find((t) => t.status === 'pending')+ if (!next) return null+ return { done, total: todos.length, next: next.content }+}++export function planReconcileSteer(gap: PlanGap): string {+ return (+ `Your own todo list shows ${gap.done} of ${gap.total} steps completed, so the task is NOT finished. ` ++ `Do not declare completion while steps are open. Continue now with the next open step: "${gap.next}". ` ++ `Execute it as a tool call, then update the list with todo_write once it actually succeeded.`+ )+}diff --git a/src/lib/plan-staleness.ts b/src/lib/plan-staleness.tsnew file mode 100644index 00000000..5207080d--- /dev/null+++ b/src/lib/plan-staleness.ts@@ -0,0 +1,51 @@+/**+ * PlanBar lag (measured on the 2026-08-07 runs, next to G14-4): the bar read+ * PLAN 8/31 while the model was demonstrably narrating step 17. The bar only+ * renders what the model reports through todo_write, both system prompts+ * already demand an update after every step, and small models ignore it once+ * they get going. So the app notices the silence deterministically: batches of+ * real work keep landing while the plan has open items and none of them was a+ * todo_write. After PLAN_STALE_BATCHES of that, ONE steer asks for the update,+ * at most PLAN_STALE_STEER_BUDGET times per run so a model that will not+ * comply is not nagged forever.+ *+ * The steer asks the model to REPORT its own progress. It never invents plan+ * state: the store is only ever written by the model's todo_write.+ */+import type { PlanGap } from './plan-reconcile'++/** Executed tool batches without a todo_write before the plan counts as stale. */+export const PLAN_STALE_BATCHES = 3++/** Steers per run. Two is enough to recover a forgetful model once and prove+ * an unwilling one will not comply. */+export const PLAN_STALE_STEER_BUDGET = 2++/** One instance per run, fed once per executed tool batch. */+export class PlanStaleness {+ private quiet = 0+ private steersLeft = PLAN_STALE_STEER_BUDGET++ /** Returns true when the steer should fire NOW (and consumes budget). */+ recordBatch(toolNames: string[], hasOpenPlan: boolean): boolean {+ if (!hasOpenPlan || toolNames.length === 0 || toolNames.includes('todo_write')) {+ this.quiet = 0+ return false+ }+ this.quiet+++ if (this.quiet >= PLAN_STALE_BATCHES && this.steersLeft > 0) {+ this.quiet = 0+ this.steersLeft--+ return true+ }+ return false+ }+}++export function planStalenessSteer(gap: PlanGap): string {+ return (+ `Your plan still shows ${gap.done} of ${gap.total} steps completed and has not been updated while you worked. ` ++ `Bring it up to date NOW with one todo_write call: send the full list, mark every finished step completed, and mark the step you are actually on as the single in_progress item. ` ++ `Then continue with the work. The list currently names "${gap.next}" as the next step.`+ )+}diff --git a/src/lib/reasoning-round.ts b/src/lib/reasoning-round.tsnew file mode 100644index 00000000..b781c08e--- /dev/null+++ b/src/lib/reasoning-round.ts@@ -0,0 +1,28 @@+/**+ * A round that is all thought is not an ending.+ *+ * Measured on R17 (Agent, Ollama, Qwen3-4B, 2026-08-07): step 1 of 31 fired,+ * the next round arrived as reasoning with no answer segment and no tool+ * call, and the loop ended the run. On Ollama's Qwen3 chat templates this is+ * not even unusual: the opening think tag lives in the PROMPT (G12), so an+ * entire round can stream as thought text.+ *+ * Three layers now stand between such a round and a dead run, in order:+ * 1. the dud-turn retry (before ANY tool ran, retry once with think off),+ * 2. the G16 plan reconcile (an open todo list contradicts the ending),+ * 3. this: mid-run, no plan to lean on, thought but no words and no call.+ */++/** True when the model produced reasoning but neither answer text nor calls. */+export function reasoningOnlyRound(content: string, thinking: string): boolean {+ return !content.trim() && !!thinking.trim()+}++/** Per-run budget. A model that reasons three rounds straight without acting+ * is stuck in its head; further pushes only spend tokens. */+export const REASONING_CONTINUE_BUDGET = 2++export const REASONING_CONTINUE_STEER =+ 'Your last round was internal reasoning only, with no answer and no tool call. ' ++ 'That is fine, but the task is still open: continue now. Either execute the next ' ++ 'step as a tool call, or, if everything is genuinely done, state the final answer in plain text.'diff --git a/src/lib/render-budget.ts b/src/lib/render-budget.tsnew file mode 100644index 00000000..5b22d01d--- /dev/null+++ b/src/lib/render-budget.ts@@ -0,0 +1,109 @@+/**+ * Render budget for agent-triggered generations (G19-1, R32 witness): the app+ * queued a 30 to 60 minute Wan render on an RTX 3060 inside an interactive+ * run, polled it 354 times and said nothing. The poll deadline alone is blind:+ * it burns its whole budget before admitting the job never had a chance.+ *+ * The tracker reads the pace off ComfyUI's own progress events (value/max per+ * sampler step) and projects how long the whole sampling pass will take. Once+ * enough steps are in, a projection clearly past the budget ends the wait+ * early with an honest, actionable message, and the job itself is abandoned so+ * the GPU stops burning (the timeout used to orphan it).+ */++/** Sampler steps observed before we trust the pace. */+export const MIN_STEPS_FOR_VERDICT = 3++/** A projection must overshoot the budget by this factor before we give up,+ * so a render that would land a little late still gets to finish. */+export const HOPELESS_FACTOR = 1.25++interface PaceState {+ t0: number+ v0: number+ value: number+ max: number+ at: number+}++/**+ * Feed it ComfyUI `progress` ticks, ask it for the projected total. Pace is+ * measured from the FIRST tick, so model-load time never pollutes it. A value+ * that moves backwards means a new sampler node started (wan22 runs two+ * passes); re-anchor there. Projecting only the current pass under-estimates+ * multi-pass jobs, which errs on the side of letting them run.+ */+export class PaceTracker {+ private s: PaceState | null = null++ tick(value: number, max: number, at: number): void {+ if (!this.s || value < this.s.value) {+ this.s = { t0: at, v0: value, value, max, at }+ return+ }+ this.s.value = value+ this.s.max = max+ this.s.at = at+ }++ /** Projected ms for the whole sampling pass, or null before enough steps. */+ projectedTotalMs(): number | null {+ const s = this.s+ if (!s) return null+ const steps = s.value - s.v0+ if (steps < MIN_STEPS_FOR_VERDICT) return null+ return ((s.at - s.t0) / steps) * s.max+ }+}++export function overBudget(projectedTotalMs: number | null, budgetMs: number): boolean {+ return projectedTotalMs !== null && projectedTotalMs > budgetMs * HOPELESS_FACTOR+}++/**+ * Budget for the warm-up phase before the FIRST sampler progress event: model+ * load, VRAM swap, cold start (G24, R17c witness 2026-08-07: a Wan render sat+ * in "loading model into VRAM" for 19 minutes without one progress event, so+ * the pace tracker never engaged and a generous user timeout never fired; the+ * whole 20 minute run was lost to it). The promised swap is 30 to 90 s; this+ * sits well above that so only a genuinely wedged load trips it.+ */+export const SWAP_WARMUP_BUDGET_MS = 5 * 60_000++/**+ * True when the warm-up phase overran its budget. Deliberately narrow:+ * - the WS must be connected, otherwise we are blind by design and only the+ * flat deadline applies (exactly as before this guard existed);+ * - NO prompt at all may have progressed. Progress on someone else's prompt+ * means the GPU is busy, not wedged, and our job is just queued behind it;+ * killing it there would punish a healthy queue.+ */+export function warmupExceeded(+ sawAnyProgress: boolean,+ wsConnected: boolean,+ elapsedMs: number,+ budgetMs: number = SWAP_WARMUP_BUDGET_MS,+): boolean {+ return wsConnected && !sawAnyProgress && elapsedMs > budgetMs+}++/** Tool result for a warm-up abort. Says what was observed, not a guess. */+export function swapWarmupNotice(kindLabel: string, elapsedMs: number): string {+ const m = Math.max(1, Math.round(elapsedMs / 60_000))+ return `${kindLabel} generation stopped: after ${m} minute${m === 1 ? '' : 's'} the model was still loading into VRAM and sampling never started. The job was cancelled so the GPU is free again. Free some VRAM (close other GPU apps, or set VRAM hand-off to "always" in Settings so the chat model is evicted first), or pick a smaller model.`+}++const advice = 'Try fewer frames, a smaller resolution or fewer steps, or pick a lighter model. The generation timeout is adjustable in Settings.'++/** Tool result for a pace-based early stop. Honest about what was measured. */+export function renderBudgetNotice(kindLabel: string, projectedMs: number, budgetMs: number): string {+ const p = Math.max(1, Math.round(projectedMs / 60_000))+ const b = Math.max(1, Math.round(budgetMs / 60_000))+ return `${kindLabel} generation stopped early: at the measured pace this render needs about ${p} minutes, more than the ${b} minute budget. The job was cancelled so the GPU is free again. ${advice}`+}++/** Tool result for the flat deadline. The job is abandoned, not orphaned. */+export function renderTimeoutNotice(kindLabel: string, budgetMs: number): string {+ const b = Math.max(1, Math.round(budgetMs / 60_000))+ return `${kindLabel} generation hit the ${b} minute budget and was cancelled so the GPU is free again. ${advice}`+}diff --git a/src/lib/run-idle.ts b/src/lib/run-idle.tsnew file mode 100644index 00000000..ec3c1e24--- /dev/null+++ b/src/lib/run-idle.ts@@ -0,0 +1,59 @@+/**+ * G25 (R17c witness 2026-08-07): backend detection resolves asynchronously a+ * few seconds after startup, so the "Multiple backends running" selector could+ * open MID RUN and stand over the chat for the rest of a 20 minute agent run.+ * Detection is a startup convenience; an active run is the one thing on screen+ * the user is actually watching. Any modal it wants to open waits here until+ * every surface is idle.+ */+import { useGenerationStore } from '../stores/generationStore'+import { useCodexStore } from '../stores/codexStore'++/**+ * Pure verdict over the two run signals: the per-conversation generating+ * flags (Chat + Agent share them) and the Coding Agent's per-thread status.+ * Exported for the unit tests.+ */+export function anyRunActive(+ generating: Record<string, boolean>,+ threads: Record<string, { status: string }>,+): boolean {+ if (Object.values(generating).some(Boolean)) return true+ return Object.values(threads).some((t) => t.status === 'running')+}++function busy(): boolean {+ return anyRunActive(+ useGenerationStore.getState().generating,+ useCodexStore.getState().threads,+ )+}++/**+ * Call `show` now when no run is active, otherwise the moment the last run+ * ends. Returns a cancel function that withdraws a still-deferred `show`+ * without firing it; after `show` ran, cancelling is a no-op. Neither store+ * persists a running flag across a restart (generationStore is ephemeral by+ * design, codexStore persists only the working directory), so a crash can+ * never leave this waiting on a ghost run.+ */+export function whenRunsIdle(show: () => void): () => void {+ if (!busy()) {+ show()+ return () => {}+ }+ let done = false+ const unsubs: (() => void)[] = []+ const check = () => {+ if (done || busy()) return+ done = true+ for (const u of unsubs) u()+ show()+ }+ unsubs.push(useGenerationStore.subscribe(check))+ unsubs.push(useCodexStore.subscribe(check))+ return () => {+ done = true+ for (const u of unsubs) u()+ }+}diff --git a/src/lib/turn-summary.ts b/src/lib/turn-summary.tsindex bbf4dade..47fa20c9 100644--- a/src/lib/turn-summary.ts+++ b/src/lib/turn-summary.ts@@ -28,6 +28,13 @@ export interface TurnSummaryInput {videoGenDone: number/** True only when an image was fed back to a vision-capable model. */visionFeedbackGiven: boolean+ /** The run's own plan, when one is open (G27). The G16 reconcile steers the+ * MODEL back to work, but its budget is two; once it is spent the run ends+ * anyway and this function writes the last thing the user reads. On R01b+ * (Mac, 2026-08-07) that sentence was "Task completed: 3 operations+ * completed." while the PlanBar beside it read 1 of 31. The closing line+ * must never claim completion the plan contradicts. */+ planGap?: { done: number; total: number; next: string } | null}const NOTHING_AT_ALL =@@ -39,18 +46,36 @@ const NOTHING_AT_ALL =* noise · David 2026-06-16).*/export function summarizeTurn(input: TurnSummaryInput): string {- const { calls, imageGenDone, videoGenDone, visionFeedbackGiven } = input+ const { calls, imageGenDone, videoGenDone, visionFeedbackGiven, planGap } = inputconst completed = calls.filter((c) => c.status === 'completed')const failed = calls.filter((c) => c.status === 'failed')+ // G27: an open plan outranks every cheerful ending below. It is a SUFFIX,+ // never a replacement: the D#81 rule that a failed picture always shows its+ // reason stands, and a picture that landed is still worth saying. Only the+ // claim of completion is taken away.+ const planNote = planGap+ ? `The run stopped with the plan unfinished: ${planGap.done} of ${planGap.total} steps done. Next open step: "${planGap.next}". Send "continue" to carry on.`+ : ''+ const withPlan = (text: string) => (planNote ? (text ? `${text}\n\n${planNote}` : planNote) : text)++ if (planGap && imageGenDone === 0 && videoGenDone === 0) {+ const failedMediaNow = failed.filter((c) => isMediaTool(c.toolName))+ // A failed picture keeps its own headline (D#81); the plan note follows it.+ if (failedMediaNow.length === 0) return planNote+ }+if (imageGenDone > 0 || videoGenDone > 0) {- if (!visionFeedbackGiven) return ''+ // The empty return stays empty when the plan is done: the tool block+ // already shows the picture and a robotic line only adds noise. With an+ // open plan the note is the whole point, so it survives on its own.+ if (!visionFeedbackGiven) return withPlan('')if (imageGenDone > 0 && videoGenDone > 0) {- return 'Fertig, dein Bild und dein Video sind oben. / Done, your image and video are above.'+ return withPlan('Fertig, dein Bild und dein Video sind oben. / Done, your image and video are above.')}- return videoGenDone > 0+ return withPlan(videoGenDone > 0? 'Fertig, dein Video ist oben. / Done, your video is above.'- : 'Fertig, dein Bild ist oben. / Done, your image is above.'+ : 'Fertig, dein Bild ist oben. / Done, your image is above.')}// Nothing landed. If a picture or clip was attempted and failed, that is the@@ -59,9 +84,9 @@ export function summarizeTurn(input: TurnSummaryInput): string {if (failedMedia.length) {const kind = failedMedia.some((c) => c.toolName === 'video_generate') ? 'video' : 'image'const why = (failedMedia[0].result ?? '').trim()- return why+ return withPlan(why? `That ${kind} did not come out: ${why}\n\nSay "again" to retry, or change the prompt or model and send it once more.`- : `That ${kind} did not come out and no reason came back. Check that ComfyUI is still running, then try again.`+ : `That ${kind} did not come out and no reason came back. Check that ComfyUI is still running, then try again.`)}const writes = completed.filter((c) => c.toolName === 'file_write').lengthdiff --git a/src/stores/__tests__/todoStore.test.ts b/src/stores/__tests__/todoStore.test.tsnew file mode 100644index 00000000..cd9b7ce1--- /dev/null+++ b/src/stores/__tests__/todoStore.test.ts@@ -0,0 +1,130 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { useTodoStore, normalizeTodos, summarizeTodos, writeTodos } from '../todoStore'++// The plan the model writes through `todo_write` (audit C4). Everything here is+// about surviving what a small local model actually sends: a 3B model asked for+// {content, status} will sooner or later send a bare string, a missing status,+// a status it invented, or forty items.++beforeEach(() => {+ useTodoStore.setState({ byConversation: {}, updatedAt: {} })+})++describe('normalizeTodos survives what a model sends', () => {+ it('keeps well-formed items as they are', () => {+ expect(+ normalizeTodos([+ { content: 'read the file', status: 'completed' },+ { content: 'fix the bug', status: 'in_progress' },+ { content: 'run the tests', status: 'pending' },+ ]),+ ).toEqual([+ { content: 'read the file', status: 'completed' },+ { content: 'fix the bug', status: 'in_progress' },+ { content: 'run the tests', status: 'pending' },+ ])+ })++ it('treats an unknown status as not started', () => {+ // The dangerous direction is the other one: a typo must never be read as+ // done, or the user sees work ticked off that never happened.+ expect(normalizeTodos([{ content: 'x', status: 'donezo' }])[0].status).toBe('pending')+ expect(normalizeTodos([{ content: 'x', status: 'DONE' }])[0].status).toBe('pending')+ expect(normalizeTodos([{ content: 'x' }])[0].status).toBe('pending')+ })++ it('drops entries with no usable content instead of rendering blanks', () => {+ expect(+ normalizeTodos([+ { content: ' ', status: 'pending' },+ 'just a string',+ null,+ 42,+ { status: 'completed' },+ { content: 'real one', status: 'pending' },+ ]),+ ).toEqual([{ content: 'real one', status: 'pending' }])+ })++ it('returns an empty plan for anything that is not a list', () => {+ for (const junk of [undefined, null, 'todos', 42, { todos: [] }]) {+ expect(normalizeTodos(junk)).toEqual([])+ }+ })++ it('caps runaway lists and runaway items', () => {+ const many = Array.from({ length: 100 }, (_, i) => ({ content: `step ${i}`, status: 'pending' }))+ expect(normalizeTodos(many)).toHaveLength(40)++ const long = normalizeTodos([{ content: 'x'.repeat(1000), status: 'pending' }])+ expect(long[0].content.length).toBe(200)+ })++ it('trims whitespace so the strip does not render ragged', () => {+ expect(normalizeTodos([{ content: ' padded ', status: 'pending' }])[0].content).toBe('padded')+ })+})++describe('the plan is per conversation', () => {+ it('does not leak between two chats', () => {+ writeTodos('chat-a', [{ content: 'a-step', status: 'pending' }])+ writeTodos('chat-b', [{ content: 'b-step', status: 'completed' }])++ expect(useTodoStore.getState().getTodos('chat-a')).toEqual([{ content: 'a-step', status: 'pending' }])+ expect(useTodoStore.getState().getTodos('chat-b')).toEqual([{ content: 'b-step', status: 'completed' }])+ })++ it('replaces the whole list rather than merging', () => {+ writeTodos('c', [+ { content: 'one', status: 'completed' },+ { content: 'two', status: 'in_progress' },+ ])+ writeTodos('c', [{ content: 'only this', status: 'pending' }])++ // Merging would leave 'one' and 'two' behind and show a plan the model never+ // wrote. Whole-list replacement is the contract the tool description states.+ expect(useTodoStore.getState().getTodos('c')).toEqual([{ content: 'only this', status: 'pending' }])+ })++ it('reports an empty plan for an unknown or missing conversation', () => {+ expect(useTodoStore.getState().getTodos('never-seen')).toEqual([])+ expect(useTodoStore.getState().getTodos(null)).toEqual([])+ expect(useTodoStore.getState().getTodos(undefined)).toEqual([])+ })++ it('clearing one chat leaves the other alone', () => {+ writeTodos('keep', [{ content: 'k', status: 'pending' }])+ writeTodos('drop', [{ content: 'd', status: 'pending' }])+ useTodoStore.getState().clearTodos('drop')++ expect(useTodoStore.getState().getTodos('keep')).toHaveLength(1)+ expect(useTodoStore.getState().getTodos('drop')).toEqual([])+ })+})++describe('the summary handed back to the model', () => {+ it('states progress and the current step', () => {+ const out = summarizeTodos([+ { content: 'read', status: 'completed' },+ { content: 'edit', status: 'in_progress' },+ { content: 'test', status: 'pending' },+ ])+ expect(out).toContain('1/3 done')+ expect(out).toContain('now: edit')+ // The model has to be able to read its own plan back without us replaying+ // the whole list into the context on every turn.+ expect(out).toContain('[x] read')+ expect(out).toContain('[>] edit')+ expect(out).toContain('[ ] test')+ })++ it('says so plainly when the plan is emptied', () => {+ expect(summarizeTodos([])).toBe('Plan cleared.')+ })++ it('omits the current step when nothing is in progress', () => {+ const out = summarizeTodos([{ content: 'a', status: 'pending' }])+ expect(out).toContain('0/1 done')+ expect(out).not.toContain('now:')+ })+})diff --git a/src/stores/todoStore.ts b/src/stores/todoStore.tsnew file mode 100644index 00000000..5e39a6e0--- /dev/null+++ b/src/stores/todoStore.ts@@ -0,0 +1,111 @@+import { create } from 'zustand'+import { persist, createJSONStorage } from 'zustand/middleware'++/**+ * The plan a long run is working through, written by the model itself.+ *+ * On a task that takes twenty tool calls the transcript scrolls away and the+ * user is left guessing whether the agent is on step 2 or step 9, and whether+ * it still remembers what it set out to do. The audit filed this as C4: the+ * model had no way to state a plan and no way to show progress against it.+ *+ * The model owns the list through the `todo_write` tool and replaces it whole+ * on every call. Whole-list replacement rather than per-item patching is+ * deliberate: a small local model cannot be trusted to hold stable item ids+ * across twenty turns, and a half-applied patch would show a plan that never+ * existed.+ *+ * Keyed by conversation so the Code tab and every chat keep their own plan, and+ * persisted so closing the app mid-task does not lose it.+ */++export type TodoStatus = 'pending' | 'in_progress' | 'completed'++export interface TodoItem {+ content: string+ status: TodoStatus+}++interface TodoState {+ /** conversation id -> that run's plan */+ byConversation: Record<string, TodoItem[]>+ /** Wall-clock of the last write per conversation, for the "just updated" cue. */+ updatedAt: Record<string, number>++ setTodos: (conversationId: string, todos: TodoItem[]) => void+ getTodos: (conversationId: string | null | undefined) => TodoItem[]+ clearTodos: (conversationId: string) => void+}++/** Guards against a model that returns 40 steps or a novel per step. */+const MAX_ITEMS = 40+const MAX_CONTENT = 200++export function normalizeTodos(raw: unknown): TodoItem[] {+ if (!Array.isArray(raw)) return []+ const out: TodoItem[] = []+ for (const entry of raw.slice(0, MAX_ITEMS)) {+ if (!entry || typeof entry !== 'object') continue+ const e = entry as Record<string, unknown>+ const content = typeof e.content === 'string' ? e.content.trim() : ''+ if (!content) continue+ // Anything unrecognised counts as not started: a typo must never mark work+ // done that was never done.+ const status: TodoStatus =+ e.status === 'completed' || e.status === 'in_progress' ? e.status : 'pending'+ out.push({ content: content.slice(0, MAX_CONTENT), status })+ }+ return out+}++export const useTodoStore = create<TodoState>()(+ persist(+ (set, get) => ({+ byConversation: {},+ updatedAt: {},++ setTodos: (conversationId, todos) =>+ set((s) => ({+ byConversation: { ...s.byConversation, [conversationId]: todos },+ updatedAt: { ...s.updatedAt, [conversationId]: Date.now() },+ })),++ getTodos: (conversationId) =>+ (conversationId && get().byConversation[conversationId]) || [],++ clearTodos: (conversationId) =>+ set((s) => {+ const byConversation = { ...s.byConversation }+ const updatedAt = { ...s.updatedAt }+ delete byConversation[conversationId]+ delete updatedAt[conversationId]+ return { byConversation, updatedAt }+ }),+ }),+ {+ name: 'locally-uncensored-todos',+ storage: createJSONStorage(() => localStorage),+ },+ ),+)++/** Non-hook access for the tool executor, which runs outside React. */+export function writeTodos(conversationId: string, raw: unknown): TodoItem[] {+ const todos = normalizeTodos(raw)+ useTodoStore.getState().setTodos(conversationId, todos)+ return todos+}++/** One-line summary the tool hands back to the model, so it can see its own+ * progress in the transcript without us replaying the whole list. */+export function summarizeTodos(todos: TodoItem[]): string {+ if (todos.length === 0) return 'Plan cleared.'+ const done = todos.filter((t) => t.status === 'completed').length+ const current = todos.find((t) => t.status === 'in_progress')+ const lines = todos.map((t) => {+ const mark = t.status === 'completed' ? '[x]' : t.status === 'in_progress' ? '[>]' : '[ ]'+ return `${mark} ${t.content}`+ })+ const head = `Plan updated (${done}/${todos.length} done${current ? `, now: ${current.content}` : ''}).`+ return `${head}\n${lines.join('\n')}`+}