diff --git a/apps/chat-ui/src/app-shell.tsx b/apps/chat-ui/src/app-shell.tsx index e84e1938..5c51780a 100644 --- a/apps/chat-ui/src/app-shell.tsx +++ b/apps/chat-ui/src/app-shell.tsx @@ -551,14 +551,25 @@ export function AppShell() { // its tool results, take its approvals and write its transcript to its // own thread, not to whichever one is showing now (`engine-pool.ts`). create: (id) => { + // The run stays alive on navigation; Stop/disposal cancels only this + // engine's local tools, never the ones another thread is running. + let toolController = new AbortController(); const created = createChatEngine({ client: felix, threadId: () => id, clientTools: { + cancel: () => { + toolController.abort(); + toolController = new AbortController(); + }, // `local_open` on a file opens it in this thread's side pane: the // engine's own thread, so a run on another thread fills that one's. execute: (req) => - executeClientTool(req, (path) => openPaneItem(id, { kind: 'file', path })), + executeClientTool( + req, + (path) => openPaneItem(id, { kind: 'file', path }), + toolController.signal, + ), // A `local_*` write's before is the browser's file; any other write's // is the harness's, on the thread the write is on. readForDiff: routedDiffReader(felix, readWorkspaceFile), diff --git a/apps/chat-ui/src/components/chat/response.tsx b/apps/chat-ui/src/components/chat/response.tsx index 60a87c2c..1161c3f1 100644 --- a/apps/chat-ui/src/components/chat/response.tsx +++ b/apps/chat-ui/src/components/chat/response.tsx @@ -1,5 +1,5 @@ import { PanelRightOpenIcon } from 'lucide-react'; -import { type ReactNode, useEffect, useState } from 'react'; +import { type ComponentProps, type ElementType, type ReactNode, useEffect, useState } from 'react'; import remarkBreaks from 'remark-breaks'; import { defaultRemarkPlugins, Streamdown, type StreamdownProps } from 'streamdown'; import { loadedPlugins, loadPlugins, needsMath, needsRaw, pluginsFor } from '@/lib/reply-plugins'; @@ -76,34 +76,36 @@ const HEADING = { h6: 'mt-4 mb-1 text-sm font-semibold text-muted-foreground', } as const; +type MarkdownProps = ComponentProps & { node?: unknown }; + export const responseComponents: Components = { - h1: ({ node: _node, className, ...props }) => ( + h1: ({ node: _node, className, ...props }: MarkdownProps<'h1'>) => (

), - h2: ({ node: _node, className, ...props }) => ( + h2: ({ node: _node, className, ...props }: MarkdownProps<'h2'>) => (

), - h3: ({ node: _node, className, ...props }) => ( + h3: ({ node: _node, className, ...props }: MarkdownProps<'h3'>) => (

), - h4: ({ node: _node, className, ...props }) => ( + h4: ({ node: _node, className, ...props }: MarkdownProps<'h4'>) => (

), - h5: ({ node: _node, className, ...props }) => ( + h5: ({ node: _node, className, ...props }: MarkdownProps<'h5'>) => (

), - h6: ({ node: _node, className, ...props }) => ( + h6: ({ node: _node, className, ...props }: MarkdownProps<'h6'>) => (
), - ul: ({ node: _node, className, ...props }) => ( + ul: ({ node: _node, className, ...props }: MarkdownProps<'ul'>) => (
    ), - ol: ({ node: _node, className, ...props }) => ( + ol: ({ node: _node, className, ...props }: MarkdownProps<'ol'>) => (
      ), // `task-list-item` arrives from remark-gfm. GitHub drops the marker on those for // the reason it is dropped here: the checkbox is the marker. - li: ({ node: _node, className, ...props }) => ( + li: ({ node: _node, className, ...props }: MarkdownProps<'li'>) => (
    1. p]:inline', diff --git a/apps/chat-ui/src/lib/cowork.ts b/apps/chat-ui/src/lib/cowork.ts index 374bad98..105bbe42 100644 --- a/apps/chat-ui/src/lib/cowork.ts +++ b/apps/chat-ui/src/lib/cowork.ts @@ -31,8 +31,12 @@ const vfs = getVfs('felix.chat.vfs'); * The browser's client tools. `openFile` is where `local_open` puts a workspace * file — the side pane of the thread the call is on, never a new window. */ -export async function executeClientTool(req: ClientToolRequest, openFile: (path: string) => void) { - return exec(req, vfs, { openFile }); +export async function executeClientTool( + req: ClientToolRequest, + openFile: (path: string) => void, + signal?: AbortSignal, +) { + return exec(req, vfs, { openFile, signal }); } export async function readWorkspaceFile(path: string): Promise { diff --git a/apps/chat-ui/src/routes/harness.tsx b/apps/chat-ui/src/routes/harness.tsx index 83ca6ff0..01e92098 100644 --- a/apps/chat-ui/src/routes/harness.tsx +++ b/apps/chat-ui/src/routes/harness.tsx @@ -25,7 +25,7 @@ import { useMemo, useRef, } from 'react'; -import { Link, Navigate, NavLink, Outlet, useMatch } from 'react-router'; +import { Link, Navigate, NavLink, type NavLinkRenderProps, Outlet, useMatch } from 'react-router'; import { listJobs, listSkillReviewQueue } from '@/api'; import { useHarnessAgent } from '@/components/harness/harness-agent'; import { DOCS_ORIGIN, PageBack, PageDocs, useMeasure } from '@/components/harness/panel'; @@ -481,7 +481,7 @@ function HarnessNav({ onNavigate, className }: { onNavigate?: () => void; classN onClick={onNavigate} // The sidebar's row grammar (`SidebarMenuButton`): the same list // drawn two ways read as two lists. - className={({ isActive }) => + className={({ isActive }: NavLinkRenderProps) => cn( 'flex h-9 items-center gap-2 rounded-lg px-2.5 text-sm transition-[background-color,color,box-shadow] coarse:h-11', 'focus-visible:ring-[3px] focus-visible:ring-ring focus-visible:outline-none', diff --git a/apps/chat-ui/tests/app-stream.test.tsx b/apps/chat-ui/tests/app-stream.test.tsx index f1f29159..7b40e215 100644 --- a/apps/chat-ui/tests/app-stream.test.tsx +++ b/apps/chat-ui/tests/app-stream.test.tsx @@ -6,6 +6,7 @@ import { MemoryRouter } from 'react-router'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import App from '../src/App'; import { ThemeProvider } from '../src/components/theme-provider'; +import * as cowork from '../src/lib/cowork'; /** * The chat surface, driven the way a person drives it. @@ -501,3 +502,44 @@ describe('the header with every mode on and a run blocked', () => { expect(header.querySelector('a[href^="/harness"]')).toBeNull(); }); }); + +it('Stop cancels the current engine’s browser tool executor', async () => { + let signal: AbortSignal | undefined; + let finish: (result: { content: string; error?: boolean }) => void = () => {}; + const execute = vi.spyOn(cowork, 'executeClientTool').mockImplementation((_req, _open, abort) => { + signal = abort; + return new Promise((resolve) => { + finish = resolve; + abort?.addEventListener('abort', () => resolve({ content: 'error: aborted', error: true }), { + once: true, + }); + }); + }); + try { + stubFetch([ + { + event: 'tool_request', + data: { id: 'blocked-read', name: 'local_read', args: { path: 'code.ts' } }, + }, + ]); + mount(); + await send(); + await waitFor(() => expect(execute).toHaveBeenCalledOnce()); + expect(signal).toBeDefined(); + const stop = await waitFor(() => { + const button = document.querySelector('[aria-label="Stop generating"]'); + expect(button).not.toBeNull(); + return button!; + }); + await act(async () => { + await userEvent.click(stop); + }); + await waitFor(() => expect(signal?.aborted).toBe(true)); + await waitFor(() => + expect(document.querySelector('[aria-label="Send message"]')).not.toBeNull(), + ); + } finally { + finish({ content: 'cleanup' }); + execute.mockRestore(); + } +}); diff --git a/apps/chat-ui/tests/finished-turns-memo.test.tsx b/apps/chat-ui/tests/finished-turns-memo.test.tsx index d837c0ad..62137134 100644 --- a/apps/chat-ui/tests/finished-turns-memo.test.tsx +++ b/apps/chat-ui/tests/finished-turns-memo.test.tsx @@ -86,6 +86,11 @@ describe('finished turns', () => { }; await send('one'); await screen.findByText('first answer', undefined, { timeout: 3000 }); + // The final delta is visible before DONE. Do not count the first run's + // own completion as an extra layout during the second run. + await waitFor(() => + expect(screen.queryByRole('button', { name: 'Stop generating' })).toBeNull(), + ); laidOut.length = 0; await send('two'); diff --git a/apps/docs/src/content/guide/terminal.mdx b/apps/docs/src/content/guide/terminal.mdx index 609739e3..b26fc422 100644 --- a/apps/docs/src/content/guide/terminal.mdx +++ b/apps/docs/src/content/guide/terminal.mdx @@ -405,3 +405,23 @@ the terminal has been restored — is the thread you were in and the command tha felix: Proxy worker routing rejoin with: felix --thread 0f9c1e7a-… ``` + + +## Coding with code + +Start the TUI from the project folder, with a harness API key configured: + +```bash +bun /path/to/felix-web/apps/tui/dist/felix.js --manifest code --shell +``` + +The harness must have the `code` manifest available. Code reads repository +instructions, implements changes and checks the results. `--shell` enables real `/bin/sh` +commands for builds, tests and Git. Each command shows its full text and absolute working +directory for confirmation, including when `--yes` skips file-write prompts. Without +`--shell`, only the existing emulated file commands are available. + +Commands start inside the project, but **are not sandboxed**: an approved command has your +account's filesystem and network access. stdin is closed; interactive programs are unsupported. +Output is capped at 200 kB and commands time out after four minutes. Stop cancels the process +group. `local_open` displays text files through `$PAGER`; web URLs appear as links to open manually. diff --git a/apps/tui/CLAUDE.md b/apps/tui/CLAUDE.md index e5fb0203..ecdf4c70 100644 --- a/apps/tui/CLAUDE.md +++ b/apps/tui/CLAUDE.md @@ -290,3 +290,14 @@ browser cannot do rather than about the chat: - **`apps/tui` runs on Bun, and only Bun.** The renderer reaches a native core over FFI, which Bun has first-class (`bun:ffi`) and Node has only as `node:ffi`, experimental and flag-gated behind `--experimental-ffi` from Node 26. The rest of the repo is unchanged and still Node. + + +## Coding tools (November 2026) + +`--shell` opts into native `/bin/sh` through `src/shell.ts`; without it the emulated verbs +remain. Native commands always use the local confirmation gate, even under `--yes`, and +respect `cwd` after containment validation. cwd containment is not process sandboxing. +The workspace owns per-call abort controllers; `cancel()` kills active process groups and +invalidates pending confirmations. App stop, thread changes and unmount call it. Output is +bounded and a four-minute process timer precedes the 270-second workspace cancellation. +`local_open` pages contained text files; URLs are returned for manual opening. diff --git a/apps/tui/README.md b/apps/tui/README.md index b8f9d868..198a2698 100644 --- a/apps/tui/README.md +++ b/apps/tui/README.md @@ -352,3 +352,23 @@ assert that a failed tool card is still red or a dim line still dim. - **One prompt owns the keyboard.** `useKeyboard` is a global subscription, so two banners on screen means one `y` answers both. `App` renders exactly one, and a handler that answers a key calls `preventDefault` so it does not also reach the composer. + + +## Coding with code + +Start the TUI from the project folder, with a harness API key configured: + +```bash +bun /path/to/felix-web/apps/tui/dist/felix.js --manifest code --shell +``` + +The harness must have the `code` manifest available. Code reads repository +instructions, implements changes and checks the results. `--shell` enables real `/bin/sh` +commands for builds, tests and Git. Each command shows its full text and absolute working +directory for confirmation, including when `--yes` skips file-write prompts. Without +`--shell`, only the existing emulated file commands are available. + +Commands start inside the project, but **are not sandboxed**: an approved command has your +account's filesystem and network access. stdin is closed; interactive programs are unsupported. +Output is capped at 200 kB and commands time out after four minutes. Stop cancels the process +group. `local_open` displays text files through `$PAGER`; web URLs appear as links to open manually. diff --git a/apps/tui/src/app.tsx b/apps/tui/src/app.tsx index df04ae37..60f93f15 100644 --- a/apps/tui/src/app.tsx +++ b/apps/tui/src/app.tsx @@ -103,6 +103,7 @@ export function App({ * the wire before `onExit` waits for it (`settleReleases`). */ const exit = useCallback(() => { + workspaceRef.current?.cancel(); void leaseRef.current?.release(); onExit(); }, [onExit]); @@ -176,9 +177,20 @@ export function App({ prompt: writePrompt, answer: answerWrite, confirm: confirmWrite, - cancel: cancelWrite, + cancel: cancelPrompt, } = writeGate; + const workspaceRef = useRef | null>(null); + const cancelWrite = useCallback(() => { + workspaceRef.current?.cancel(); + cancelPrompt(); + }, [cancelPrompt]); + useEffect( + () => () => { + workspaceRef.current?.cancel(); + }, + [], + ); const engineRef = useRef(null); /** The open thread's lease, for the client's hooks, which are built before it. */ const leaseRef = useRef(null); @@ -213,6 +225,21 @@ export function App({ }, }); clientRef.current = client; + workspaceRef.current = createWorkspace({ + root, + shell: config.shell, + confirmShell: confirmWrite, + openFile: async (body, name) => { + if (!pagerCommand()) throw new Error('set $PAGER to view files'); + renderer.suspend(); + try { + page(body, name); + } finally { + renderer.resume(); + } + }, + confirm: config.yes ? async () => true : confirmWrite, + }); engineRef.current = createChatEngine({ client, threadId: () => threadIdRef.current, @@ -226,15 +253,7 @@ export function App({ // *because* a durable stream carries no deltas, so there is no local // detail for the rebuild to throw away. onDurableComplete: () => void hydrateRef.current(threadIdRef.current), - clientTools: withHarnessDiffs( - createWorkspace({ - root, - // `--yes` is a confirm that always agrees, not an absent one: a - // workspace with no confirm at all would be a silent writer. - confirm: config.yes ? async () => true : confirmWrite, - }), - client, - ), + clientTools: withHarnessDiffs(workspaceRef.current, client), }); engineRef.current.setTurns(store.loadTurns(threadIdRef.current)); } diff --git a/apps/tui/src/config.ts b/apps/tui/src/config.ts index 5efbe0b5..bb21c9b1 100644 --- a/apps/tui/src/config.ts +++ b/apps/tui/src/config.ts @@ -24,6 +24,8 @@ export interface Config { manifest: string; /** Skip the confirmation prompt before a client tool writes. */ yes: boolean; + /** Opt in to real shell commands, confirmed individually. */ + shell?: boolean; /** Resume this thread instead of starting a new one. */ thread?: string; /** Send the key to a plaintext non-loopback origin anyway. */ @@ -130,7 +132,7 @@ export function readConfigFile(path: string): Partial { * `--yes` and sends "the worker" — a message quietly missing its first word, * which is worse than an error. */ -const SWITCHES = new Set(['yes', 'help', 'h', 'insecure']); +const SWITCHES = new Set(['yes', 'help', 'h', 'insecure', 'shell']); export interface ParsedArgs { flags: Record; @@ -203,6 +205,7 @@ export function resolveConfig( ...(apiKey ? { apiKey } : {}), manifest: str('manifest') ?? env.FELIX_MANIFEST?.trim() ?? file.manifest ?? DEFAULT_MANIFEST, yes: flags.yes === true || flags.yes === 'true', + shell: flags.shell === true || flags.shell === 'true', insecure: flags.insecure === true || flags.insecure === 'true', ...(str('thread') ? { thread: str('thread') } : {}), }, @@ -249,6 +252,7 @@ usage: felix [options] [message] --manifest agent manifest (default ${DEFAULT_MANIFEST}) --thread resume a thread instead of starting a new one --yes do not ask before a client tool writes a file + --shell enable real shell commands (always confirmed; not sandboxed) --insecure allow the key over plaintext http to a remote origin --help this diff --git a/apps/tui/src/pager.ts b/apps/tui/src/pager.ts index 48d16970..036d8f7c 100644 --- a/apps/tui/src/pager.ts +++ b/apps/tui/src/pager.ts @@ -38,7 +38,9 @@ export function page(body: string, name: string): { path: string } { const cmd = pagerCommand(); if (cmd?.length) { const [bin, ...args] = cmd as [string, ...string[]]; - spawnSync(bin, [...args, path], { stdio: 'inherit' }); + const result = spawnSync(bin, [...args, path], { stdio: 'inherit' }); + if (result.error) throw result.error; + if (result.status !== 0) throw new Error(`pager exited with ${result.signal ?? result.status}`); } return { path }; } diff --git a/apps/tui/src/shell.ts b/apps/tui/src/shell.ts new file mode 100644 index 00000000..98b9a584 --- /dev/null +++ b/apps/tui/src/shell.ts @@ -0,0 +1,87 @@ +/** Explicitly enabled local process execution. cwd containment is not a sandbox. */ +import { spawn } from 'node:child_process'; +import type { ClientToolResult } from '@felix/client'; +import type { ConfirmFn } from './workspace.js'; + +const MAX_OUTPUT_BYTES = 200_000; + +export async function runNativeShell( + command: string, + cwd: string, + confirm: ConfirmFn, + signal?: AbortSignal, + timeoutMs = 240_000, +): Promise { + if (!command.trim()) return { content: 'error: command is empty', error: true }; + if (signal?.aborted) return { content: 'error: local_shell aborted', error: true }; + if (!(await confirm(`run command in ${cwd}\n${command}`))) { + return { content: 'refused by the user', error: true }; + } + if (signal?.aborted) return { content: 'error: local_shell aborted', error: true }; + + return await new Promise((resolve) => { + // A process group lets cancellation kill shell children too. Never inherit + // stdin/stdout: a child must not read the TUI's keys or corrupt its screen. + const child = spawn('/bin/sh', ['-c', command], { + cwd, + detached: true, + stdio: ['ignore', 'pipe', 'pipe'], + }); + const chunks: Buffer[] = []; + let bytes = 0; + let truncated = false; + let finished = false; + const capture = (chunk: Buffer) => { + const remaining = MAX_OUTPUT_BYTES - bytes; + if (chunk.length > remaining) truncated = true; + if (remaining > 0) { + const kept = chunk.subarray(0, remaining); + chunks.push(kept); + bytes += kept.length; + } + }; + const kill = () => { + if (!child.pid) return; + try { + process.kill(-child.pid, 'SIGKILL'); + } catch { + /* already exited */ + } + }; + const finish = (content: string, error = false) => { + if (finished) return; + finished = true; + clearTimeout(timer); + signal?.removeEventListener('abort', abort); + resolve({ content, ...(error ? { error: true } : {}) }); + }; + const outputWith = (status: string) => { + const output = Buffer.concat(chunks).toString('utf8'); + const suffix = truncated ? '\n(output truncated at 200000 bytes)' : ''; + return `${output}${suffix}\n${status}`.trim(); + }; + const abort = () => { + kill(); + finish(outputWith('error: local_shell aborted'), true); + }; + // Keep below the workspace executor and the manifest's 300-second deadline. + const timer = setTimeout(() => { + kill(); + finish(outputWith(`error: local_shell timed out after ${timeoutMs}ms`), true); + }, timeoutMs); + child.stdout.on('data', capture); + child.stderr.on('data', capture); + child.on('error', (error) => finish(`error: ${error.message}`, true)); + child.on('close', (code, killedBy) => { + const output = Buffer.concat(chunks).toString('utf8'); + const suffix = truncated ? '\n(output truncated at 200000 bytes)' : ''; + const status = + code === 0 + ? '' + : `\nerror: command ${killedBy ? `killed by ${killedBy}` : `exited with code ${code}`}`; + finish(`${output}${suffix}${status}`.trim() || '(ok)', code !== 0); + }); + signal?.addEventListener('abort', abort, { once: true }); + if (signal?.aborted) abort(); + }); +} diff --git a/apps/tui/src/workspace.ts b/apps/tui/src/workspace.ts index a6f897b5..452bf7ca 100644 --- a/apps/tui/src/workspace.ts +++ b/apps/tui/src/workspace.ts @@ -25,10 +25,10 @@ * under the root — `.env` included — and the result goes to the harness. Scope * that by choosing the directory you start in. * - * No process execution. `local_shell` here is the same handful of verbs the - * browser client implements, run against real files — not a shell. Spawning - * what the model typed is a different feature with a different threat model. + * By default `local_shell` emulates the browser verbs. With --shell it runs a + * confirmed real command. Only its initial cwd is contained; this is not an OS sandbox. */ + import { constants } from 'node:fs'; import { access, @@ -43,7 +43,7 @@ import { unlink, writeFile, } from 'node:fs/promises'; -import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { type ClientToolRequest, type ClientToolResult, @@ -52,6 +52,7 @@ import { runLocalFileTool, settleClientTool, } from '@felix/client'; +import { runNativeShell } from './shell.js'; /** * Asked before anything is written, with the **absolute** path it would touch. @@ -65,6 +66,12 @@ export type ConfirmFn = (summary: string) => Promise; export interface WorkspaceOptions { root: string; confirm: ConfirmFn; + /** Real process execution is an explicit CLI opt-in. */ + shell?: boolean; + /** Shell commands always ask, even when file writes use --yes. */ + confirmShell?: ConfirmFn; + /** Display a text file in the terminal viewer. URLs are returned as links. */ + openFile?: (body: string, name: string) => Promise; /** Abandons an in-flight tool when the run is stopped. */ signal?: AbortSignal; } @@ -337,6 +344,7 @@ function workingDirFs(opts: WorkspaceOptions): LocalFs { await assertWritable(root, target); if (!(await opts.confirm(`${summary} ${target}`))) throw new Error('refused by the user'); await mkdir(dirname(target), { recursive: true }); + opts.signal?.throwIfAborted(); if (append) await appendFile(target, content, 'utf8'); else await writeFile(target, content, 'utf8'); }, @@ -350,6 +358,7 @@ function workingDirFs(opts: WorkspaceOptions): LocalFs { if (!info.isFile()) throw new Error(`${path} is not a file; only files are deleted`); await assertWritable(root, target); if (!(await opts.confirm(`${summary} ${target}`))) throw new Error('refused by the user'); + opts.signal?.throwIfAborted(); await unlink(target); }, rename: async (path, toPath, { summary }) => { @@ -373,6 +382,7 @@ function workingDirFs(opts: WorkspaceOptions): LocalFs { if (!(await opts.confirm(`${summary} ${from} → ${to}`))) throw new Error('refused by the user'); await mkdir(dirname(to), { recursive: true }); + opts.signal?.throwIfAborted(); await rename(from, to); }, }; @@ -383,13 +393,43 @@ async function run(req: ClientToolRequest, opts: WorkspaceOptions): Promise(); return { - execute: (req: ClientToolRequest) => - settleClientTool(req, () => run(req, opts), opts.signal ? { signal: opts.signal } : {}), + /** Stop work as well as settling its result; a later turn gets a fresh controller. */ + cancel: () => { + for (const controller of active) controller.abort(); + }, + execute: async (req: ClientToolRequest) => { + const controller = new AbortController(); + active.add(controller); + const signal = opts.signal + ? AbortSignal.any([opts.signal, controller.signal]) + : controller.signal; + // Cancels the underlying work, including a confirmation answered after timeout. + const timer = setTimeout( + () => controller.abort(), + opts.shell && req.name === 'local_shell' ? 270_000 : 29_000, + ); + try { + const confirm = + (ask: ConfirmFn): ConfirmFn => + async (summary) => { + if (signal.aborted) return false; + const ok = await ask(summary); + return ok && !signal.aborted; + }; + return await settleClientTool( + req, + () => + run(req, { + ...opts, + signal, + confirm: confirm(opts.confirm), + confirmShell: confirm(opts.confirmShell ?? opts.confirm), + }), + { signal, timeoutMs: opts.shell && req.name === 'local_shell' ? 275_000 : 30_000 }, + ); + } finally { + clearTimeout(timer); + active.delete(controller); + } + }, /** * Pre-edit text for a `write_file` approval diff. Null means new, unreadable, * a directory, or too large — anything the banner must not present as diff --git a/apps/tui/tests/config.test.ts b/apps/tui/tests/config.test.ts index f35639c4..aa88a5c5 100644 --- a/apps/tui/tests/config.test.ts +++ b/apps/tui/tests/config.test.ts @@ -197,3 +197,10 @@ describe('readDevVars', () => { expect(readDevVars(file)).toEqual({}); }); }); + +it('enables native shell only with an explicit switch and keeps the first message', () => { + expect(resolveConfig([], {}, noFiles).config.shell).toBe(false); + const result = resolveConfig(['--shell', 'run', 'tests'], {}, noFiles); + expect(result.config.shell).toBe(true); + expect(result.firstMessage).toBe('run tests'); +}); diff --git a/apps/tui/tests/shell.test.ts b/apps/tui/tests/shell.test.ts new file mode 100644 index 00000000..e8352608 --- /dev/null +++ b/apps/tui/tests/shell.test.ts @@ -0,0 +1,60 @@ +import { afterEach, describe, expect, it, vi } from 'bun:test'; +import { existsSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { runNativeShell } from '../src/shell'; + +const roots: string[] = []; +const folder = () => { + const root = mkdtempSync(join(tmpdir(), 'felix-shell-')); + roots.push(root); + return root; +}; +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +describe('native shell deadline', () => { + it('kills the command at the deadline and keeps its diagnostic output', async () => { + const root = folder(); + const pending = runNativeShell( + 'printf started; sleep 2; touch never.txt', + root, + async () => true, + undefined, + 100, + ); + const result = await pending; + expect(result.error).toBe(true); + expect(result.content).toContain('timed out'); + expect(result.content).toContain('started'); + await Bun.sleep(2100); + expect(existsSync(join(root, 'never.txt'))).toBe(false); + }); + + it('does not start a command when approval arrives after cancellation', async () => { + const root = folder(); + const controller = new AbortController(); + let answer!: (ok: boolean) => void; + const pending = runNativeShell( + 'touch never.txt', + root, + () => + new Promise((resolve) => { + answer = resolve; + }), + controller.signal, + ); + controller.abort(); + answer(true); + expect((await pending).error).toBe(true); + expect(existsSync(join(root, 'never.txt'))).toBe(false); + }); + + it('never asks or spawns for an already aborted command', async () => { + const confirm = vi.fn(async () => true); + const result = await runNativeShell('touch never.txt', folder(), confirm, AbortSignal.abort()); + expect(result.error).toBe(true); + expect(confirm).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/tui/tests/workspace.test.ts b/apps/tui/tests/workspace.test.ts index e1d175a8..6548d871 100644 --- a/apps/tui/tests/workspace.test.ts +++ b/apps/tui/tests/workspace.test.ts @@ -382,3 +382,134 @@ describe('local_delete and local_rename on the working directory', () => { expect(existsSync(join(root, 'a.md'))).toBe(false); }); }); + +describe('coding workspace', () => { + it('honors cwd in emulated shell commands', async () => { + const result = await permissive().execute( + call('local_shell', { command: 'cat api.ts', cwd: 'src' }), + ); + expect(result.content).toBe('export const x = 1;\n'); + }); + + it('refuses a shell cwd outside the workspace', async () => { + const result = await permissive().execute( + call('local_shell', { command: 'pwd', cwd: outside }), + ); + expect(result.error).toBe(true); + }); + + it('marks unsupported commands as errors', async () => { + const result = await permissive().execute(call('local_shell', { command: 'git status' })); + expect(result.error).toBe(true); + }); + + it('runs a real command in cwd only after its own confirmation', async () => { + const confirmShell = vi.fn(async (_summary: string) => true); + const ws = createWorkspace({ root, shell: true, confirm: allow, confirmShell }); + const result = await ws.execute( + call('local_shell', { command: 'pwd; printf hello >&2', cwd: 'src' }), + ); + expect(result.error).toBeUndefined(); + expect(result.content).toContain(join(root, 'src')); + expect(result.content).toContain('hello'); + expect(confirmShell.mock.calls[0]?.[0]).toContain('pwd; printf hello >&2'); + }); + + it('refuses commands even when file writes are allowed without asking', async () => { + const ws = createWorkspace({ + root, + shell: true, + confirm: allow, + confirmShell: async () => false, + }); + const result = await ws.execute(call('local_shell', { command: 'touch never.txt' })); + expect(result.error).toBe(true); + expect(existsSync(join(root, 'never.txt'))).toBe(false); + }); + + it('reports a nonzero exit and keeps stderr', async () => { + const ws = createWorkspace({ root, shell: true, confirm: allow }); + const result = await ws.execute(call('local_shell', { command: 'printf failure >&2; exit 7' })); + expect(result.error).toBe(true); + expect(result.content).toContain('failure'); + expect(result.content).toContain('code 7'); + }); + + it('cancels a command and permits a later turn', async () => { + const ws = createWorkspace({ root, shell: true, confirm: allow }); + const pending = ws.execute(call('local_shell', { command: 'sleep 2; touch never.txt' })); + await Bun.sleep(50); + ws.cancel(); + expect((await pending).error).toBe(true); + expect((await ws.execute(call('local_shell', { command: 'printf next' }))).content).toBe( + 'next', + ); + await Bun.sleep(2100); + expect(existsSync(join(root, 'never.txt'))).toBe(false); + }); + + it('does not write when confirmation arrives after cancellation', async () => { + let answer: (ok: boolean) => void = () => {}; + const ws = createWorkspace({ + root, + confirm: () => + new Promise((resolve) => { + answer = resolve; + }), + }); + const pending = ws.execute(call('local_write', { path: 'never.txt', content: 'late' })); + await Bun.sleep(30); + ws.cancel(); + expect((await pending).error).toBe(true); + answer(true); + await Bun.sleep(30); + expect(existsSync(join(root, 'never.txt'))).toBe(false); + }); +}); + +describe('local_open', () => { + it('shows a contained text file through the viewer', async () => { + const openFile = vi.fn(async (_body: string, _name: string) => {}); + const result = await createWorkspace({ root, confirm: allow, openFile }).execute( + call('local_open', { target: 'src/api.ts' }), + ); + expect(result.error).toBeUndefined(); + expect(openFile).toHaveBeenCalledWith('export const x = 1;\n', 'api.ts'); + }); + it('refuses an escaped file without calling the viewer', async () => { + const openFile = vi.fn(async () => {}); + const result = await createWorkspace({ root, confirm: allow, openFile }).execute( + call('local_open', { target: join(outside, 'secret') }), + ); + expect(result.error).toBe(true); + expect(openFile).not.toHaveBeenCalled(); + }); + it('returns web links without launching a process', async () => { + const result = await permissive().execute( + call('local_open', { target: 'https://example.com/docs' }), + ); + expect(result.error).toBeUndefined(); + expect(result.content).toContain('https://example.com/docs'); + }); +}); + +it('bounds native command output without blocking the child', async () => { + const ws = createWorkspace({ root, shell: true, confirm: allow }); + const result = await ws.execute(call('local_shell', { command: 'yes x | head -c 210000' })); + expect(result.error).toBeUndefined(); + expect(result.content).toContain('output truncated at 200000 bytes'); + expect(result.content.length).toBeLessThan(200100); +}); + +it('reports viewer errors to the model', async () => { + const ws = createWorkspace({ + root, + confirm: allow, + openFile: async () => { + throw new Error('pager failed'); + }, + }); + const result = await ws.execute(call('local_open', { target: 'src/api.ts' })); + expect(result.error).toBe(true); + expect(result.content).toContain('pager failed'); +}); diff --git a/package.json b/package.json index b3b1e88c..49e60b55 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "@biomejs/biome": "^2.4.15", "@cloudflare/workers-types": "catalog:", "@types/node": "^25.7.0", + "@types/react": "catalog:", "turbo": "^2.5.8", "typescript": "catalog:", "vite": "catalog:" diff --git a/packages/cowork-client/src/client-tools.ts b/packages/cowork-client/src/client-tools.ts index f648a85c..34212727 100644 --- a/packages/cowork-client/src/client-tools.ts +++ b/packages/cowork-client/src/client-tools.ts @@ -2,6 +2,7 @@ import { type ClientToolOptions, type ClientToolRequest, type ClientToolResult, + DEFAULT_CLIENT_TOOL_TIMEOUT_MS, isLocalFileTool, type LocalFs, runLocalFileTool, @@ -9,6 +10,7 @@ import { } from '@felix/client'; import { clearMount, + getMountIdentity, getMountLabel, hasMount, mountList, @@ -33,7 +35,13 @@ function joinPath(cwd: string, p: string): string { return `${cwd.replace(/\/$/, '')}/${p}`.replace(/^\.\//, ''); } -async function runLocalShell(command: string, cwd: string, vfs: VirtualFs): Promise { +async function runLocalShell( + command: string, + cwd: string, + vfs: VirtualFs, + check: () => void, +): Promise { + check(); const trimmed = command.trim(); if (!trimmed) return ''; @@ -59,12 +67,12 @@ async function runLocalShell(command: string, cwd: string, vfs: VirtualFs): Prom return mounted ? await mountRead(join(arg)) : vfs.read(join(arg)); } case 'echo': { - if (rest.includes('>')) { - const idx = rest.indexOf('>'); - const text = rest.slice(0, idx).join(' '); - const path = rest.slice(idx + 1).join(' '); + const redirect = /^(.*?)>\s*(\S.*)$/.exec(rest.join(' ')); + if (redirect) { + const text = redirect[1]?.trim() ?? ''; + const path = (redirect[2] ?? '').trim().replace(/^['"]|['"]$/g, ''); if (!path) return 'usage: echo text > path'; - if (mounted) await mountWrite(join(path), `${text}\n`); + if (mounted) await mountWrite(join(path), `${text}\n`, false, check); else vfs.write(join(path), `${text}\n`); return ''; } @@ -72,7 +80,7 @@ async function runLocalShell(command: string, cwd: string, vfs: VirtualFs): Prom } case 'mkdir': { if (!arg) return 'usage: mkdir '; - if (mounted) await mountMkdir(join(arg)); + if (mounted) await mountMkdir(join(arg), check); else vfs.mkdir(join(arg)); return ''; } @@ -83,7 +91,8 @@ async function runLocalShell(command: string, cwd: string, vfs: VirtualFs): Prom if (mounted) await mountRead(path); else vfs.read(path); } catch { - if (mounted) await mountWrite(path, ''); + check(); + if (mounted) await mountWrite(path, '', false, check); else vfs.write(path, ''); } return ''; @@ -106,22 +115,32 @@ async function runLocalShell(command: string, cwd: string, vfs: VirtualFs): Prom * `local_edit`, `local_delete` and `local_rename` with an approval, so a write reaches this point only after a person said * yes on the banner, which is where the diff is drawn. */ -export function workspaceFs(vfs: VirtualFs): LocalFs { +export function workspaceFs(vfs: VirtualFs, check: () => void = () => {}): LocalFs { + const checked = async (work: () => T | Promise): Promise => { + check(); + const result = await work(); + check(); + return result; + }; return { - list: async (path) => (hasMount() ? await mountList(path || '.') : vfs.list(path || '.')), - read: async (path) => (hasMount() ? await mountRead(path) : vfs.read(path)), + list: async (path) => + checked(() => (hasMount() ? mountList(path || '.') : vfs.list(path || '.'))), + read: async (path) => checked(() => (hasMount() ? mountRead(path) : vfs.read(path))), write: async (path, content, { append }) => { - if (hasMount()) await mountWrite(path, content, append); + check(); + if (hasMount()) await mountWrite(path, content, append, check); else vfs.write(path, content, append); }, // Files only, never overwriting — the same rules the operator's pane // follows, through the same helpers, gated by the same approval rule. remove: async (path) => { - if (hasMount()) await mountRemove(path); + check(); + if (hasMount()) await mountRemove(path, check); else vfs.remove(path); }, rename: async (path, toPath) => { - if (hasMount()) await mountRename(path, toPath); + check(); + if (hasMount()) await mountRename(path, toPath, check); else vfs.rename(path, toPath); }, }; @@ -149,22 +168,57 @@ export async function executeClientTool( vfs: VirtualFs, opts: BrowserToolOptions = {}, ): Promise { - const { openFile, ...settle } = opts; - return settleClientTool(req, () => runClientTool(req, vfs, openFile), settle); + const controller = new AbortController(); + const signal = opts.signal + ? AbortSignal.any([opts.signal, controller.signal]) + : controller.signal; + const mount = getMountIdentity(); + const check = () => { + signal.throwIfAborted(); + if (getMountIdentity() !== mount) + throw new Error('workspace changed while the tool was running'); + }; + const timeoutMs = opts.timeoutMs ?? DEFAULT_CLIENT_TOOL_TIMEOUT_MS; + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + controller.abort(); + }, timeoutMs); + try { + const result = await settleClientTool( + req, + () => runClientTool(req, vfs, opts.openFile, check), + { signal, timeoutMs }, + ); + return timedOut + ? { content: `error: ${req.name} timed out after ${timeoutMs}ms`, error: true } + : result; + } finally { + clearTimeout(timer); + } } async function runClientTool( req: ClientToolRequest, vfs: VirtualFs, - openFile?: (path: string) => void, + openFile: ((path: string) => void) | undefined, + check: () => void, ): Promise { try { - if (isLocalFileTool(req.name)) return await runLocalFileTool(req, workspaceFs(vfs)); + check(); + if (isLocalFileTool(req.name)) return await runLocalFileTool(req, workspaceFs(vfs, check)); if (req.name === 'local_shell') { const command = asString(req.args.command); const cwd = asString(req.args.cwd); - const content = await runLocalShell(command, cwd, vfs); - return { content: content || '(ok)' }; + const content = await runLocalShell(command, cwd, vfs, check); + return { + content: content || '(ok)', + ...(content.startsWith('unsupported') || + content.startsWith('usage:') || + content.startsWith('error:') + ? { error: true } + : {}), + }; } if (req.name === 'local_open') { const target = asString(req.args.target); @@ -182,6 +236,7 @@ async function runClientTool( if ((await readExisting(cleaned, vfs)) === null) { return { content: `error: no such file: ${cleaned}`, error: true }; } + check(); openFile(cleaned); return { content: JSON.stringify({ opened: cleaned, kind: 'file', in: 'side_pane' }) }; } diff --git a/packages/cowork-client/src/fs-mount.ts b/packages/cowork-client/src/fs-mount.ts index 9408c333..ad339814 100644 --- a/packages/cowork-client/src/fs-mount.ts +++ b/packages/cowork-client/src/fs-mount.ts @@ -10,6 +10,33 @@ export type DirHandle = FileSystemDirectoryHandle; let root: DirHandle | null = null; let mountName = ''; +/** Identity only: callers pin the store across an asynchronous tool call. */ +export function getMountIdentity(): object | null { + return root; +} + +/** Revalidate a request after an awaited handle operation, before its next mutation. */ +type MutationCheck = () => void; +const unchecked: MutationCheck = () => {}; + +async function writeAndCommit( + writable: FileSystemWritableFileStream, + data: string | Uint8Array, + check: MutationCheck, +): Promise { + try { + check(); + await writable.write(data); + check(); + await writable.close(); + } catch (error) { + // A stream's writes are staged until close. Abort drops those changes; a + // browser operation already committed before cancellation is not rolled back. + await writable.abort().catch(() => {}); + throw error; + } +} + /** `queryPermission`/`requestPermission` are not in the DOM lib yet. */ type PermissionCapableHandle = DirHandle & { queryPermission?: (opts: { mode: 'readwrite' }) => Promise; @@ -136,8 +163,9 @@ function splitContainedPath(path: string): string[] { async function resolve( path: string, - opts: { create?: boolean } = {}, + opts: { create?: boolean; check?: MutationCheck } = {}, ): Promise<{ parent: DirHandle; name: string }> { + opts.check?.(); if (!root) throw new Error('no folder mounted'); const parts = splitContainedPath(path); if (parts.length === 0) return { parent: root, name: '' }; @@ -146,6 +174,7 @@ async function resolve( for (let i = 0; i < parts.length - 1; i++) { const part = parts[i]!; dir = await dir.getDirectoryHandle(part, { create: opts.create }); + opts.check?.(); } const name = parts[parts.length - 1]!; return { parent: dir, name }; @@ -190,30 +219,41 @@ export async function mountReadBytes(path: string): Promise { return new Uint8Array(await file.arrayBuffer()); } -export async function mountWrite(path: string, content: string, append = false): Promise { - const { parent, name } = await resolve(path, { create: true }); +export async function mountWrite( + path: string, + content: string, + append = false, + check: MutationCheck = unchecked, +): Promise { + const { parent, name } = await resolve(path, { create: true, check }); + check(); if (!name) throw new Error('not a file'); const fileHandle = await parent.getFileHandle(name, { create: true }); + check(); let next = content; if (append) { try { const existing = await (await fileHandle.getFile()).text(); + check(); next = existing + content; } catch { // new file } } + check(); const writable = await fileHandle.createWritable(); - await writable.write(next); - await writable.close(); + await writeAndCommit(writable, next, check); } -export async function mountMkdir(path: string): Promise { +export async function mountMkdir(path: string, check: MutationCheck = unchecked): Promise { + check(); const parts = splitContainedPath(path); if (!root || !parts.length) throw new Error('invalid path'); let dir = root; for (const part of parts) { + check(); dir = await dir.getDirectoryHandle(part, { create: true }); + check(); } } @@ -300,12 +340,14 @@ export class TargetExistsError extends Error { } /** Delete one file in the mounted folder. A directory is refused. */ -export async function mountRemove(path: string): Promise { - const { parent, name } = await resolve(path); +export async function mountRemove(path: string, check: MutationCheck = unchecked): Promise { + const { parent, name } = await resolve(path, { check }); + check(); if (!name) throw new Error('not a file'); // Asked for as a file first, so a folder of the same name is refused rather // than removed: `removeEntry` takes either. await parent.getFileHandle(name); + check(); await parent.removeEntry(name); } @@ -316,12 +358,19 @@ export async function mountRemove(path: string): Promise { * written in full before anything is removed, and a failure after the write * leaves two copies, never none. */ -export async function mountRename(from: string, to: string): Promise { - const src = await resolve(from); +export async function mountRename( + from: string, + to: string, + check: MutationCheck = unchecked, +): Promise { + const src = await resolve(from, { check }); + check(); if (!src.name) throw new Error('not a file'); const handle = await src.parent.getFileHandle(src.name); const bytes = new Uint8Array(await (await handle.getFile()).arrayBuffer()); - const dst = await resolve(to, { create: true }); + check(); + const dst = await resolve(to, { create: true, check }); + check(); if (!dst.name) throw new Error('no destination'); const taken = await dst.parent .getFileHandle(dst.name) @@ -332,11 +381,13 @@ export async function mountRename(from: string, to: string): Promise { .then(() => true) .catch(() => false), ); + check(); if (taken) throw new TargetExistsError(to); const out = await dst.parent.getFileHandle(dst.name, { create: true }); + check(); const writable = await out.createWritable(); - await writable.write(bytes); - await writable.close(); + await writeAndCommit(writable, bytes, check); + check(); await src.parent.removeEntry(src.name); } diff --git a/packages/cowork-client/tests/client-tools.test.ts b/packages/cowork-client/tests/client-tools.test.ts index 45b658ef..d786f279 100644 --- a/packages/cowork-client/tests/client-tools.test.ts +++ b/packages/cowork-client/tests/client-tools.test.ts @@ -156,3 +156,56 @@ describe('executeClientTool', () => { expect(Number.isFinite(DEFAULT_CLIENT_TOOL_TIMEOUT_MS)).toBe(true); }); }); + +it('reports unsupported browser commands as failures', async () => { + const result = await executeClientTool( + { id: 'build', name: 'local_shell', args: { command: 'npm test' } }, + vfs, + ); + expect(result.error).toBe(true); + expect(result.content).toContain('unsupported'); +}); + +it('supports compact echo redirection instead of falsely reporting a write', async () => { + const result = await executeClientTool( + { id: 'write', name: 'local_shell', args: { command: 'echo hello >notes.md' } }, + vfs, + ); + expect(result.error).toBeUndefined(); + expect(vfs.read('notes.md')).toBe('hello\n'); +}); + +it.each([ + 'abort', + 'timeout', +])('never resumes an edit after %s settles the request', async (reason) => { + vfs.write('code.ts', 'before'); + let finish!: (text: string) => void; + const read = vi.spyOn(vfs, 'read').mockImplementation( + () => + new Promise((resolve) => { + finish = resolve; + }) as unknown as string, + ); + const write = vi.spyOn(vfs, 'write'); + const controller = new AbortController(); + const pending = executeClientTool( + { + id: 'late-edit', + name: 'local_edit', + args: { path: 'code.ts', old_string: 'before', new_string: 'after' }, + }, + vfs, + { signal: controller.signal, timeoutMs: reason === 'timeout' ? 20 : 500 }, + ); + if (reason === 'abort') controller.abort(); + try { + expect((await pending).error).toBe(true); + finish('before'); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(write).not.toHaveBeenCalled(); + } finally { + read.mockRestore(); + write.mockRestore(); + } +}); diff --git a/packages/cowork-client/tests/fs-mount.test.ts b/packages/cowork-client/tests/fs-mount.test.ts index 47fc6b42..ec0b8554 100644 --- a/packages/cowork-client/tests/fs-mount.test.ts +++ b/packages/cowork-client/tests/fs-mount.test.ts @@ -1,4 +1,5 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { executeClientTool } from '../src/client-tools'; import { clearMount, getMountLabel, @@ -20,6 +21,7 @@ import { supportsDirectoryPicker, TargetExistsError, } from '../src/fs-mount'; +import { getVfs } from '../src/vfs'; /** * The mount is a real folder on the user's disk, reached through the File @@ -417,3 +419,97 @@ describe('folders in the mount', () => { await expect(mountRead('src/a.ts')).rejects.toThrow(); }); }); + +it('aborts an uncommitted write when the request is stopped', async () => { + const file = await root.getFileHandle('code.ts', { create: true }); + file.content = 'before'; + const controller = new AbortController(); + const writable = { + write: vi.fn(async () => {}), + close: vi.fn(async () => {}), + abort: vi.fn(async () => {}), + }; + vi.spyOn(file, 'createWritable').mockImplementation(async () => { + controller.abort(); + return writable; + }); + await expect( + mountWrite('code.ts', 'after', false, () => controller.signal.throwIfAborted()), + ).rejects.toThrow(); + expect(writable.abort).toHaveBeenCalledOnce(); + expect(writable.close).not.toHaveBeenCalled(); + expect(file.content).toBe('before'); +}); + +it('does not delete a rename source after the call is stopped', async () => { + const file = await root.getFileHandle('old.ts', { create: true }); + file.content = 'source'; + const controller = new AbortController(); + const original = file.getFile.bind(file); + vi.spyOn(file, 'getFile').mockImplementation(async () => { + const result = await original(); + controller.abort(); + return result; + }); + await expect( + mountRename('old.ts', 'new.ts', () => controller.signal.throwIfAborted()), + ).rejects.toThrow(); + expect(root.children.has('old.ts')).toBe(true); + expect(root.children.has('new.ts')).toBe(false); +}); + +it.each(['unmount', 'replace'])('never redirects an edit after a workspace %s', async (change) => { + const vfs = getVfs(`workspace-change-${change}`); + vfs.reset(); + const file = await root.getFileHandle('code.ts', { create: true }); + file.content = 'before'; + const replacement = new MockDirHandle('project'); + const other = await replacement.getFileHandle('code.ts', { create: true }); + other.content = 'other folder'; + const original = file.getFile.bind(file); + vi.spyOn(file, 'getFile').mockImplementation(async () => { + if (change === 'unmount') clearMount(); + else { + ( + window as unknown as { showDirectoryPicker: () => Promise } + ).showDirectoryPicker = async () => replacement; + await pickDirectory(); + } + return original(); + }); + const result = await executeClientTool( + { + id: 'edit-moved-workspace', + name: 'local_edit', + args: { path: 'code.ts', old_string: 'before', new_string: 'after' }, + }, + vfs, + ); + expect(result.error).toBe(true); + expect(result.content).toContain('workspace changed'); + expect(file.content).toBe('before'); + expect(other.content).toBe('other folder'); + expect(vfs.list()).toEqual([]); +}); + +it('aborts staged content instead of closing it when Stop arrives during write', async () => { + const file = await root.getFileHandle('code.ts', { create: true }); + file.content = 'before'; + const controller = new AbortController(); + const writable = { + write: vi.fn(async () => { + controller.abort(); + }), + close: vi.fn(async () => { + file.content = 'after'; + }), + abort: vi.fn(async () => {}), + }; + vi.spyOn(file, 'createWritable').mockResolvedValue(writable); + await expect( + mountWrite('code.ts', 'after', false, () => controller.signal.throwIfAborted()), + ).rejects.toThrow(); + expect(writable.abort).toHaveBeenCalledOnce(); + expect(writable.close).not.toHaveBeenCalled(); + expect(file.content).toBe('before'); +}); diff --git a/packages/felix-client/src/engine.ts b/packages/felix-client/src/engine.ts index d8cd496d..6c48c2a2 100644 --- a/packages/felix-client/src/engine.ts +++ b/packages/felix-client/src/engine.ts @@ -54,6 +54,7 @@ import { import { OPEN_FILE_TOOL, openedPath } from './open-file'; import { reattachThread } from './reattach'; import { eventsToTurns } from './session-log'; +import { classifyToolResult } from './tool-results'; import type { FelixClient } from './transport'; import { closeTool, markToolPhase, type Turn, toolImages, type WorkspaceEdit } from './turns'; import { describeWorkspaceEdit, workspaceEditOf } from './workspace-edits'; @@ -79,6 +80,8 @@ export interface EngineState { } export interface ClientToolPort { + /** Cancel underlying local work on Stop or a thread reset. */ + cancel?(): void; /** Run the tool the harness handed back, and never throw — a hang costs the run. */ execute(req: { id: string; @@ -345,6 +348,13 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { * folder for one call. */ const takenToolRequests = new Set(); + let toolGeneration = 0; + const pendingClientTools = new Set(); + const cancelClientTools = () => { + toolGeneration++; + pendingClientTools.clear(); + ports.clientTools?.cancel?.(); + }; let controller: AbortController | null = null; /** @@ -749,19 +759,54 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { })); // The run is blocked on this. A client with no executor still has to // answer, or the harness waits out the tool's timeout for nothing. - const result = ports.clientTools - ? await ports.clientTools.execute({ id: data.id, name: data.name, args: data.args ?? {} }) - : { content: `error: this client cannot run ${data.name}`, error: true }; - await ports.client.postToolResult({ - threadId: ports.threadId(), - toolCallId: data.id, - content: result.content, - error: result.error, - }); - patch((t) => ({ - ...t, - tools: closeTool(t.tools, `client · ${data.name}`, result.content, data.id), - })); + const threadId = ports.threadId(); + const generation = toolGeneration; + const pending = Symbol(data.id); + const stream = liveStream; + pendingClientTools.add(pending); + try { + let result: { content: string; error?: boolean }; + try { + result = ports.clientTools + ? await ports.clientTools.execute({ + id: data.id, + name: data.name, + args: data.args ?? {}, + }) + : { content: `error: this client cannot run ${data.name}`, error: true }; + } catch (error) { + result = { + content: `error: ${error instanceof Error ? error.message : String(error)}`, + error: true, + }; + } + // A stopped or replaced turn must never submit a late result to the + // thread that happens to be selected now, nor patch its transcript. + if (generation !== toolGeneration || ports.threadId() !== threadId) break; + await ports.client.postToolResult({ + threadId, + toolCallId: data.id, + content: result.content, + error: result.error, + }); + if (generation !== toolGeneration || ports.threadId() !== threadId) break; + // The local card sees the raw client result before the harness + // adds its failure marker. Preserve the explicit error bit here too. + const name = `client · ${data.name}`; + const output = + result.error && !classifyToolResult(name, result.content) + ? `[tool error/provider_error] ${result.content}` + : result.content; + patch((t) => ({ + ...t, + tools: closeTool(t.tools, name, output, data.id), + })); + } finally { + pendingClientTools.delete(pending); + // SSE dispatch awaits this handler, so no heartbeat can be read + // during the command. Give the reader a fresh liveness window. + if (stream && liveStream === stream) stream.lastActivityAt = Date.now(); + } break; } // Nothing to read here: the harness puts its in-process `InvokeOutput` on this @@ -1041,22 +1086,26 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { threadId, signal: follow.signal, holdOpen: true, - onTurns: adoptTurns, - onEvent: (ev) => applyEvent(ev), + onTurns: (turns) => { + if (!signal.aborted) adoptTurns(turns); + }, + onEvent: (ev) => (signal.aborted ? Promise.resolve() : applyEvent(ev)), }) : Promise.resolve(); let run: DurableRun; try { run = await ports.client.pollDurableRun(token, { signal, - onTick: (r) => tick(r.status || 'pending'), + onTick: (r) => { + if (!signal.aborted) tick(r.status || 'pending'); + }, }); } finally { signal.removeEventListener('abort', stopFollowing); follow.abort(); await followed; } - finishDurable(run); + if (!signal.aborted) finishDurable(run); }; /** @@ -1097,7 +1146,10 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { /** What every run leaves behind, however it ended. */ const endRun = (ctrl: AbortController) => { - if (controller === ctrl) controller = null; + // A stopped send may still be awaiting its executor when a new send starts. + // Only the current run owns the transcript and the streaming/phase flags. + if (controller !== ctrl) return; + controller = null; replayPrefix = null; replayEvents = []; // Stopped on purpose: nothing is left for a reload to rejoin. @@ -1125,6 +1177,7 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { if (state.streaming) return; const ctrl = new AbortController(); controller = ctrl; + if (resumeToken !== token) takenToolRequests.clear(); activeAssistantId = newId(); resumeToken = token; lastEventId = undefined; @@ -1148,6 +1201,12 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { const send = async (args: SendArgs): Promise => { const mode = args.mode ?? 'stream'; + if (controller && !controller.signal.aborted) { + controller.abort(); + cancelClientTools(); + } + // Deduplicate tool requests within this run, not the engine's lifetime. + takenToolRequests.clear(); activeAssistantId = args.assistantId; const ctrl = new AbortController(); @@ -1208,13 +1267,16 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { }, { onOpen: ({ replayed }) => { + if (ctrl.signal.aborted || controller !== ctrl) return; opened = true; if (!replayed) return; replayPrefix = beforeRun(); replayEvents = []; }, - onEvent: (ev) => applyEvent(ev), + onEvent: (ev) => + ctrl.signal.aborted || controller !== ctrl ? Promise.resolve() : applyEvent(ev), onCursor: (id) => { + if (ctrl.signal.aborted || controller !== ctrl) return; lastEventId = id; }, onActivity: ({ keepAlive }) => { @@ -1263,9 +1325,14 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { client: ports.client, threadId, signal: ctrl.signal, - onTurns: (rebuilt) => set({ turns: rebuilt }), - onPhase: (phase) => set({ phase }), - onEvent: (ev) => applyEvent(ev), + onTurns: (rebuilt) => { + if (!ctrl.signal.aborted && controller === ctrl) set({ turns: rebuilt }); + }, + onPhase: (phase) => { + if (!ctrl.signal.aborted && controller === ctrl) set({ phase }); + }, + onEvent: (ev) => + ctrl.signal.aborted || controller !== ctrl ? Promise.resolve() : applyEvent(ev), }); } finally { set({ reattaching: false }); @@ -1294,9 +1361,14 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { threadId, lastEventId, signal: ctrl.signal, - onTurns: (rebuilt) => set({ turns: rebuilt }), - onPhase: (phase) => set({ phase }), - onEvent: (ev) => applyEvent(ev), + onTurns: (rebuilt) => { + if (!ctrl.signal.aborted && controller === ctrl) set({ turns: rebuilt }); + }, + onPhase: (phase) => { + if (!ctrl.signal.aborted && controller === ctrl) set({ phase }); + }, + onEvent: (ev) => + ctrl.signal.aborted || controller !== ctrl ? Promise.resolve() : applyEvent(ev), }); } finally { set({ reattaching: false }); @@ -1312,6 +1384,7 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { try { await run(); } catch (err) { + if (ctrl.signal.aborted || controller !== ctrl) return 'done'; if (err instanceof RunInProgressError) { outcome = 'run_in_progress'; refusedFor = err.resumeToken; @@ -1381,6 +1454,11 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { }, setTurns: adoptTurns, reset() { + controller?.abort(); + controller = null; + liveStream = null; + cancelClientTools(); + takenToolRequests.clear(); seenApprovals.clear(); activeAssistantId = ''; resumeToken = null; @@ -1388,6 +1466,8 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { lastEventId = undefined; set({ turns: [], + streaming: false, + reattaching: false, error: null, phase: 'idle', approvals: [], @@ -1400,7 +1480,8 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { applyEvent, checkLiveness(now = Date.now()) { const stream = liveStream; - if (!stream || now - stream.lastActivityAt < STREAM_STALL_MS) return false; + if (!stream || pendingClientTools.size || now - stream.lastActivityAt < STREAM_STALL_MS) + return false; // A durable run's stream carries status, not deltas, and never heartbeats. const proved = stream.heartbeats || (harnessHeartbeats && resumeToken === null); if (!proved) return false; @@ -1495,8 +1576,8 @@ export function createChatEngine(ports: EnginePorts): ChatEngine { set({ permissionMode: mode === 'default' ? null : mode }); }, abort() { + cancelClientTools(); controller?.abort(); - controller = null; }, }; } diff --git a/packages/felix-client/tests/engine.test.ts b/packages/felix-client/tests/engine.test.ts index 264db331..ab5322e8 100644 --- a/packages/felix-client/tests/engine.test.ts +++ b/packages/felix-client/tests/engine.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { createChatEngine } from '../src/engine'; +import { classifyToolResult } from '../src/tool-results'; import { createFelixClient } from '../src/transport'; /** @@ -1230,3 +1231,184 @@ describe('inspect', () => { expect(engine.inspect().stream).toBeNull(); }); }); + +describe('client tool lifecycle', () => { + it('does not post a late tool result to another thread', async () => { + let thread = 't1'; + let finish!: (result: { content: string }) => void; + const execute = vi.fn( + () => + new Promise<{ content: string }>((resolve) => { + finish = resolve; + }), + ); + const engine = engineOn([], { threadId: () => thread, clientTools: { execute } }); + const pending = engine.applyEvent({ + event: 'tool_request', + data: { id: 'late', name: 'local_shell', args: {} }, + }); + thread = 't2'; + engine.reset(); + finish({ content: 'old output' }); + await pending; + expect(posted.some((p) => p.url.includes('/chat/tool_result'))).toBe(false); + expect(engine.state.turns).toEqual([]); + }); + + it('cancels local work on abort and ignores the late result', async () => { + let finish!: (result: { content: string }) => void; + const cancel = vi.fn(); + const execute = () => + new Promise<{ content: string }>((resolve) => { + finish = resolve; + }); + const engine = engineOn([], { clientTools: { execute, cancel } }); + const pending = engine.applyEvent({ + event: 'tool_request', + data: { id: 'aborted', name: 'local_shell', args: {} }, + }); + engine.abort(); + finish({ content: 'late' }); + await pending; + expect(cancel).toHaveBeenCalledOnce(); + expect(posted.some((p) => p.url.includes('/chat/tool_result'))).toBe(false); + }); + + it('posts an executor exception as a failed tool result', async () => { + const engine = engineOn([], { + clientTools: { + execute: async () => { + throw new Error('disk unavailable'); + }, + }, + }); + await engine.applyEvent({ + event: 'tool_request', + data: { id: 'failed', name: 'local_read', args: {} }, + }); + expect(posted.find((p) => p.url.includes('/chat/tool_result'))?.body).toMatchObject({ + thread_id: 't1', + error: true, + content: 'error: disk unavailable', + }); + }); + + it('does not declare a stream dead while its reader awaits a local command', async () => { + let finish!: (result: { content: string }) => void; + const execute = vi.fn( + () => + new Promise<{ content: string }>((resolve) => { + finish = resolve; + }), + ); + const engine = engineOn([], { clientTools: { execute } }); + stubFetch((url) => + url.endsWith('/chat/stream') + ? new Response( + ': keep-alive\n\ndata: ' + + JSON.stringify({ + event: 'tool_request', + data: { id: 'slow', name: 'local_shell', args: {} }, + }) + + '\n\ndata: [DONE]\n\n', + { headers: { 'content-type': 'text/event-stream' } }, + ) + : new Response('{}'), + ); + const pending = run(engine); + await until(() => execute.mock.calls.length === 1); + try { + expect(engine.checkLiveness(Date.now() + 60_000)).toBe(false); + } finally { + finish({ content: 'done' }); + await pending; + } + }); +}); + +it('draws an explicitly failed client command as failed even with diagnostic output first', async () => { + const engine = engineOn( + [{ event: 'tool_request', data: { id: 'bad-build', name: 'local_shell', args: {} } }], + { + clientTools: { + execute: async () => ({ content: 'compiling...\ncommand exited with code 1', error: true }), + }, + }, + ); + await run(engine); + const tool = engine.state.turns.at(-1)?.tools?.[0]; + expect(tool).toBeDefined(); + expect(classifyToolResult(tool!.name, tool!.output)?.kind).toBe('failed'); + expect(posted.find((p) => p.url.includes('/chat/tool_result'))?.body).toMatchObject({ + error: true, + }); +}); + +describe('starting a later coding turn', () => { + it('permits the same model tool-call id in a later turn', async () => { + const execute = vi.fn(async () => ({ content: 'ok' })); + const frame = { + event: 'tool_request', + data: { id: 'reused', name: 'local_read', args: { path: 'code.ts' } }, + }; + const engine = engineOn([frame, frame], { clientTools: { execute } }); + await run(engine); + await run(engine); + expect(execute).toHaveBeenCalledTimes(2); // one per turn, despite each stream's duplicate + }); + + it('forgets consumed request ids when the thread is reset', async () => { + const execute = vi.fn(async () => ({ content: 'ok' })); + const engine = engineOn([], { clientTools: { execute } }); + const frame = { + event: 'tool_request' as const, + data: { id: 'reused', name: 'local_read', args: {} }, + }; + await engine.applyEvent(frame); + engine.reset(); + await engine.applyEvent(frame); + expect(execute).toHaveBeenCalledTimes(2); + }); + + it('does not let an aborted send finishing late settle the next send', async () => { + const finish: Array<(result: { content: string }) => void> = []; + const execute = vi.fn( + () => + new Promise<{ content: string }>((resolve) => { + finish.push(resolve); + }), + ); + const engine = engineOn([], { clientTools: { execute } }); + let stream = 0; + stubFetch((url) => + url.endsWith('/chat/stream') + ? sse([ + { + event: 'tool_request', + data: { id: `call-${++stream}`, name: 'local_shell', args: {} }, + }, + ]) + : new Response('{}'), + ); + const old = run(engine); + await until(() => execute.mock.calls.length === 1); + engine.abort(); + engine.setTurns([{ id: 'a2', role: 'assistant', content: '', tools: [] }]); + const next = engine.send({ + manifest: 'code', + assistantId: 'a2', + messages: [{ role: 'user', content: 'next task' }], + }); + await until(() => execute.mock.calls.length === 2); + try { + finish[0]?.({ content: 'old output' }); + await old; + expect(engine.state.streaming).toBe(true); + expect(engine.state.turns[0]?.tools?.[0]?.done).toBe(false); + } finally { + finish[1]?.({ content: 'new output' }); + await next; + } + expect(engine.state.streaming).toBe(false); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e900cd28..8c26500d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -107,6 +107,9 @@ importers: '@types/node': specifier: ^25.7.0 version: 25.7.0 + '@types/react': + specifier: 'catalog:' + version: 19.2.18 turbo: specifier: ^2.5.8 version: 2.10.4 diff --git a/scripts/harness-events.json b/scripts/harness-events.json index 239e8e5a..fc4c878d 100644 --- a/scripts/harness-events.json +++ b/scripts/harness-events.json @@ -1,6 +1,6 @@ { "$comment": "Every SSE event the harness can emit, recorded from a checkout by scripts/sync-harness-contract.mjs. check-protocol-parity fails when one of these has no StreamEvent arm — the direction the type system cannot see, because the union ends in an open arm. Do not hand-edit: re-run the sync.", - "harnessCommit": "0958f1ed", + "harnessCommit": "cb4dde08", "harnessVersion": "0.19.2", "eventsSource": "schemas/sse-events.json", "normalised": { diff --git a/scripts/harness-payloads.json b/scripts/harness-payloads.json index 7e0884a4..219583eb 100644 --- a/scripts/harness-payloads.json +++ b/scripts/harness-payloads.json @@ -1,6 +1,6 @@ { "$comment": "The key set of every row the harness serialises, recorded from a checkout by scripts/sync-harness-contract.mjs. check-payload-shapes fails when a client type requires a field that is not in one of these sets — the `payload` vs `payload_json` bug, which typechecks, lints, drifts past check-api-drift (it reads paths, not shapes) and renders `undefined` forever. Do not hand-edit: re-run the sync.", - "harnessCommit": "0958f1ed", + "harnessCommit": "cb4dde08", "harnessVersion": "0.19.2", "unreadable": [ "felix/a2a/tasks.py:_task_dict", diff --git a/scripts/harness-tool-results.json b/scripts/harness-tool-results.json index a1841d2e..655b4bbe 100644 --- a/scripts/harness-tool-results.json +++ b/scripts/harness-tool-results.json @@ -1,6 +1,6 @@ { "$comment": "Every prefix the harness counts as a failed tool result, recorded from a checkout by scripts/sync-harness-contract.mjs. tool-results.test.ts fails on one it has no sample for: an unread prefix draws a green `done` on a call that failed, and no other check reads tool output. Do not hand-edit: re-run the sync.", - "harnessCommit": "0958f1ed", + "harnessCommit": "cb4dde08", "harnessVersion": "0.19.2", "failurePrefixes": [ "[error/",