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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion apps/chat-ui/src/app-shell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
22 changes: 12 additions & 10 deletions apps/chat-ui/src/components/chat/response.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -76,34 +76,36 @@ const HEADING = {
h6: 'mt-4 mb-1 text-sm font-semibold text-muted-foreground',
} as const;

type MarkdownProps<Tag extends ElementType> = ComponentProps<Tag> & { node?: unknown };

export const responseComponents: Components = {
h1: ({ node: _node, className, ...props }) => (
h1: ({ node: _node, className, ...props }: MarkdownProps<'h1'>) => (
<h1 className={cn(HEADING.h1, 'first:mt-0', className)} {...props} />
),
h2: ({ node: _node, className, ...props }) => (
h2: ({ node: _node, className, ...props }: MarkdownProps<'h2'>) => (
<h2 className={cn(HEADING.h2, 'first:mt-0', className)} {...props} />
),
h3: ({ node: _node, className, ...props }) => (
h3: ({ node: _node, className, ...props }: MarkdownProps<'h3'>) => (
<h3 className={cn(HEADING.h3, 'first:mt-0', className)} {...props} />
),
h4: ({ node: _node, className, ...props }) => (
h4: ({ node: _node, className, ...props }: MarkdownProps<'h4'>) => (
<h4 className={cn(HEADING.h4, 'first:mt-0', className)} {...props} />
),
h5: ({ node: _node, className, ...props }) => (
h5: ({ node: _node, className, ...props }: MarkdownProps<'h5'>) => (
<h5 className={cn(HEADING.h5, 'first:mt-0', className)} {...props} />
),
h6: ({ node: _node, className, ...props }) => (
h6: ({ node: _node, className, ...props }: MarkdownProps<'h6'>) => (
<h6 className={cn(HEADING.h6, 'first:mt-0', className)} {...props} />
),
ul: ({ node: _node, className, ...props }) => (
ul: ({ node: _node, className, ...props }: MarkdownProps<'ul'>) => (
<ul className={cn(LIST, 'list-disc', className)} {...props} />
),
ol: ({ node: _node, className, ...props }) => (
ol: ({ node: _node, className, ...props }: MarkdownProps<'ol'>) => (
<ol className={cn(LIST, 'list-decimal', className)} {...props} />
),
// `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'>) => (
<li
className={cn(
'py-1 [&>p]:inline',
Expand Down
8 changes: 6 additions & 2 deletions apps/chat-ui/src/lib/cowork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | null> {
Expand Down
4 changes: 2 additions & 2 deletions apps/chat-ui/src/routes/harness.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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',
Expand Down
42 changes: 42 additions & 0 deletions apps/chat-ui/tests/app-stream.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<HTMLButtonElement>('[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();
}
});
5 changes: 5 additions & 0 deletions apps/chat-ui/tests/finished-turns-memo.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
20 changes: 20 additions & 0 deletions apps/docs/src/content/guide/terminal.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
11 changes: 11 additions & 0 deletions apps/tui/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
20 changes: 20 additions & 0 deletions apps/tui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
39 changes: 29 additions & 10 deletions apps/tui/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down Expand Up @@ -176,9 +177,20 @@ export function App({
prompt: writePrompt,
answer: answerWrite,
confirm: confirmWrite,
cancel: cancelWrite,
cancel: cancelPrompt,
} = writeGate;

const workspaceRef = useRef<ReturnType<typeof createWorkspace> | null>(null);
const cancelWrite = useCallback(() => {
workspaceRef.current?.cancel();
cancelPrompt();
}, [cancelPrompt]);
useEffect(
() => () => {
workspaceRef.current?.cancel();
},
[],
);
const engineRef = useRef<ChatEngine | null>(null);
/** The open thread's lease, for the client's hooks, which are built before it. */
const leaseRef = useRef<LeaseHold | null>(null);
Expand Down Expand Up @@ -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,
Expand All @@ -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));
}
Expand Down
6 changes: 5 additions & 1 deletion apps/tui/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -130,7 +132,7 @@ export function readConfigFile(path: string): Partial<Config> {
* `--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<string, string | true>;
Expand Down Expand Up @@ -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') } : {}),
},
Expand Down Expand Up @@ -249,6 +252,7 @@ usage: felix [options] [message]
--manifest <name> agent manifest (default ${DEFAULT_MANIFEST})
--thread <id> 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

Expand Down
4 changes: 3 additions & 1 deletion apps/tui/src/pager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}
Loading
Loading