The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 19:30 UTC
refactor(web): ChatView's thread derivations are tested functions in ChatView.logic (#23071)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 21, 2026 at 13:40 UTC
9952a7aa518275c4c42f7cf57b28409122a22537
3 files changed
+246
-135
apps/web/src/components/ChatView.logic.test.ts
+81
@@ -5,6 +5,8 @@ import {
5
planComposerTurn,
6
snapshotComposerSend,
7
withMessageContext,
8
+ deriveAvailableRevertTurnCounts,
9
+ deriveWorkspaceMutationId,
10
} from "./ChatView.logic";
11
import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic";
12
import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
@@ -1158,3 +1160,82 @@ describe("boundAttachmentIds", () => {
1160
).toEqual(["upload-1", "local-2"]);
1161
});
1162
});
1163
+
1164
+describe("deriveAvailableRevertTurnCounts", () => {
1165
+ const providerThreadId = ProviderThreadId.make("provider-thread");
1166
+ const otherProviderThreadId = ProviderThreadId.make("other-provider-thread");
1167
+
1168
+ function projection(input: { readonly providerSessionId: ProviderSessionId | null }) {
1169
+ const base = makeThreadProjectionFixture();
1170
+ const run = (ordinal: number) => ({
1171
+ id: RunId.make(`run-${ordinal}`),
1172
+ ordinal,
1173
+ activeAttemptId: `attempt-${ordinal}`,
1174
+ });
1175
+ const turn = (ordinal: number, attempt: number, threadId: ProviderThreadId) => ({
1176
+ id: `turn-${attempt}-${ordinal}`,
1177
+ runAttemptId: `attempt-${attempt}`,
1178
+ ordinal,
1179
+ providerThreadId: threadId,
1180
+ });
1181
+ return {
1182
+ ...base,
1183
+ thread: { ...base.thread, activeProviderThreadId: providerThreadId },
1184
+ providerThreads: [
1185
+ {
1186
+ id: providerThreadId,
1187
+ providerInstanceId: base.thread.modelSelection.instanceId,
1188
+ providerSessionId: input.providerSessionId,
1189
+ },
1190
+ ],
1191
+ runs: [run(1), run(2), run(3)],
1192
+ attempts: [1, 2, 3].map((ordinal) => ({ id: `attempt-${ordinal}`, providerTurnId: null })),
1193
+ // Run 2's latest turn moved to another provider thread, so its checkpoint cannot restore
1194
+ // this conversation.
1195
+ providerTurns: [
1196
+ turn(1, 1, providerThreadId),
1197
+ turn(1, 2, providerThreadId),
1198
+ turn(2, 2, otherProviderThreadId),
1199
+ turn(1, 3, providerThreadId),
1200
+ ],
1201
+ } as unknown as ReturnType<typeof makeThreadProjectionFixture>;
1202
+ }
1203
+
1204
+ it("offers the thread start and runs whose latest turn is on the active provider thread", () => {
1205
+ const available = deriveAvailableRevertTurnCounts(
1206
+ projection({ providerSessionId: ProviderSessionId.make("session") }),
1207
+ );
1208
+ expect([...available].toSorted()).toEqual([0, 1, 3]);
1209
+ });
1210
+
1211
+ it("offers nothing without a provider session to rewind", () => {
1212
+ expect(deriveAvailableRevertTurnCounts(projection({ providerSessionId: null })).size).toBe(0);
1213
+ expect(deriveAvailableRevertTurnCounts(null).size).toBe(0);
1214
+ });
1215
+});
1216
+
1217
+describe("deriveWorkspaceMutationId", () => {
1218
+ const item = (id: string, type: string, status: string) =>
1219
+ ({
1220
+ item: { id: TurnItemId.make(id), type, status },
1221
+ }) as unknown as OrchestrationV2ProjectedTurnItem;
1222
+
1223
+ it("keys on the latest finished command or file change and the latest checkpoint", () => {
1224
+ expect(
1225
+ deriveWorkspaceMutationId(
1226
+ [
1227
+ item("edit", "file_change", "completed"),
1228
+ item("reply", "assistant_message", "completed"),
1229
+ item("command", "command_execution", "running"),
1230
+ ],
1231
+ "2026-01-01T00:00:00.000Z",
1232
+ ),
1233
+ ).toBe(JSON.stringify(["edit", "2026-01-01T00:00:00.000Z"]));
1234
+ });
1235
+
1236
+ it("is null before anything could have touched the workspace", () => {
1237
+ expect(deriveWorkspaceMutationId([item("reply", "assistant_message", "completed")], null)).toBe(
1238
+ null,
1239
+ );
1240
+ });
1241
+});
apps/web/src/components/ChatView.logic.ts
+149
-1
@@ -1,9 +1,22 @@
1
+import { type OrchestrationV2ProviderTurn, type RunAttemptId } from "@t3tools/contracts";
2
+import {
3
+ deriveLatestThreadRun,
4
+ deriveThreadRuntime,
5
+} from "@t3tools/client-runtime/state/thread-execution";
6
+import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
7
+import {
8
+ latestUnheldRun,
9
+ usageLimitRunPresentedAsLatest,
10
+} from "@t3tools/shared/orchestrationV2ThreadError";
11
import * as Option from "effect/Option";
12
import type { SetStateAction } from "react";
13
import { applyClaudePromptEffortPrefix, resolvePromptInjectedEffort } from "@t3tools/shared/model";
14
import { getProviderModelCapabilities } from "../providerModels";
15
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
6
-import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
16
+import type {
17
+ EnvironmentThread,
18
+ EnvironmentThreadShell,
19
+} from "@t3tools/client-runtime/state/shell";
20
import {
21
ANTIGRAVITY_DEFAULT_MODEL,
22
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
@@ -92,6 +105,8 @@ import {
105
type ProviderInstanceEntry,
106
} from "../providerInstances";
107
108
+type ThreadProjection = EnvironmentThread["projection"];
109
+
110
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
111
export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
112
@@ -1610,3 +1625,136 @@ export function sendTitleFallbackLabels(snapshot: ComposerSendSnapshot) {
1625
previewAnnotation ? previewAnnotationContextLabel(previewAnnotation) : undefined,
1626
];
1627
}
1628
+
1629
+/** A thread shell built from its loaded detail, for direct links that hydrate the detail first. */
1630
+export function presentThreadShellFromProjection(
1631
+ environmentId: EnvironmentId,
1632
+ threadId: ThreadId,
1633
+ projection: ThreadProjection,
1634
+) {
1635
+ const latestRun = deriveLatestThreadRun(projection);
1636
+ const runtime = deriveThreadRuntime(projection);
1637
+ const pendingRuntimeRequest =
1638
+ projection.runtimeRequests.findLast((request) => request.status === "pending") ?? null;
1639
+ // Direct links can hydrate detail before the thread enters the shell index.
1640
+ return {
1641
+ ...presentThreadShell(environmentId, {
1642
+ ...projection.thread,
1643
+ latestRunId: latestRun?.runId ?? null,
1644
+ activeRunId: runtime?.activeRunId ?? null,
1645
+ status: runtime?.status ?? "idle",
1646
+ pendingRuntimeRequest,
1647
+ latestVisibleMessage: null,
1648
+ latestUserMessageAt:
1649
+ projection.messages.findLast((message) => message.role === "user")?.updatedAt ?? null,
1650
+ hasActionableProposedPlan: projection.plans.some(
1651
+ (plan) => plan.kind === "proposed_plan" && plan.status === "active",
1652
+ ),
1653
+ providerInstanceHistory: [
1654
+ ...new Set(
1655
+ projection.providerThreads
1656
+ .filter((thread) => thread.appThreadId === threadId && thread.ownerNodeId === null)
1657
+ .map((thread) => thread.providerInstanceId),
1658
+ ),
1659
+ ],
1660
+ goal:
1661
+ projection.providerThreads.find(
1662
+ (thread) => thread.id === projection.thread.activeProviderThreadId,
1663
+ )?.goal ?? null,
1664
+ itemCount: projection.turnItems.length,
1665
+ visibleItemCount: projection.visibleTurnItems.length,
1666
+ updatedAt: projection.updatedAt,
1667
+ }),
1668
+ latestRun,
1669
+ runtime,
1670
+ };
1671
+}
1672
+
1673
+/** Background work the provider still runs after the latest run ended. */
1674
+export function deriveThreadPendingBackgroundTasks(projection: ThreadProjection | null) {
1675
+ if (projection === null) return [];
1676
+ const sessionError =
1677
+ projection.providerSessions.findLast(
1678
+ (session) => session.providerInstanceId === projection.thread.providerInstanceId,
1679
+ )?.lastError ?? null;
1680
+ const latestRun =
1681
+ usageLimitRunPresentedAsLatest(projection.runs, projection.turnItems, sessionError) ??
1682
+ latestUnheldRun(projection.runs);
1683
+ return [
1684
+ ...derivePendingBackgroundWork({
1685
+ latestRun,
1686
+ providerThreads: projection.providerThreads,
1687
+ turnItems: projection.turnItems,
1688
+ activeProviderThreadId: projection.thread.activeProviderThreadId,
1689
+ runs: projection.runs,
1690
+ pullRequests: projection.thread.pullRequests,
1691
+ }),
1692
+ ];
1693
+}
1694
+
1695
+/**
1696
+ * Run ordinals the conversation can be reverted to: those whose provider turn belongs to the
1697
+ * active provider thread, plus 0 for the thread start. Empty without a live provider session
1698
+ * on the thread's selected instance.
1699
+ */
1700
+export function deriveAvailableRevertTurnCounts(projection: ThreadProjection | null) {
1701
+ const available = new Set<number>();
1702
+ const providerThread = projection?.providerThreads.find(
1703
+ (candidate) => candidate.id === projection.thread.activeProviderThreadId,
1704
+ );
1705
+ if (
1706
+ !providerThread?.providerSessionId ||
1707
+ providerThread.providerInstanceId !== projection?.thread.modelSelection.instanceId
1708
+ )
1709
+ return available;
1710
+ available.add(0);
1711
+ const attemptsById = new Map(projection.attempts.map((attempt) => [attempt.id, attempt]));
1712
+ const providerTurnsById = new Map<
1713
+ OrchestrationV2ProviderTurn["id"],
1714
+ OrchestrationV2ProviderTurn
1715
+ >();
1716
+ const latestTurnByAttempt = new Map<RunAttemptId, OrchestrationV2ProviderTurn>();
1717
+ for (const turn of projection.providerTurns) {
1718
+ providerTurnsById.set(turn.id, turn);
1719
+ if (turn.runAttemptId === null) continue;
1720
+ const latest = latestTurnByAttempt.get(turn.runAttemptId);
1721
+ if (latest === undefined || turn.ordinal > latest.ordinal) {
1722
+ latestTurnByAttempt.set(turn.runAttemptId, turn);
1723
+ }
1724
+ }
1725
+ for (const run of projection.runs) {
1726
+ if (run.activeAttemptId === null) continue;
1727
+ const attempt = attemptsById.get(run.activeAttemptId);
1728
+ const providerTurn =
1729
+ latestTurnByAttempt.get(run.activeAttemptId) ??
1730
+ (attempt?.providerTurnId == null ? undefined : providerTurnsById.get(attempt.providerTurnId));
1731
+ // A ready file checkpoint alone cannot restore the provider conversation.
1732
+ if (providerTurn?.providerThreadId === providerThread.id) available.add(run.ordinal);
1733
+ }
1734
+ return available;
1735
+}
1736
+
1737
+/**
1738
+ * Changes when the agent may have changed the workspace, so file views refresh. File tools are
1739
+ * explicit; completed commands are included because a shell command can mutate the workspace
1740
+ * without reporting the paths it touched.
1741
+ */
1742
+export function deriveWorkspaceMutationId(
1743
+ visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
1744
+ latestCheckpointCompletedAt: string | null,
1745
+) {
1746
+ let itemId: string | null = null;
1747
+ for (let index = visibleTurnItems.length - 1; index >= 0; index -= 1) {
1748
+ const item = visibleTurnItems[index]?.item;
1749
+ if (!item) continue;
1750
+ if (item.type !== "command_execution" && item.type !== "file_change") continue;
1751
+ if (item.status === "pending" || item.status === "running" || item.status === "waiting") {
1752
+ continue;
1753
+ }
1754
+ itemId = item.id;
1755
+ break;
1756
+ }
1757
+ return itemId === null && latestCheckpointCompletedAt === null
1758
+ ? null
1759
+ : JSON.stringify([itemId, latestCheckpointCompletedAt]);
1760
+}
apps/web/src/components/ChatView.tsx
+16
-134
@@ -1,3 +1,9 @@
1
+import {
2
+ deriveAvailableRevertTurnCounts,
3
+ deriveThreadPendingBackgroundTasks,
4
+ deriveWorkspaceMutationId,
5
+ presentThreadShellFromProjection,
6
+} from "./ChatView.logic";
7
import { usePullRequestDraftThread } from "./chat/usePullRequestDraftThread";
8
import { useComposerSelection } from "./chat/useComposerSelection";
9
import { useProjectCloneBanner } from "./chat/useProjectCloneBanner";
@@ -55,21 +61,18 @@ import {
61
type EnvironmentId,
62
type MessageId,
63
type ModelSelection,
58
- type OrchestrationV2ProviderTurn,
64
type PreviewAnnotationPayload,
65
ProviderInstanceId,
66
type ServerProvider,
67
type ScopedThreadRef,
68
type ThreadId,
69
type RunId,
65
- type RunAttemptId,
70
ProviderInteractionMode,
71
resolveIdleCompaction,
72
RuntimeMode,
73
} from "@t3tools/contracts";
74
import { readPastedComposerContext } from "./composerInlineTokenPaste";
75
import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
72
-import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
76
import { useThreadActions } from "../hooks/useThreadActions";
77
import {
78
deriveProviderSubagentStatus,
@@ -100,11 +103,6 @@ import {
103
} from "@t3tools/client-runtime/environment";
104
import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model";
105
import { projectScriptCwd, resolveProjectScripts } from "@t3tools/shared/projectScripts";
103
-import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
104
-import {
105
- latestUnheldRun,
106
- usageLimitRunPresentedAsLatest,
107
-} from "@t3tools/shared/orchestrationV2ThreadError";
106
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
107
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
108
import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
@@ -477,48 +475,10 @@ export default function ChatView(props: ChatViewProps) {
475
});
476
const serverThreadProjection = useThreadProjection(routeThreadDetailRef);
477
const serverProjection = serverThreadProjection?.projection ?? null;
480
- const serverThread = (() => {
481
- if (serverThreadShell !== null || serverProjection === null) {
482
- return serverThreadShell;
483
- }
484
- const latestRun = deriveLatestThreadRun(serverProjection);
485
- const runtime = deriveThreadRuntime(serverProjection);
486
- const pendingRuntimeRequest =
487
- serverProjection.runtimeRequests.findLast((request) => request.status === "pending") ?? null;
488
- // Direct links can hydrate detail before the thread enters the shell index.
489
- return {
490
- ...presentThreadShell(environmentId, {
491
- ...serverProjection.thread,
492
- latestRunId: latestRun?.runId ?? null,
493
- activeRunId: runtime?.activeRunId ?? null,
494
- status: runtime?.status ?? "idle",
495
- pendingRuntimeRequest,
496
- latestVisibleMessage: null,
497
- latestUserMessageAt:
498
- serverProjection.messages.findLast((message) => message.role === "user")?.updatedAt ??
499
- null,
500
- hasActionableProposedPlan: serverProjection.plans.some(
501
- (plan) => plan.kind === "proposed_plan" && plan.status === "active",
502
- ),
503
- providerInstanceHistory: [
504
- ...new Set(
505
- serverProjection.providerThreads
506
- .filter((thread) => thread.appThreadId === threadId && thread.ownerNodeId === null)
507
- .map((thread) => thread.providerInstanceId),
508
- ),
509
- ],
510
- goal:
511
- serverProjection.providerThreads.find(
512
- (thread) => thread.id === serverProjection.thread.activeProviderThreadId,
513
- )?.goal ?? null,
514
- itemCount: serverProjection.turnItems.length,
515
- visibleItemCount: serverProjection.visibleTurnItems.length,
516
- updatedAt: serverProjection.updatedAt,
517
- }),
518
- latestRun,
519
- runtime,
520
- };
521
- })();
478
+ const serverThread =
479
+ serverThreadShell !== null || serverProjection === null
480
+ ? serverThreadShell
481
+ : presentThreadShellFromProjection(environmentId, threadId, serverProjection);
482
const promptRef = useRef("");
483
const localComposerRef = useRef<ChatComposerHandle | null>(null);
484
const composerRef = useComposerHandleContext() ?? localComposerRef;
@@ -1452,31 +1412,7 @@ export default function ChatView(props: ChatViewProps) {
1412
activeThreadLiveTokenUsage,
1413
activeProviderThread,
1414
);
1455
- const pendingBackgroundTasks = (() => {
1456
- if (serverProjection === null || serverProjection === undefined) {
1457
- return [];
1458
- }
1459
- const sessionError =
1460
- serverProjection.providerSessions.findLast(
1461
- (session) => session.providerInstanceId === serverProjection.thread.providerInstanceId,
1462
- )?.lastError ?? null;
1463
- const latestRun =
1464
- usageLimitRunPresentedAsLatest(
1465
- serverProjection.runs,
1466
- serverProjection.turnItems,
1467
- sessionError,
1468
- ) ?? latestUnheldRun(serverProjection.runs);
1469
- return [
1470
- ...derivePendingBackgroundWork({
1471
- latestRun,
1472
- providerThreads: serverProjection.providerThreads,
1473
- turnItems: serverProjection.turnItems,
1474
- activeProviderThreadId: serverProjection.thread.activeProviderThreadId,
1475
- runs: serverProjection.runs,
1476
- pullRequests: serverProjection.thread.pullRequests,
1477
- }),
1478
- ];
1479
- })();
1415
+ const pendingBackgroundTasks = deriveThreadPendingBackgroundTasks(serverProjection);
1416
const activeWorkStartedAt =
1417
deriveActiveWorkStartedAt(activeActivityRun, activeRuntime, localDispatchStartedAt) ??
1418
runlessWorkStartedAt;
@@ -1614,70 +1550,16 @@ export default function ChatView(props: ChatViewProps) {
1550
panelAnimationDurationMs,
1551
);
1552
const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadDetailRef);
1617
- const availableRevertTurnCounts = (() => {
1618
- const available = new Set<number>();
1619
- const providerThread = serverProjection?.providerThreads.find(
1620
- (candidate) => candidate.id === serverProjection.thread.activeProviderThreadId,
1621
- );
1622
- if (
1623
- !providerThread?.providerSessionId ||
1624
- providerThread.providerInstanceId !== serverProjection?.thread.modelSelection.instanceId
1625
- )
1626
- return available;
1627
- available.add(0);
1628
- const attemptsById = new Map(serverProjection.attempts.map((attempt) => [attempt.id, attempt]));
1629
- const providerTurnsById = new Map<
1630
- OrchestrationV2ProviderTurn["id"],
1631
- OrchestrationV2ProviderTurn
1632
- >();
1633
- const latestTurnByAttempt = new Map<RunAttemptId, OrchestrationV2ProviderTurn>();
1634
- for (const turn of serverProjection.providerTurns) {
1635
- providerTurnsById.set(turn.id, turn);
1636
- if (turn.runAttemptId === null) continue;
1637
- const latest = latestTurnByAttempt.get(turn.runAttemptId);
1638
- if (latest === undefined || turn.ordinal > latest.ordinal) {
1639
- latestTurnByAttempt.set(turn.runAttemptId, turn);
1640
- }
1641
- }
1642
- for (const run of serverProjection.runs) {
1643
- if (run.activeAttemptId === null) continue;
1644
- const attempt = attemptsById.get(run.activeAttemptId);
1645
- const providerTurn =
1646
- latestTurnByAttempt.get(run.activeAttemptId) ??
1647
- (attempt?.providerTurnId == null
1648
- ? undefined
1649
- : providerTurnsById.get(attempt.providerTurnId));
1650
- // A ready file checkpoint alone cannot restore the provider conversation.
1651
- if (providerTurn?.providerThreadId === providerThread.id) available.add(run.ordinal);
1652
- }
1653
- return available;
1654
- })();
1553
+ const availableRevertTurnCounts = deriveAvailableRevertTurnCounts(serverProjection);
1554
// A paged history window cannot identify the first loaded run as the thread start.
1555
const threadStartCheckpointReady =
1556
!serverThreadHistory.hasMoreHistory &&
1557
findRevertCheckpoint(serverProjection?.checkpoints ?? [], 0) !== undefined;
1558
1660
- /**
1661
- * File tools are explicit; completed commands are included because a shell
1662
- * command can mutate the workspace without reporting the paths it touched.
1663
- */
1664
- const workspaceMutationId = (() => {
1665
- let itemId: string | null = null;
1666
- for (let index = serverVisibleTurnItems.length - 1; index >= 0; index -= 1) {
1667
- const item = serverVisibleTurnItems[index]?.item;
1668
- if (!item) continue;
1669
- if (item.type !== "command_execution" && item.type !== "file_change") continue;
1670
- if (item.status === "pending" || item.status === "running" || item.status === "waiting") {
1671
- continue;
1672
- }
1673
- itemId = item.id;
1674
- break;
1675
- }
1676
- const latestCheckpointCompletedAt = turnDiffSummaries.at(-1)?.completedAt ?? null;
1677
- return itemId === null && latestCheckpointCompletedAt === null
1678
- ? null
1679
- : JSON.stringify([itemId, latestCheckpointCompletedAt]);
1680
- })();
1559
+ const workspaceMutationId = deriveWorkspaceMutationId(
1560
+ serverVisibleTurnItems,
1561
+ turnDiffSummaries.at(-1)?.completedAt ?? null,
1562
+ );
1563
1564
const gitCwd = activeProject
1565
? projectScriptCwd({