Skip to content

Commit 34ef2a8

Browse files
refactor(web): ChatView's thread derivations are tested functions in ChatView.logic
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6b61b05 commit 34ef2a8

3 files changed

Lines changed: 246 additions & 135 deletions

File tree

‎apps/web/src/components/ChatView.logic.test.ts‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import {
55
planComposerTurn,
66
snapshotComposerSend,
77
withMessageContext,
8+
deriveAvailableRevertTurnCounts,
9+
deriveWorkspaceMutationId,
810
} from "./ChatView.logic";
911
import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic";
1012
import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
@@ -1158,3 +1160,82 @@ describe("boundAttachmentIds", () => {
11581160
).toEqual(["upload-1", "local-2"]);
11591161
});
11601162
});
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‎

Lines changed: 149 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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";
111
import * as Option from "effect/Option";
212
import type { SetStateAction } from "react";
313
import { applyClaudePromptEffortPrefix, resolvePromptInjectedEffort } from "@t3tools/shared/model";
414
import { getProviderModelCapabilities } from "../providerModels";
515
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";
720
import {
821
ANTIGRAVITY_DEFAULT_MODEL,
922
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
@@ -92,6 +105,8 @@ import {
92105
type ProviderInstanceEntry,
93106
} from "../providerInstances";
94107

108+
type ThreadProjection = EnvironmentThread["projection"];
109+
95110
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
96111
export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;
97112

@@ -1610,3 +1625,136 @@ export function sendTitleFallbackLabels(snapshot: ComposerSendSnapshot) {
16101625
previewAnnotation ? previewAnnotationContextLabel(previewAnnotation) : undefined,
16111626
];
16121627
}
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+
}

0 commit comments

Comments
 (0)