Skip to content

Commit 071594c

Browse files
donjor-agent[bot]rsi-pr-agent
authored andcommitted
feat(web): fork a thread from the thread menu (#1330)
* feat(contracts): thread.fork RPC contract and refusal errors Wire contract for forking a thread from the thread menu, same provider (Claude and Codex only): payload, child thread result, and the tagged refusal errors the server handler and web client share. Fork-Domain: thread-fork Fork-Tier: core * feat(server): same-provider thread fork handler with Claude and Codex cursors thread.fork guards the source (quiescent, no pending requests, forkable provider, usable cursor, not deleted/archived), then creates the child through the import pipeline's own commands: binding insert-ignore, thread.create with the source model/modes/branch, thread.history.import with fresh import: ids, and thread.unsettle (the import settles). Claude forks eagerly through a scoped history worker mirroring runScopedHistoryCommand, seeding the child cursor from the clone's human-prompt UUIDs. Codex installs {threadId, forkFrom: {lastTurnId}} from the source's latest completed turn; the runtime sends thread/fork at the child's first start and fails closed with no thread/start fallback. Fork-Domain: thread-fork Fork-Tier: core * feat(web): Fork thread menu action on the sidebar and header menus Both menu surfaces share one dispatch: it fires thread.fork, disables the item while a fork is in flight, toasts readable refusals, and navigates to the child thread on success. The item is built only for Claude and Codex rows; the provider comes from the live session's instance or the model selection. The fallback context menu learns a git-fork glyph. Fork-Domain: thread-fork Fork-Tier: core * chore(fork): register the thread-fork domain Fork-Domain: fork-meta Fork-Tier: qol * fix(contracts): collapse thread-fork refusals into one coded ThreadForkError Eight single-reason classes carried no extra data and forced a widening union on the wire; the client only ever read the message. One TaggedError with a coded reason literal, optional provider/childThreadId/detail, and a reason-derived message keeps the wire contract small and every refusal still diagnosable; the message now appends the server detail so refusal toasts can copy the concrete cause. Fork-Domain: thread-fork Fork-Tier: core * fix(server): tighten thread-fork quiescence and routing guards - refuse when the child's copied modelSelection routes to a different instance than the session binding (instance-mismatch) - re-read the source after the native fork and refuse source-race when it gained a turn, is running, or picked up a request — before any child command dispatches - mirror the decider's openRequests incl. stale-request cleanup so a failed approval response does not wedge the fork forever - fork-of-fork: a fresh lazy Codex fork reuses the cutoff its own cursor already carries instead of demanding a completed turn - dedupe the forked title suffix instead of stacking ' (fork) (fork)' - table-driven guard tests now run through it.effect.each (plain it.each never executed the Effects) Fork-Domain: thread-fork Fork-Tier: core * refactor(server): send lazy Codex forks over the client's raw request channel The injected forkRequest duplicated the raw channel with a wider method type just to smuggle thread/fork past resume-only typing. The underlying client already passes methods through; the fork now rides raw.request like resume, the open-input field and injected-request type are gone, and a missing cutoff fails closed inside the fork helper. Fork-Domain: thread-fork Fork-Tier: core * fix(web): gate the Fork item on thread busyness and flatten the fork dispatch - extend the marked fork-state hook lines to pass the thread shell and compute busy from the same quiescence signals the server guards on (running/queued turn, pending approvals/user input); the item renders disabled instead of hidden so the affordance stays discoverable, with the server guard still authoritative - restore the upstream threadActionMenu test verbatim and move the fork cases into the fork sibling built on a full menu state - drop the ForkOutcome/settlePromise indirection: try/catch/finally with the in-flight flag cleared in finally, interruption still silent, and a navigation failure after a successful fork no longer toasts Fork-Domain: thread-fork Fork-Tier: core * fix(web): land the fork on the child, not on a stray draft The thread.fork reply races the child's shell projection: ThreadRouteView reads bootstrap-done + no shell as a missing thread and bounces the route to the index, so the fork landed on a fresh draft and the next send created an unrelated thread. The dispatch now waits — bounded, reusing the threadShellAtom subscription — for the child shell to reach the client store before navigating, navigates anyway on timeout, and keeps the in-flight flag held until navigation settles. Squashes: - cc34f7e feat(web): fork a thread from the thread menu (#1330) (#1330) - 3f11a28 fixup! feat(web): fork a thread from the thread menu (#1330) (#1330) - b93b28a feat(web): fork a thread from the thread menu (#1330) (#1330) - 221a415 test(thread-fork): drop the V1 lazy Codex fork runtime cases - e173b77 fix(web): Fork thread dispatches V2 thread.fork from the latest stable run Fork-Domain: thread-fork Fork-Tier: core Fork-Upstreamable: no
1 parent b5561df commit 071594c

12 files changed

Lines changed: 721 additions & 73 deletions

‎apps/web/src/components/Sidebar.tsx‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,13 @@ import {
169169
threadActionRequiresOperate,
170170
} from "./threadActionMenu.logic";
171171
import { useAttemptResetThreadOrder } from "../hooks/useThreadActions.fork"; // fork-hook: thread-ordering/reset-order-action-import
172+
import {
173+
forkInFlight,
174+
forkThreadMenuStateFork,
175+
forkThreadStateTailFork, // fork-hook: thread-fork/sidebar-state-import
176+
readForkProviderFork,
177+
useThreadForkDispatchFork,
178+
} from "../hooks/useThreadActionMenu.fork"; // fork-hook: thread-fork/sidebar-import
172179
import {
173180
applySidebarThreadDrop,
174181
filterSidebarV2VisibleThreads,
@@ -1627,6 +1634,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
16271634
})();
16281635
};
16291636
const attemptResetOrder = useAttemptResetThreadOrder(reorderActiveThreadOrClear); // fork-hook: thread-ordering/reset-order-action
1637+
const forkThreadDispatch = useThreadForkDispatchFork(); // fork-hook: thread-fork/sidebar-dispatch-hook
16301638
const attemptUnsnooze = (threadRef: ScopedThreadRef) => {
16311639
void (async () => {
16321640
const result = await unsnoozeThread(threadRef);
@@ -2666,8 +2674,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
26662674
isRegeneratingTitle,
26672675
isRunning: !threadRuntimeCanArchive(thread.runtime),
26682676
hasManualOrder: thread.activeOrderKey != null, // fork-hook: thread-ordering/reset-order-state
2669-
canShareWithGuest: appAtomRegistry.get(
2670-
canShareWithGuestAtom(threadRef.environmentId),
2677+
canShareWithGuest: appAtomRegistry.get(canShareWithGuestAtom(threadRef.environmentId)), // fork-hook: thread-ordering/share-with-guest-menu-state
2678+
fork: forkThreadMenuStateFork(
2679+
readForkProviderFork(threadRef, thread),
2680+
forkInFlight(threadKey),
2681+
...forkThreadStateTailFork(thread, new Date().toISOString()), // fork-hook: thread-fork/sidebar-state
26712682
),
26722683
supports: {
26732684
settlement: supportsSettlement,
@@ -2778,6 +2789,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
27782789
}
27792790
return;
27802791
}
2792+
case "fork":
2793+
return forkThreadDispatch(threadRef); // fork-hook: thread-fork/sidebar-dispatch
27812794
case "reset-order":
27822795
return attemptResetOrder(threadRef); // fork-hook: thread-ordering/reset-order-dispatch
27832796
case "rename":
Lines changed: 96 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,104 @@
1+
// Fork-only: the Fork menu item is built once the thread has run on a
2+
// configured provider, disabled while the thread is busy (active run or
3+
// pending request) or while a fork is in flight.
4+
import { ProviderDriverKind, ProviderInstanceId, RunId } from "@t3tools/contracts";
15
import { describe, expect, it } from "vite-plus/test";
26

3-
import { buildThreadActionMenuItems, type ThreadActionMenuState } from "./threadActionMenu.logic";
4-
5-
const baseState: ThreadActionMenuState = {
6-
branch: null,
7-
projectFilter: null,
8-
isPinned: false,
9-
isSettled: false,
10-
autoSettleEnabled: true,
11-
isSnoozed: false,
12-
canSnoozeNow: true,
13-
isRegeneratingTitle: false,
14-
isRunning: false,
15-
hasManualOrder: false,
16-
supports: {
17-
settlement: true,
18-
autoSettleOptOut: true,
19-
snooze: true,
20-
pinning: true,
21-
titleRegeneration: true,
22-
},
23-
snoozePresets: [
24-
{ id: "hour", label: "In 1 hour", whenLabel: "3:00 PM", snoozedUntil: "2026-08-07T15:00:00Z" },
25-
],
7+
import type { ThreadActionMenuState } from "./threadActionMenu.logic.ts";
8+
import {
9+
forkThreadMenuItems,
10+
forkThreadMenuStateFork,
11+
type ForkableThreadProviderState,
12+
type ForkThreadShell,
13+
} from "./threadActionMenu.logic.fork.ts";
14+
15+
const CODEX = ProviderDriverKind.make("codex");
16+
const OPENCODE = ProviderDriverKind.make("opencode");
17+
const NOW = "2026-08-20T00:00:00.000Z";
18+
19+
/** Mirror of the upstream test's base state, with the fork slice filled in. */
20+
const baseFork: ForkableThreadProviderState = {
21+
provider: CODEX,
22+
busy: false,
23+
inFlight: false,
24+
};
25+
26+
const baseState: Pick<ThreadActionMenuState, "fork"> = { fork: baseFork };
27+
28+
const completedRun: NonNullable<ForkThreadShell["latestRun"]> = {
29+
runId: RunId.make("run-1"),
30+
status: "completed",
31+
requestedAt: "2026-08-19T23:00:00.000Z",
32+
startedAt: "2026-08-19T23:00:01.000Z",
33+
completedAt: "2026-08-19T23:05:00.000Z",
34+
assistantMessageId: null,
2635
};
2736

28-
function ids(state: ThreadActionMenuState): string[] {
29-
return buildThreadActionMenuItems(state).map((item) => item.id);
30-
}
31-
32-
describe("buildThreadActionMenuItems reset order (fork)", () => {
33-
it("offers reset order only while the thread carries a manual order key", () => {
34-
expect(ids(baseState)).not.toContain("reset-order");
35-
const item = buildThreadActionMenuItems({ ...baseState, hasManualOrder: true }).find(
36-
(candidate) => candidate.id === "reset-order",
37-
);
38-
expect(item).toMatchObject({ label: "Reset order", icon: "arrow-down-up" });
37+
const runtime = (
38+
status: NonNullable<ForkThreadShell["runtime"]>["status"],
39+
): ForkThreadShell["runtime"] => ({
40+
status,
41+
activeRunId: status === "idle" ? null : RunId.make("run-2"),
42+
providerInstanceId: ProviderInstanceId.make("codex"),
43+
providerName: null,
44+
lastError: null,
45+
updatedAt: NOW,
46+
});
47+
48+
/** The quiescence slice the busy check reads: a quiet thread with one finished run. */
49+
const shell = (overrides: Partial<ForkThreadShell> = {}): ForkThreadShell => ({
50+
latestRun: completedRun,
51+
runtime: runtime("idle"),
52+
hasPendingApprovals: false,
53+
hasPendingUserInput: false,
54+
latestUserMessageAt: null,
55+
...overrides,
56+
});
57+
58+
describe("forkThreadMenuStateFork", () => {
59+
it("builds state for any configured provider once the thread has run", () => {
60+
expect(forkThreadMenuStateFork(CODEX, false, shell(), NOW)).toEqual({
61+
provider: CODEX,
62+
busy: false,
63+
inFlight: false,
64+
});
65+
// V2 forks portably where the provider cannot fork natively.
66+
expect(forkThreadMenuStateFork(OPENCODE, false, shell(), NOW)).not.toBeNull();
67+
expect(forkThreadMenuStateFork(null, false, shell(), NOW)).toBeNull();
68+
expect(forkThreadMenuStateFork(CODEX, false, shell({ latestRun: null }), NOW)).toBeNull();
69+
});
70+
71+
it.each([
72+
{ name: "a running run", shell: shell({ runtime: runtime("running") }) },
73+
{ name: "a starting run", shell: shell({ runtime: runtime("starting") }) },
74+
{ name: "a queued run", shell: shell({ runtime: runtime("queued") }) },
75+
{ name: "a run waiting on the user", shell: shell({ runtime: runtime("waiting") }) },
76+
{ name: "a pending approval", shell: shell({ hasPendingApprovals: true }) },
77+
{ name: "a pending user input", shell: shell({ hasPendingUserInput: true }) },
78+
{
79+
name: "an unadopted user message",
80+
shell: shell({ latestUserMessageAt: "2026-08-19T23:59:30.000Z" }),
81+
},
82+
])("marks the thread busy for $name", ({ shell: busyShell }) => {
83+
expect(forkThreadMenuStateFork(CODEX, false, busyShell, NOW)?.busy).toBe(true);
84+
});
85+
86+
it("passes the in-flight flag through", () => {
87+
expect(forkThreadMenuStateFork(CODEX, true, shell(), NOW)?.inFlight).toBe(true);
88+
});
89+
});
90+
91+
describe("forkThreadMenuItems", () => {
92+
it("renders a disabled Fork item while busy or in flight", () => {
93+
expect(forkThreadMenuItems(baseState)).toEqual([
94+
{ id: "fork", label: "Fork thread", icon: "git-fork", disabled: false },
95+
]);
96+
expect(forkThreadMenuItems({ fork: { ...baseFork, busy: true } })[0]?.disabled).toBe(true);
97+
expect(forkThreadMenuItems({ fork: { ...baseFork, inFlight: true } })[0]?.disabled).toBe(true);
3998
});
4099

41-
it("orders reset before the lifecycle actions", () => {
42-
const items = buildThreadActionMenuItems({ ...baseState, hasManualOrder: true });
43-
const resetIndex = items.findIndex((item) => item.id === "reset-order");
44-
const settleIndex = items.findIndex((item) => item.id === "settle");
45-
expect(resetIndex).toBeGreaterThanOrEqual(0);
46-
expect(resetIndex).toBeLessThan(settleIndex);
100+
it("omits the item entirely without fork state", () => {
101+
expect(forkThreadMenuItems({ fork: null })).toEqual([]);
102+
expect(forkThreadMenuItems({})).toEqual([]);
47103
});
48104
});

‎apps/web/src/components/threadActionMenu.logic.fork.ts‎

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import type { ContextMenuItem } from "@t3tools/contracts";
1+
import type { ContextMenuItem, ProviderDriverKind } from "@t3tools/contracts";
2+
import {
3+
threadRuntimeIsActive,
4+
type EnvironmentThreadShell,
5+
} from "@t3tools/client-runtime/state/shell";
6+
import { hasQueuedTurnStart } from "@t3tools/client-runtime/state/thread-settled";
27

38
import type { ThreadActionMenuId, ThreadActionMenuState } from "./threadActionMenu.logic.ts";
49

@@ -15,3 +20,80 @@ export function resetOrderMenuItems(
1520
? [{ id: "reset-order" as const, label: "Reset order", icon: "arrow-down-up" }]
1621
: [];
1722
}
23+
24+
/**
25+
* Fork: Open in New Window for a thread (RSI-Software/t3code-hyprws#1343).
26+
* Present only where the client can open desktop windows.
27+
*/
28+
export function openInNewWindowMenuItems(
29+
state: Pick<ThreadActionMenuState, "openInNewWindow">,
30+
): ReadonlyArray<ContextMenuItem<ThreadActionMenuId>> {
31+
return state.openInNewWindow === true
32+
? [{ id: "open-in-new-window" as const, label: "Open in New Window", icon: "external-link" }]
33+
: [];
34+
}
35+
36+
export interface ForkableThreadProviderState {
37+
readonly provider: ProviderDriverKind;
38+
/** A running or queued turn or a pending request blocks the fork client-side too. */
39+
readonly busy: boolean;
40+
readonly inFlight: boolean;
41+
}
42+
43+
/** The quiescence slice of the shell the fork busy check reads. */
44+
export type ForkThreadShell = Pick<
45+
EnvironmentThreadShell,
46+
"latestRun" | "runtime" | "hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt"
47+
>;
48+
49+
/**
50+
* V2 `thread.fork` copies from the latest stable run, natively or as a portable context
51+
* handoff, so any configured provider qualifies once the thread has run. Disabled while
52+
* busy (the orchestrator stays authoritative) or while a fork for it is in flight.
53+
*/
54+
export function forkThreadMenuStateFork(
55+
driver: ProviderDriverKind | null | undefined,
56+
inFlight: boolean,
57+
thread: ForkThreadShell,
58+
now: string,
59+
): ForkableThreadProviderState | null {
60+
if (driver === null || driver === undefined || thread.latestRun === null) return null;
61+
const busy =
62+
threadRuntimeIsActive(thread.runtime) ||
63+
thread.hasPendingApprovals ||
64+
thread.hasPendingUserInput ||
65+
hasQueuedTurnStart(
66+
{
67+
latestUserMessageAt: thread.latestUserMessageAt,
68+
latestRun: thread.latestRun,
69+
runtime: thread.runtime,
70+
},
71+
{ now },
72+
);
73+
return { provider: driver, busy, inFlight };
74+
}
75+
76+
/**
77+
* The `thread` + `now` tail arguments for `forkThreadMenuStateFork` call
78+
* sites, as a spreadable tuple so each upstream builder file takes the fork
79+
* state through one marked line.
80+
*/
81+
export const forkThreadStateTailFork = (
82+
thread: ForkThreadShell,
83+
now: string,
84+
): [thread: ForkThreadShell, now: string] => [thread, now];
85+
86+
/** The Fork entry, hidden until the thread has a run to fork from. */
87+
export function forkThreadMenuItems(
88+
state: Pick<ThreadActionMenuState, "fork">,
89+
): ReadonlyArray<ContextMenuItem<ThreadActionMenuId>> {
90+
if (state.fork === undefined || state.fork === null) return [];
91+
return [
92+
{
93+
id: "fork" as const,
94+
label: "Fork thread",
95+
icon: "git-fork",
96+
disabled: state.fork.inFlight || state.fork.busy,
97+
},
98+
];
99+
}

‎apps/web/src/components/threadActionMenu.logic.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import type { ContextMenuItem } from "@t3tools/contracts";
22
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
33

44
import { resetOrderMenuItems } from "./threadActionMenu.logic.fork"; // fork-hook: thread-ordering/reset-order-items-import
5+
import type { ForkableThreadProviderState } from "./threadActionMenu.logic.fork"; // fork-hook: thread-fork/menu-state-type-import
6+
import { forkThreadMenuItems } from "./threadActionMenu.logic.fork"; // fork-hook: thread-fork/menu-items-import
57

68
export type ThreadActionMenuId =
79
| "new-thread-on-branch"
@@ -10,6 +12,7 @@ export type ThreadActionMenuId =
1012
| "pin"
1113
| "unpin"
1214
| "reset-order" // fork-hook: thread-ordering/reset-order-id
15+
| "fork" // fork-hook: thread-fork/menu-id
1316
| "settle"
1417
| "unsettle"
1518
| "auto-settle"
@@ -76,6 +79,7 @@ export interface ThreadActionMenuState {
7679
} | null;
7780
readonly isPinned: boolean;
7881
readonly hasManualOrder?: boolean; // fork-hook: thread-ordering/reset-order-state
82+
readonly fork?: ForkableThreadProviderState | null; // fork-hook: thread-fork/menu-state
7983
readonly isSettled: boolean;
8084
readonly autoSettleEnabled: boolean;
8185
readonly isSnoozed: boolean;
@@ -130,6 +134,7 @@ export function buildThreadActionMenuItems(
130134
]
131135
: []),
132136
...resetOrderMenuItems(state), // fork-hook: thread-ordering/reset-order-items
137+
...forkThreadMenuItems(state), // fork-hook: thread-fork/menu-items
133138
...(state.supports.settlement
134139
? [
135140
state.isSettled

‎apps/web/src/contextMenuFallback.fork.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,12 @@ export const forkIconPaths: Record<
1414
{ tag: "path", attrs: { d: "m3 8 4-4 4 4" } },
1515
{ tag: "path", attrs: { d: "M7 4v16" } },
1616
],
17+
// Lucide `git-fork`: the glyph for Fork thread.
18+
"git-fork": [
19+
{ tag: "circle", attrs: { cx: "12", cy: "18", r: "3" } },
20+
{ tag: "circle", attrs: { cx: "6", cy: "6", r: "3" } },
21+
{ tag: "circle", attrs: { cx: "18", cy: "6", r: "3" } },
22+
{ tag: "path", attrs: { d: "M18 9v2c0 .6-.4 1-1 1H7c-.6 0-1-.4-1-1V9" } },
23+
{ tag: "path", attrs: { d: "M12 12v3" } },
24+
],
1725
};

0 commit comments

Comments
 (0)