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
4 changes: 4 additions & 0 deletions .fallowrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@
"labs/claude-code-style/src/components/flow-state/tool-grouping.ts",
// and of the registry's error, whose `ErrorDisplay` export its sheet doesn't draw.
"labs/claude-code-style/src/components/flow-state/error.tsx",
// and of the registry's request-recovery, whose interrupted-turn default the failed-turn line doesn't read.
"labs/claude-code-style/src/components/flow-state/request-recovery.tsx",
// The stock shadcn copies the Teammates lab and Shift Manager palettes are built on.
"labs/teammates/src/components/ui/**",
"packages/shift-manager/src/components/ui/command.tsx",
Expand All @@ -121,6 +123,8 @@
"labs/teammates/src/components/flow-state/review-hold.tsx",
// and of the registry's error, whose `ErrorDisplay` export its task popup doesn't draw.
"labs/teammates/src/components/flow-state/error.tsx",
// and of the registry's request-recovery, whose interrupted-turn default the failed-turn line doesn't read.
"labs/teammates/src/components/flow-state/request-recovery.tsx",
// The Teammates lab's byte copy of the registry's connection screen; its
// backoff export is for apps that time their own retries.
"labs/teammates/src/components/flow-state/connection-screen.tsx",
Expand Down
1 change: 1 addition & 0 deletions labs/claude-code-style/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ a package call:
| A result card inside a running turn | `answerAgain: true` on the main worker's flow: the settled task's notice, taken into the turn |
| The main session reading the project's files | `projectSourceCapability({ workspace })` on the `agent` flow, over the coding runs' host; `desk.main` and `desk.researcher` name its `read` preset in their `WORKER.md` |
| Interrupting | aborting the session's running turn; its tasks keep running |
| A failed turn and *Retry* | the engine's `error` item for the turn, drawn by the UI registry's `request-recovery` (installed in `src/components/flow-state/`); Retry is the client's `request(id).retry()`, on the newest turn only |
| The tasks pane and a task's work | the `listTasks_tasks` read (stores nothing per poll), and the items of the task's run session |
| Threads mode's sessions | the same, with `desk.lead`, a `coordinator`, as the main worker |
| A thread card, and *Sent to a task* | the lead's `createTask` call in the session's items |
Expand Down
83 changes: 68 additions & 15 deletions labs/claude-code-style/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* | `openSession` | a new session on the mode's main worker, then `setWorkProject` |
* | `send` | the worker's door, `respond`, in that session |
* | `interrupt` | aborting the session's running request |
* | `retry` | the client's `request(id).retry()` on the session's flow: a failed turn again |
* | `watchThread` | the session's items, followed through the client's `sessionFeed` |
* | | and that feed's connection state, for the connection bar; `loadEarlier` |
* | | is the feed's, for a thread longer than its first read; its running turn |
Expand Down Expand Up @@ -98,7 +99,8 @@ export type ThreadEntry = (
/** Threads mode: the lead's turn filed threads for this line. */
sentToThread?: boolean;
}
| { kind: "assistant"; id: string; text: string }
/** `incomplete` when its turn failed before the reply was finished. */
| { kind: "assistant"; id: string; text: string; incomplete?: boolean }
/** A run of consecutive tool calls in one turn, in words (`toolRun`): one line that opens to a line per call. */
| ({ kind: "tool"; id: string } & ToolRun)
| {
Expand All @@ -112,6 +114,11 @@ export type ThreadEntry = (
duringTurn: boolean;
}
| { kind: "interrupted"; id: string }
/**
* A turn that failed, from the engine's `error` item: its reason, and `retryable` when Retry is
* offered on it: it is the thread's newest turn, and one the engine will run again for you.
*/
| { kind: "failed"; id: string; reason: string; code?: string; details?: Record<string, unknown>; retryable: boolean }
/** Threads mode: a thread the lead filed, where its `createTask` call is. The card reads the task row. */
| { kind: "thread"; id: string; taskId: string }
) & { requestId?: string };
Expand Down Expand Up @@ -201,6 +208,8 @@ export interface LabAdapter {
openSession(mode: ModeId, projectId: string): Promise<SessionRow>;
send(sessionId: string, text: string): Promise<void>;
interrupt(sessionId: string): Promise<void>;
/** Run a failed turn of the session again, as a new request the engine links to `requestId`. */
retry(sessionId: string, requestId: string): Promise<void>;
watchThread(sessionId: string, onChange: (view: ThreadView) => void): Unsubscribe;
watchTasks(sessionId: string, onChange: (rows: TaskRow[]) => void): Unsubscribe;
watchTaskWork(sessionId: string, taskId: string, onChange: (work: TaskWork) => void): Unsubscribe;
Expand Down Expand Up @@ -242,8 +251,15 @@ const UPDATE_TASK_ACTION = taskActionName("updateTask", TASKS_BOARD);
/** The flow a coding worker runs on: its run sessions answer which harness it is (`harness`). */
const CODING_FLOW = "harness-thread";

/** The item types a thread draws. */
const THREAD_ITEMS = ["message", "tool_output"];
/**
* The request sources the engine retries for a caller (`PUBLIC_REENTRY_SOURCES`): a turn that came
* in another way, such as a worker's message (`internal`) or a task's run (`task`), it refuses.
* A copy, since the page can't import the engine; a test pins it to the engine's.
*/
export const RETRYABLE_SOURCES: ReadonlySet<string> = new Set(["http", "mcp", "scheduled"]);

/** The item types a thread draws: a failed turn's `error` item too. */
const THREAD_ITEMS = ["message", "tool_output", "error"];

/** One stored item, as far as the thread reads it. */
export interface Item {
Expand All @@ -265,6 +281,10 @@ export interface Item {
status?: string;
/** A failed `tool_output` item's error: a `SUSPENSION` one is a call waiting on you (`isSuspensionWait`). */
error?: { code?: string };
/** An `error` item's: why its turn failed. */
message?: string;
code?: string;
details?: Record<string, unknown>;
}


Expand Down Expand Up @@ -395,12 +415,16 @@ function filedTaskOf(item: Item): string | undefined {
* and so is a delegate's answer that landed in the conversation as written (a task filed with `resultTo:
* "conversation"`): either way the task's reply is one line, not the session's own words.
* In threads mode (`threads`), a task the lead filed is a thread card where its `createTask` call is, and
* your line is marked when its turn filed one.
* your line is marked when its turn filed one. A failed turn's `error` item is a failed entry, `retryable`
* when it is the newest turn and one of `retryableTurns` (the requests the engine will retry), and a reply
* that turn never finished is marked incomplete.
*/
export function entriesOf(items: readonly Item[], threads = false): ThreadEntry[] {
export function entriesOf(items: readonly Item[], threads = false, retryableTurns: ReadonlySet<string> = new Set()): ThreadEntry[] {
// A turn a user's line started holds that line; a notice's own turn holds none.
const userTurns = new Set(items.filter((item) => item.type === "message" && item.role === "user").map((item) => item.requestId));
const filingTurns = new Set(items.filter((item) => filedTaskOf(item) !== undefined).map((item) => item.requestId));
// A turn that failed; its reply, if it never finished, is marked incomplete. Retry is offered on the newest turn only.
const failedTurns = new Set(items.filter((item) => item.type === "error").map((item) => item.requestId));
const entries: ThreadEntry[] = [];
const runs = new Map<string, ToolCallOf[]>();
for (const item of items) {
Expand All @@ -421,6 +445,18 @@ export function entriesOf(items: readonly Item[], threads = false): ThreadEntry[
else entries.push(entry);
continue;
}
if (item.type === "error") {
entries.push({
kind: "failed",
id: item.id,
reason: item.message ?? "",
...(item.code === undefined ? {} : { code: item.code }),
...(item.details === undefined ? {} : { details: item.details }),
retryable: false,
requestId,
});
continue;
}
const text = textOf(item);
if (item.role === "user") {
entries.push({ kind: "user", id: item.id, text, requestId, ...(threads && filingTurns.has(requestId) ? { sentToThread: true } : {}) });
Expand Down Expand Up @@ -448,9 +484,17 @@ export function entriesOf(items: readonly Item[], threads = false): ThreadEntry[
entries.push({ kind: "result", id: item.id, taskId: answer.taskId, title: `Answer from ${worker}`, status: "completed", summary: resultSummary(text), duringTurn: userTurns.has(requestId), requestId });
continue;
}
if (text.length > 0) entries.push({ kind: "assistant", id: item.id, text, requestId });
if (text.length > 0) {
const incomplete = failedTurns.has(requestId) && item.status !== "completed";
entries.push({ kind: "assistant", id: item.id, text, ...(incomplete ? { incomplete: true } : {}), requestId });
}
}
return entries;
// The newest turn is the one that drew the last entry: an item that draws none (a retried notice,
// an empty message) does not move it.
const newestTurn = entries[entries.length - 1]?.requestId;
return entries.map((entry) =>
entry.kind === "failed" && entry.requestId !== undefined && entry.requestId === newestTurn && retryableTurns.has(entry.requestId) ? { ...entry, retryable: true } : entry,
);
}

/** The adapter the app runs on: the served lab, as the user the page was served for. */
Expand Down Expand Up @@ -571,10 +615,12 @@ export function createWiredLab(fsd: Client): LabAdapter {
);

/** The turns running in a session, oldest first. */
const runningTurns = async (sessionId: string) =>
(await fsd.sessions.requests(sessionId, { status: "in_progress", limit: 50 }))
.filter((request) => TURN_ACTIONS.has(request.actionName))
/** Of a session's requests, its turns still running, oldest first. */
const turnsRunningIn = (requests: Awaited<ReturnType<typeof fsd.sessions.requests>>) =>
requests
.filter((request) => request.status === "in_progress" && TURN_ACTIONS.has(request.actionName))
.sort((a, b) => (a.startedAtMs ?? 0) - (b.startedAtMs ?? 0));
const runningTurns = async (sessionId: string) => turnsRunningIn(await fsd.sessions.requests(sessionId, { status: "in_progress", limit: 50 }));

/** Every item of a session of the types a thread draws (or `types`), every page. */
const itemsOf = async (sessionId: string, types: readonly string[] = THREAD_ITEMS): Promise<Item[]> => {
Expand Down Expand Up @@ -959,19 +1005,22 @@ export function createWiredLab(fsd: Client): LabAdapter {
await fsd.flow(turn.flowId ?? turn.flowKind).request(turn.id).abort().catch(() => undefined);
}
},
retry: async (sessionId, requestId) => {
await fsd.flow(await flowOfSession(sessionId)).request(requestId).retry();
},
Comment thread
jhoffner marked this conversation as resolved.
Resolved
watchThread: (sessionId, onChange) => {
// Items come from the session feed. The running turn is still read: the feed's runs are
// child sessions, not this session's own turns.
let items: Item[] | undefined;
let loadEarlier: (() => Promise<void>) | undefined;
let connection: ConnectionState | undefined;
let turnOf: { turn: Awaited<ReturnType<typeof runningTurns>>[number] | undefined; threads: boolean } | undefined;
let turnOf: { turn: Awaited<ReturnType<typeof runningTurns>>[number] | undefined; threads: boolean; retryable: string[] } | undefined;
let last: string | undefined;
const tell = () => {
if (items === undefined || turnOf === undefined) return;
const { turn, threads } = turnOf;
const { turn, threads, retryable } = turnOf;
const view: ThreadView = {
entries: entriesOf(items, threads),
entries: entriesOf(items, threads, new Set(retryable)),
running: turn !== undefined,
...(connection === undefined ? {} : { connection }),
...(turn?.startedAtMs === undefined ? {} : { turnStartedAt: turn.startedAtMs }),
Expand Down Expand Up @@ -1006,8 +1055,12 @@ export function createWiredLab(fsd: Client): LabAdapter {
[topic.session(sessionId)],
(notice) => notice.kind === "request",
async () => {
const [turns, threads] = await Promise.all([runningTurns(sessionId), isThreads(sessionId)]);
return { turn: turns[0], threads };
// One read of the latest requests, newest updated first, answers both: the running turn
// is among them, and so is the turn a failed line could retry.
const [recent, threads] = await Promise.all([fsd.sessions.requests(sessionId, { limit: 50 }), isThreads(sessionId)]);
// The turns the engine would retry: a record with no source predates it, and came in over http.
const retryable = recent.filter((request) => RETRYABLE_SOURCES.has(request.source ?? "http")).map((request) => request.id);
return { turn: turnsRunningIn(recent)[0], threads, retryable };
},
(next) => {
turnOf = next;
Expand Down
17 changes: 14 additions & 3 deletions labs/claude-code-style/src/components/Entry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { TASK_STATUS } from "../lib/task-status";
import type { ToolRun } from "../lib/tool-steps";
import { cn } from "../lib/utils";
import { MessageResponse } from "./flow-state/message";
import { RequestRecovery } from "./flow-state/request-recovery";
import { composeToolCallsLabel, toolRunOpen, type ToolStepState } from "./flow-state/tool-grouping";

/**
Expand All @@ -28,11 +29,14 @@ function AgentMarkdown({ text, className }: { text: string; className?: string }
* session's text is Markdown; a run of tool calls is one line in plain words
* that opens to a line per call (`ToolRunLine`); a background result is one collapsed line at the point the main
* session took it, which opens to the task's reply; a thread in threads mode is
* a card (`ThreadCard`, which the main thread draws). `mark` is the feed's
* a card (`ThreadCard`, which the main thread draws). A failed turn is the
* registry's `request-recovery` line, with its reason; `onRetry` draws its
* Retry, so pass it only for the newest turn while nothing runs. A reply its
* turn never finished is marked incomplete. `mark` is the feed's
* mark for your line (`useJumpToLatest`'s `mine`), so a line you send rises to
* near the top of the feed.
*/
export function Entry({ entry, mark }: { entry: ThreadEntry; mark?: SentLineMark }) {
export function Entry({ entry, mark, onRetry }: { entry: ThreadEntry; mark?: SentLineMark; onRetry?: () => Promise<void> }) {
switch (entry.kind) {
case "user":
return (
Expand All @@ -46,8 +50,9 @@ export function Entry({ entry, mark }: { entry: ThreadEntry; mark?: SentLineMark
);
case "assistant":
return (
<div data-entry="assistant">
<div data-entry="assistant" data-incomplete={entry.incomplete ? "true" : undefined}>
<AgentMarkdown text={entry.text} />
{entry.incomplete ? <span className="mt-1 block text-xs text-muted-foreground">Incomplete</span> : null}
</div>
);
case "tool":
Expand All @@ -67,6 +72,12 @@ export function Entry({ entry, mark }: { entry: ThreadEntry; mark?: SentLineMark
Interrupted. Background tasks keep running.
</div>
);
case "failed":
return (
<div data-entry="failed">
<RequestRecovery who="The main session" reason={entry.reason} code={entry.code} details={entry.details} onRetry={onRetry} />
</div>
);
}
}

Expand Down
10 changes: 8 additions & 2 deletions labs/claude-code-style/src/components/Thread.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,10 @@ export function Thread({
const now = useNow(running && !stale);
const count = view?.entries.length ?? 0;
const feed = useJumpToLatest({ resetKey: session.id });
// On the document, so the keys work wherever focus is; a sheet's Esc arrives already spent.
const retryOf = (requestId: string) => () => adapter.retry(session.id, requestId);
// A starter line picked from the empty thread: the composer takes it as its text, and nothing is sent.
const [seed, setSeed] = useState<{ text: string; at: number }>();
// On the document, so the keys work wherever focus is; a sheet's Esc arrives already spent.
const keys = useInterruptKeys({
enabled: running && session.projectId !== null,
onInterrupt: () => void adapter.interrupt(session.id),
Expand Down Expand Up @@ -111,7 +112,12 @@ export function Thread({
) : (
// The request an entry came in on, so a check can tell which turn it landed in.
<div key={entry.id} className="contents" data-request-id={entry.requestId}>
<Entry entry={entry} mark={entry.kind === "user" ? feed.mine(entry.id) : undefined} />
<Entry
entry={entry}
mark={entry.kind === "user" ? feed.mine(entry.id) : undefined}
// Retry only the newest turn, and not while one runs: the engine retries a failed request as a new one.
onRetry={entry.kind === "failed" && entry.retryable && !running && entry.requestId !== undefined ? retryOf(entry.requestId) : undefined}
/>
</div>
),
)}
Expand Down
Loading
Loading