@devries-cameron20 / t3code Mirror · read-only / commits / e0f69e9ea4
Fork 0

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, 05:45 UTC

fix(web,mobile): chat images reload when the agent rewrites the file (#29741)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 2, 2026 at 18:03 UTC e0f69e9ea4cb550cb8a395ccc8096d387783b577
15 files changed +554 -381
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+51 -48
@@ -197,6 +197,7 @@ import {
197 } from "./ThreadComposer";
198 import { ComposerPopoverHost } from "./ComposerPopoverHost";
199 import { ThreadFeed, type ThreadFeedHandle, type ThreadFeedHistoryControls } from "./ThreadFeed";
200 +import { WorkspaceMutationIdProvider } from "./WorkspaceMutationIdProvider";
201 import { useThreadTurnSubagents } from "./ThreadAgentsSheet";
202 import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";
203 import { useThreadQueuedCount } from "./ThreadQueueControl";
@@ -1437,54 +1438,56 @@ function ThreadDetailBody(
1438 />
1439 )}
1440 >
1440 - <ThreadFeed
1441 - environmentId={props.environmentId}
1442 - threadId={props.selectedThread.id}
1443 - detailRef={props.selectedThreadDetailRef}
1444 - workspaceRoot={props.threadCwd}
1445 - feed={props.selectedThreadFeed}
1446 - pendingHandoff={props.pendingHandoff}
1447 - worktreeSetup={props.worktreeSetup}
1448 - setupWorkingStartedAt={props.setupWorkingStartedAt}
1449 - queuedMessages={props.queuedMessages}
1450 - dispatchingMessageId={props.dispatchingMessageId}
1451 - // A native subagent has no composer to edit a pending message in;
1452 - // Cancel on the edit banner would discard it.
1453 - onEditPendingMessage={
1454 - isProviderSubagent || pendingMessageEditBlocked ? null : handleEditPendingMessage
1455 - }
1456 - contentPresentation={props.contentPresentation}
1457 - threadTitle={props.selectedThread.title}
1458 - latestRun={props.activityRun}
1459 - activeWorkStartedAt={props.activeWorkStartedAt}
1460 - runlessWorkActive={props.runlessWorkActive ?? false}
1461 - listRef={listRef}
1462 - freeze={freeze}
1463 - anchorMessageId={anchorMessageId}
1464 - jumpToMessageId={jumpMessageLoaded ? jumpMessageId : null}
1465 - onJumpedToMessage={() => finishThreadMessageJump(selectedThreadKey)}
1466 - ref={feedRef}
1467 - contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
1468 - keyboardOffset={composerKeyboardOffset}
1469 - sendingWithKeyboard={sendingWithKeyboard}
1470 - fitShortFeedToViewport={questionInFlow && !isKeyboardVisible}
1471 - contentTopInset={0}
1472 - contentBottomInset={
1473 - questionInFlow
1474 - ? 0
1475 - : estimatedOverlayHeight +
1476 - (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
1477 - }
1478 - contentMaxWidth={contentMaxWidth}
1479 - historyControls={props.historyControls}
1480 - contentSideInsets={nativeMetrics?.safeArea}
1481 - layoutVariant={layoutVariant}
1482 - usesAutomaticContentInsets={props.usesAutomaticContentInsets}
1483 - onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
1484 - onEndFollowEnabledChange={handleEndFollowEnabledChange}
1485 - skills={selectedProviderSkills}
1486 - onUseArtifactTemplate={handleUseArtifactTemplate}
1487 - />
1441 + <WorkspaceMutationIdProvider threadRef={props.selectedThreadDetailRef}>
1442 + <ThreadFeed
1443 + environmentId={props.environmentId}
1444 + threadId={props.selectedThread.id}
1445 + detailRef={props.selectedThreadDetailRef}
1446 + workspaceRoot={props.threadCwd}
1447 + feed={props.selectedThreadFeed}
1448 + pendingHandoff={props.pendingHandoff}
1449 + worktreeSetup={props.worktreeSetup}
1450 + setupWorkingStartedAt={props.setupWorkingStartedAt}
1451 + queuedMessages={props.queuedMessages}
1452 + dispatchingMessageId={props.dispatchingMessageId}
1453 + // A native subagent has no composer to edit a pending message in;
1454 + // Cancel on the edit banner would discard it.
1455 + onEditPendingMessage={
1456 + isProviderSubagent || pendingMessageEditBlocked ? null : handleEditPendingMessage
1457 + }
1458 + contentPresentation={props.contentPresentation}
1459 + threadTitle={props.selectedThread.title}
1460 + latestRun={props.activityRun}
1461 + activeWorkStartedAt={props.activeWorkStartedAt}
1462 + runlessWorkActive={props.runlessWorkActive ?? false}
1463 + listRef={listRef}
1464 + freeze={freeze}
1465 + anchorMessageId={anchorMessageId}
1466 + jumpToMessageId={jumpMessageLoaded ? jumpMessageId : null}
1467 + onJumpedToMessage={() => finishThreadMessageJump(selectedThreadKey)}
1468 + ref={feedRef}
1469 + contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
1470 + keyboardOffset={composerKeyboardOffset}
1471 + sendingWithKeyboard={sendingWithKeyboard}
1472 + fitShortFeedToViewport={questionInFlow && !isKeyboardVisible}
1473 + contentTopInset={0}
1474 + contentBottomInset={
1475 + questionInFlow
1476 + ? 0
1477 + : estimatedOverlayHeight +
1478 + (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
1479 + }
1480 + contentMaxWidth={contentMaxWidth}
1481 + historyControls={props.historyControls}
1482 + contentSideInsets={nativeMetrics?.safeArea}
1483 + layoutVariant={layoutVariant}
1484 + usesAutomaticContentInsets={props.usesAutomaticContentInsets}
1485 + onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
1486 + onEndFollowEnabledChange={handleEndFollowEnabledChange}
1487 + skills={selectedProviderSkills}
1488 + onUseArtifactTemplate={handleUseArtifactTemplate}
1489 + />
1490 + </WorkspaceMutationIdProvider>
1491 </RenderErrorBoundary>
1492 </View>
1493 ) : (
apps/mobile/src/features/threads/ThreadMarkdownImage.tsx
+7 -1
@@ -19,6 +19,7 @@ import { PresentationSource } from "../../components/ui/NativePresentation";
19 import { useMediaActions } from "../../state/mediaActions";
20 import type { MediaActionsSource } from "../../lib/mediaActionsSource";
21 import { useAssetUrlState } from "../../state/assets";
22 +import { WorkspaceMutationIdContext } from "./workspaceMutationIdContext";
23 import { assetImageCacheKey } from "../../lib/assetImageSource";
24 import {
25 MARKDOWN_IMAGE_MAX_WIDTH,
@@ -277,7 +278,12 @@ export function ThreadMarkdownImage(props: {
278 readonly onPressPreview: (source: FilePreviewSource) => void;
279 }) {
280 const withGallery = useFilePreviewGallery();
280 - const assetUrl = useAssetUrlState(props.environmentId, props.resource);
281 + const workspaceMutationId = useContext(WorkspaceMutationIdContext);
282 + const assetUrl = useAssetUrlState(
283 + props.environmentId,
284 + props.resource,
285 + props.resource._tag === "media-file" ? workspaceMutationId : undefined,
286 + );
287 const resourceKey =
288 props.resource._tag === "attachment"
289 ? `attachment:${props.resource.attachmentId}`
apps/mobile/src/features/threads/WorkspaceMutationIdProvider.tsx new
+25
@@ -0,0 +1,25 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import type { ScopedThreadRef } from "@t3tools/contracts";
3 +import { Atom } from "effect/reactivity";
4 +import type { ReactNode } from "react";
5 +
6 +import { environmentThreadDetails } from "../../state/threads";
7 +import { WorkspaceMutationIdContext } from "./workspaceMutationIdContext";
8 +
9 +const NO_WORKSPACE_MUTATION_ID_ATOM = Atom.make<string | null | undefined>(undefined);
10 +
11 +export function WorkspaceMutationIdProvider(props: {
12 + readonly threadRef: ScopedThreadRef | null;
13 + readonly children: ReactNode;
14 +}) {
15 + const workspaceMutationId = useAtomValue(
16 + props.threadRef === null
17 + ? NO_WORKSPACE_MUTATION_ID_ATOM
18 + : environmentThreadDetails.workspaceMutationIdAtom(props.threadRef),
19 + );
20 + return (
21 + <WorkspaceMutationIdContext value={workspaceMutationId}>
22 + {props.children}
23 + </WorkspaceMutationIdContext>
24 + );
25 +}
apps/mobile/src/features/threads/workspaceMutationIdContext.ts new
+4
@@ -0,0 +1,4 @@
1 +import { createContext } from "react";
2 +
3 +/** The thread's workspace mutation id, so a host image the agent rewrites gets a fresh URL. */
4 +export const WorkspaceMutationIdContext = createContext<string | null | undefined>(undefined);
apps/mobile/src/state/assets.ts
+11 -1
@@ -6,6 +6,7 @@ import {
6 createAssetEnvironmentAtoms,
7 createProjectFaviconUrlAtomFamily,
8 EMPTY_ASSET_URL_ATOM,
9 + makeRevisionedAssetUrlFamily,
10 } from "@t3tools/client-runtime/state/assets";
11 import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
12 import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
@@ -34,9 +35,16 @@ export const projectFaviconUrlAtom = createProjectFaviconUrlAtomFamily({
35 projectClones: environmentProjectCloneListAtom,
36 });
37
38 +const revisionedAssetUrl = makeRevisionedAssetUrlFamily(assetEnvironment.createUrl);
39 +
40 +/**
41 + * Pass `revision` for a host file whose bytes can change under the same path; each new
42 + * revision re-mints the URL so the image reloads.
43 + */
44 export function useAssetUrlState(
45 environmentId: EnvironmentId | null,
46 resource: AssetResource | null,
47 + revision?: string | null,
48 ): AssetUrlState {
49 const fileAccessSession = useEnvironmentQuery(
50 environmentId === null ? null : environmentSession.sessionStateAtom(environmentId),
@@ -54,7 +62,9 @@ export function useAssetUrlState(
62 const result = useAtomValue(
63 blocked !== null || environmentId === null || resource === null
64 ? EMPTY_ASSET_URL_ATOM
57 - : assetEnvironment.createUrl({ environmentId, input: { resource } }),
65 + : revision === undefined
66 + ? assetEnvironment.createUrl({ environmentId, input: { resource } })
67 + : revisionedAssetUrl({ environmentId, input: { resource }, revision }),
68 );
69 const shared =
70 blocked ??
apps/web/src/assets/assetUrls.test.ts deleted
-107
@@ -1,107 +0,0 @@
1 -import { EnvironmentId, ThreadId, type AssetResource } from "@t3tools/contracts";
2 -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
3 -import { describe, expect, it } from "vite-plus/test";
4 -
5 -import { makeRevisionedAssetUrlFamily } from "./assetUrls";
6 -
7 -const environmentId = EnvironmentId.make("environment-1");
8 -const resource: AssetResource = {
9 - _tag: "workspace-file",
10 - threadId: ThreadId.make("thread-1"),
11 - path: "docs/diagram.png",
12 -};
13 -
14 -type MintResult = AsyncResult.AsyncResult<{ relativeUrl: string; expiresAt: number }>;
15 -
16 -const minted = (n: number): MintResult =>
17 - AsyncResult.success({ relativeUrl: `/a/${n}`, expiresAt: 0 });
18 -
19 -// A stand-in for the asset URL query: a refresh starts a mint (counted, shown as
20 -// waiting) and `settle` completes the latest one.
21 -function setup(initial: MintResult) {
22 - let mints = 0;
23 - // Node removal runs on the registry's scheduler; `unmount` flushes it so the
24 - // next mount of the same revision builds a fresh node.
25 - const scheduled: Array<() => void> = [];
26 - const registry = AtomRegistry.make({
27 - scheduleTask: (task) => {
28 - scheduled.push(task);
29 - return () => {};
30 - },
31 - });
32 - const server = Atom.make(initial).pipe(Atom.keepAlive);
33 - const query = Atom.readable(
34 - (get) => get(server),
35 - () => {
36 - mints += 1;
37 - registry.set(server, AsyncResult.waiting(registry.get(server)));
38 - },
39 - ).pipe(Atom.keepAlive);
40 - const revisioned = makeRevisionedAssetUrlFamily(() => query);
41 - const mount = (revision: string | null) => {
42 - const release = registry.mount(revisioned({ environmentId, input: { resource }, revision }));
43 - return () => {
44 - release();
45 - for (const task of scheduled.splice(0)) task();
46 - };
47 - };
48 - const settle = () => registry.set(server, minted(mints + 1));
49 - return { mount, settle, mints: () => mints };
50 -}
51 -
52 -describe("makeRevisionedAssetUrlFamily", () => {
53 - it("re-mints a settled URL on first read and on each new revision, not on remount", () => {
54 - const { mount, settle, mints } = setup(minted(0));
55 -
56 - mount("mutation-1")();
57 - expect(mints()).toBe(1);
58 - settle();
59 -
60 - mount("mutation-1")();
61 - expect(mints()).toBe(1);
62 -
63 - mount("mutation-2")();
64 - expect(mints()).toBe(2);
65 - });
66 -
67 - it("re-mints when a revert returns to an earlier revision", () => {
68 - const { mount, settle, mints } = setup(minted(0));
69 -
70 - mount("mutation-a")();
71 - settle();
72 - mount("mutation-b")();
73 - settle();
74 - expect(mints()).toBe(2);
75 -
76 - const reverted = mount("mutation-a");
77 - expect(mints()).toBe(3);
78 - reverted();
79 - });
80 -
81 - it("shares a mint in flight on the first read", () => {
82 - const { mount, mints } = setup(AsyncResult.initial(true));
83 -
84 - mount("mutation-1")();
85 - expect(mints()).toBe(0);
86 - });
87 -
88 - it("re-mints after a mint that was in flight when the revision changed", () => {
89 - const { mount, settle, mints } = setup(minted(0));
90 -
91 - const before = mount("mutation-1");
92 - settle();
93 - const edited = mount("mutation-2");
94 - expect(mints()).toBe(2);
95 - before();
96 -
97 - const stillMinting = mount("mutation-3");
98 - edited();
99 - expect(mints()).toBe(2);
100 -
101 - settle();
102 - expect(mints()).toBe(3);
103 - settle();
104 - expect(mints()).toBe(3);
105 - stillMinting();
106 - });
107 -});
apps/web/src/assets/assetUrls.ts
+3 -69
@@ -4,12 +4,12 @@ import {
4 assetUrlStateFromResult,
5 blockedAssetUrlState,
6 EMPTY_ASSET_URL_ATOM,
7 + makeRevisionedAssetUrlFamily,
8 resolveAssetUrl,
9 } from "@t3tools/client-runtime/state/assets";
10 import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
10 -import { AssetResource, type AssetCreateUrlResult, EnvironmentId } from "@t3tools/contracts";
11 -import * as Schema from "effect/Schema";
12 -import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
11 +import { AssetResource, EnvironmentId } from "@t3tools/contracts";
12 +import { AsyncResult } from "effect/reactivity";
13
14 import { assetEnvironment } from "~/state/assets";
15 import { useFilesystemReadAccess } from "~/state/filesystem";
@@ -20,72 +20,6 @@ export { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
20
21 export type AssetUrlState = RuntimeAssetUrlState & { readonly waiting?: boolean };
22
23 -type AssetUrlTarget = {
24 - readonly environmentId: EnvironmentId;
25 - readonly input: { readonly resource: AssetResource };
26 -};
27 -
28 -const decodeRevisionedAssetUrlKey = Schema.decodeUnknownSync(
29 - Schema.Tuple([EnvironmentId, AssetResource, Schema.NullOr(Schema.String)]),
30 -);
31 -
32 -const isSettled = (result: AsyncResult.AsyncResult<unknown, unknown>) =>
33 - !AsyncResult.isInitial(result) && !result.waiting;
34 -
35 -/**
36 - * The URL is minted per resource and shared across revisions, so reading a
37 - * different revision (even an earlier one after a revert) re-mints it. An
38 - * in-flight mint is shared only on first read; after an edit the server must
39 - * re-read the file, so the re-mint waits for that mint to settle.
40 - */
41 -export function makeRevisionedAssetUrlFamily(
42 - createUrl: (
43 - target: AssetUrlTarget,
44 - ) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>,
45 -) {
46 - // Outside the nodes: a node is dropped once unmounted, and the next read of
47 - // its revision must still see the revisions minted since. Never pruned on
48 - // purpose: pruning would forget the revision and re-mint on the next mount.
49 - // It holds one short entry per file shown, and goes with the registry.
50 - const mintedUnder = new WeakMap<AtomRegistry.AtomRegistry, Map<string, string | null>>();
51 - const family = Atom.family((key: string) => {
52 - const [environmentId, resource, revision] = decodeRevisionedAssetUrlKey(JSON.parse(key));
53 - const resourceKey = JSON.stringify([environmentId, resource]);
54 - const query = createUrl({ environmentId, input: { resource } });
55 - return Atom.transform(
56 - query,
57 - (get) => {
58 - let minted = mintedUnder.get(get.registry);
59 - if (minted === undefined) {
60 - minted = new Map();
61 - mintedUnder.set(get.registry, minted);
62 - }
63 - const firstRead = !minted.has(resourceKey);
64 - let pending = minted.get(resourceKey) !== revision;
65 - const current = get.once(query);
66 - if (pending && (firstRead || isSettled(current))) {
67 - pending = false;
68 - minted.set(resourceKey, revision);
69 - if (isSettled(current)) get.refresh(query);
70 - }
71 - get.subscribe(query, (value) => {
72 - get.setSelf(value);
73 - if (!pending || !isSettled(value)) return;
74 - pending = false;
75 - minted.set(resourceKey, revision);
76 - get.refresh(query);
77 - });
78 - return get.once(query);
79 - },
80 - { initialValueTarget: query },
81 - // No idle TTL: each mount rebuilds the node, so a revision read again after
82 - // another one is compared against the record instead of a cached node.
83 - ).pipe(Atom.setIdleTTL(0));
84 - });
85 - return (target: AssetUrlTarget & { readonly revision: string | null }) =>
86 - family(JSON.stringify([target.environmentId, target.input.resource, target.revision]));
87 -}
88 -
23 const revisionedAssetUrl = makeRevisionedAssetUrlFamily(assetEnvironment.createUrl);
24
25 /**
apps/web/src/components/ChatView.logic.test.ts
-27
@@ -7,7 +7,6 @@ import {
7 snapshotComposerSend,
8 withMessageContext,
9 deriveAvailableRevertTurnCounts,
10 - deriveWorkspaceMutationId,
10 } from "./ChatView.logic";
11 import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic";
12 import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
@@ -1259,29 +1258,3 @@ describe("deriveAvailableRevertTurnCounts", () => {
1258 expect(deriveAvailableRevertTurnCounts(null).size).toBe(0);
1259 });
1260 });
1262 -
1263 -describe("deriveWorkspaceMutationId", () => {
1264 - const item = (id: string, type: string, status: string) =>
1265 - ({
1266 - item: { id: TurnItemId.make(id), type, status },
1267 - }) as unknown as OrchestrationV2ProjectedTurnItem;
1268 -
1269 - it("keys on the latest finished command or file change and the latest checkpoint", () => {
1270 - expect(
1271 - deriveWorkspaceMutationId(
1272 - [
1273 - item("edit", "file_change", "completed"),
1274 - item("reply", "assistant_message", "completed"),
1275 - item("command", "command_execution", "running"),
1276 - ],
1277 - "2026-01-01T00:00:00.000Z",
1278 - ),
1279 - ).toBe(JSON.stringify(["edit", "2026-01-01T00:00:00.000Z"]));
1280 - });
1281 -
1282 - it("is null before anything could have touched the workspace", () => {
1283 - expect(deriveWorkspaceMutationId([item("reply", "assistant_message", "completed")], null)).toBe(
1284 - null,
1285 - );
1286 - });
1287 -});
apps/web/src/components/ChatView.logic.ts
-25
@@ -1618,28 +1618,3 @@ export function deriveAvailableRevertTurnCounts(projection: ThreadStructure | nu
1618 }
1619 return available;
1620 }
1621 -
1622 -/**
1623 - * Changes when the agent may have changed the workspace, so file views refresh. File tools are
1624 - * explicit; completed commands are included because a shell command can mutate the workspace
1625 - * without reporting the paths it touched.
1626 - */
1627 -export function deriveWorkspaceMutationId(
1628 - visibleTurnItems: ReadonlyArray<ThreadStructureRow>,
1629 - latestCheckpointCompletedAt: string | null,
1630 -) {
1631 - let itemId: string | null = null;
1632 - for (let index = visibleTurnItems.length - 1; index >= 0; index -= 1) {
1633 - const item = visibleTurnItems[index]?.item;
1634 - if (!item) continue;
1635 - if (item.type !== "command_execution" && item.type !== "file_change") continue;
1636 - if (item.status === "pending" || item.status === "running" || item.status === "waiting") {
1637 - continue;
1638 - }
1639 - itemId = item.id;
1640 - break;
1641 - }
1642 - return itemId === null && latestCheckpointCompletedAt === null
1643 - ? null
1644 - : JSON.stringify([itemId, latestCheckpointCompletedAt]);
1645 -}
apps/web/src/components/ChatView.tsx
+102 -99
@@ -9,7 +9,6 @@ import { announcedRun, isDetailBehindShell } from "./chat/threadActivityAnnounce
9 import {
10 deriveAvailableRevertTurnCounts,
11 deriveThreadPendingBackgroundTasks,
12 - deriveWorkspaceMutationId,
12 presentThreadShellFromProjection,
13 } from "./ChatView.logic";
14 import { usePullRequestDraftThread } from "./chat/usePullRequestDraftThread";
@@ -93,6 +92,7 @@ import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
92 import { HandoffRow } from "./chat/V2LifecycleRow";
93 import {
94 codexFeedbackMessage,
95 + deriveWorkspaceMutationId,
96 isCompleteTurnItemRow,
97 shouldShowLoadEarlierControl,
98 type CodexFeedbackSubmission,
@@ -111,6 +111,7 @@ import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
111 import { useAtomValue } from "@effect/atom-react";
112 import { type SetStateAction, use, useEffect, useLayoutEffect, useRef, useState } from "react";
113 import { BackgroundThreadContext } from "./chat/backgroundThread";
114 +import { WorkspaceMutationIdContext } from "./chat/ChatMarkdownMedia";
115 import { useLocation, useNavigate } from "@tanstack/react-router";
116 import { assistantCitationFromLocation } from "../lib/assistantCitationNavigation";
117 import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
@@ -3386,104 +3387,106 @@ export default function ChatView(props: ChatViewProps) {
3387 {...conversationArea}
3388 className="relative flex min-h-0 flex-1 flex-col bg-background"
3389 >
3389 - <ThreadTimeline
3390 - pendingApprovals={pendingApprovals}
3391 - heldApprovalRequestIds={heldApprovalRequestIds}
3392 - respondingRequestIds={respondingRequestIds}
3393 - onRespondToApproval={onRespondToApprovalStable}
3394 - canOperateThread={canOperateThread}
3395 - threadDetailRef={routeThreadDetailRef}
3396 - entriesInput={timelineEntriesInput}
3397 - draftEntries={isServerThread ? null : draftTimelineEntries}
3398 - activeThreadKey={activeThreadKey}
3399 - syncing={threadSyncPhase !== null}
3400 - detailLoading={threadDetailLoading}
3401 - citationRequest={citationRequest}
3402 - citationHistory={citationHistory}
3403 - onCiteAssistantText={citeAssistantTextStable}
3404 - {...(activeProject
3405 - ? { onRunShellCommand: parentPanel?.runShellCommand ?? runShellCommandStable }
3406 - : {})}
3407 - isWorking={isWorking}
3408 - runlessWorkActive={runlessWorkStartedAt !== null}
3409 - isCompacting={isCompacting}
3410 - awaitingUser={
3411 - activePendingApproval !== null
3412 - ? "approval"
3413 - : activePendingUserInput !== null ||
3414 - // A secret request has no runtime request; the shell carries it.
3415 - activeThreadShell?.hasPendingUserInput === true
3416 - ? "input"
3417 - : null
3418 - }
3419 - awaitingRequestId={
3420 - activePendingApproval?.requestId ?? activePendingUserInput?.requestId ?? null
3421 - }
3422 - activeTurnStartedAt={activeWorkStartedAt}
3423 - worktreeSetup={worktreeSetup}
3424 - onCancelWorktreeSetup={onCancelWorktreeSetupStable}
3425 - retryableWorkspacePreparationRunIds={retryableWorkspacePreparationRunIds}
3426 - onRetryWorkspacePreparation={onRetryWorkspacePreparationStable}
3427 - {...(draftId
3428 - ? { onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocallyStable }
3429 - : {})}
3430 - {...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})}
3431 - isPreparingWorktree={isPreparingWorktree}
3432 - footer={timelineFooter}
3433 - listRef={legendListRef}
3434 - runs={serverProjection?.runs ?? []}
3435 - latestRun={activeActivityRun}
3436 - announcedRun={announcedRun(activeActivityRun, serverProjection?.runs ?? [])}
3437 - detailBehindShell={isDetailBehindShell(
3438 - activeLatestRun,
3439 - activeThreadShell?.latestRun ?? null,
3440 - )}
3441 - runningRunId={activeRunningTurnId}
3442 - turnDiffSummaries={turnDiffSummaries}
3443 - activeThreadEnvironmentId={
3444 - displayedThreadRef?.environmentId ?? activeThread.environmentId
3445 - }
3446 - routeThreadKey={displayedTimelineKey}
3447 - displayThreadKey={displayedTimelineKey}
3448 - announceTurnStatus={!isProviderSubagent}
3449 - onOpenToolDiff={parentPanel?.openToolDiff ?? onOpenToolDiffStable}
3450 - // Side chat runs keep no checkpoints to diff, and a fork would promote the side chat.
3451 - {...(embedded
3452 - ? {}
3453 - : { onOpenTurnDiff: onOpenTurnDiffStable, onForkFromRun: onForkFromRunStable })}
3454 - onOpenThread={onOpenRelatedThreadStable}
3455 - parentThreadLink={parentThreadLink}
3456 - workflowOpening={workflowOpening}
3457 - supportsConversationRollback={supportsConversationRollback}
3458 - threadStartCheckpointReady={threadStartCheckpointReady}
3459 - availableRevertTurnCounts={availableRevertTurnCounts}
3460 - onRevertToTurnCount={onRevertTimelineTurnStable}
3461 - onUseArtifactTemplate={insertArtifactTemplateStable}
3462 - onSendAppMessage={sendAppMessageStable}
3463 - isRevertingCheckpoint={isRevertingCheckpoint}
3464 - onImageExpand={onExpandTimelineImageStable}
3465 - onFileOpen={openFileAttachmentStable}
3466 - onFileDownload={downloadFileAttachmentStable}
3467 - markdownCwd={gitCwd ?? undefined}
3468 - resolvedTheme={resolvedTheme}
3469 - timestampFormat={timestampFormat}
3470 - workspaceRoot={activeWorkspaceRoot}
3471 - skills={timelineSkills}
3472 - anchorMessageId={timelineAnchorMessageId}
3473 - onAnchorReady={onTimelineAnchorReadyStable}
3474 - onAnchorSizeChanged={onTimelineAnchorSizeChangedStable}
3475 - contentInsetEndAdjustment={composerTimelineInset}
3476 - liveFollowEnabled={timelineLiveFollowEnabled}
3477 - onIsAtEndChange={onIsAtEndChangeStable}
3478 - onViewportAttach={attachTimelineViewport}
3479 - onFooterGrow={onTimelineFooterGrowStable}
3480 - hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}
3481 - emptyPlaceholderInset={composerReservedHeight}
3482 - topFadeEnabled={!hasTimelineTopBanner}
3483 - {...(threadHistoryControls === undefined
3484 - ? {}
3485 - : { historyControls: threadHistoryControls })}
3486 - />
3390 + <WorkspaceMutationIdContext value={workspaceMutationId}>
3391 + <ThreadTimeline
3392 + pendingApprovals={pendingApprovals}
3393 + heldApprovalRequestIds={heldApprovalRequestIds}
3394 + respondingRequestIds={respondingRequestIds}
3395 + onRespondToApproval={onRespondToApprovalStable}
3396 + canOperateThread={canOperateThread}
3397 + threadDetailRef={routeThreadDetailRef}
3398 + entriesInput={timelineEntriesInput}
3399 + draftEntries={isServerThread ? null : draftTimelineEntries}
3400 + activeThreadKey={activeThreadKey}
3401 + syncing={threadSyncPhase !== null}
3402 + detailLoading={threadDetailLoading}
3403 + citationRequest={citationRequest}
3404 + citationHistory={citationHistory}
3405 + onCiteAssistantText={citeAssistantTextStable}
3406 + {...(activeProject
3407 + ? { onRunShellCommand: parentPanel?.runShellCommand ?? runShellCommandStable }
3408 + : {})}
3409 + isWorking={isWorking}
3410 + runlessWorkActive={runlessWorkStartedAt !== null}
3411 + isCompacting={isCompacting}
3412 + awaitingUser={
3413 + activePendingApproval !== null
3414 + ? "approval"
3415 + : activePendingUserInput !== null ||
3416 + // A secret request has no runtime request; the shell carries it.
3417 + activeThreadShell?.hasPendingUserInput === true
3418 + ? "input"
3419 + : null
3420 + }
3421 + awaitingRequestId={
3422 + activePendingApproval?.requestId ?? activePendingUserInput?.requestId ?? null
3423 + }
3424 + activeTurnStartedAt={activeWorkStartedAt}
3425 + worktreeSetup={worktreeSetup}
3426 + onCancelWorktreeSetup={onCancelWorktreeSetupStable}
3427 + retryableWorkspacePreparationRunIds={retryableWorkspacePreparationRunIds}
3428 + onRetryWorkspacePreparation={onRetryWorkspacePreparationStable}
3429 + {...(draftId
3430 + ? { onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocallyStable }
3431 + : {})}
3432 + {...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})}
3433 + isPreparingWorktree={isPreparingWorktree}
3434 + footer={timelineFooter}
3435 + listRef={legendListRef}
3436 + runs={serverProjection?.runs ?? []}
3437 + latestRun={activeActivityRun}
3438 + announcedRun={announcedRun(activeActivityRun, serverProjection?.runs ?? [])}
3439 + detailBehindShell={isDetailBehindShell(
3440 + activeLatestRun,
3441 + activeThreadShell?.latestRun ?? null,
3442 + )}
3443 + runningRunId={activeRunningTurnId}
3444 + turnDiffSummaries={turnDiffSummaries}
3445 + activeThreadEnvironmentId={
3446 + displayedThreadRef?.environmentId ?? activeThread.environmentId
3447 + }
3448 + routeThreadKey={displayedTimelineKey}
3449 + displayThreadKey={displayedTimelineKey}
3450 + announceTurnStatus={!isProviderSubagent}
3451 + onOpenToolDiff={parentPanel?.openToolDiff ?? onOpenToolDiffStable}
3452 + // Side chat runs keep no checkpoints to diff, and a fork would promote the side chat.
3453 + {...(embedded
3454 + ? {}
3455 + : { onOpenTurnDiff: onOpenTurnDiffStable, onForkFromRun: onForkFromRunStable })}
3456 + onOpenThread={onOpenRelatedThreadStable}
3457 + parentThreadLink={parentThreadLink}
3458 + workflowOpening={workflowOpening}
3459 + supportsConversationRollback={supportsConversationRollback}
3460 + threadStartCheckpointReady={threadStartCheckpointReady}
3461 + availableRevertTurnCounts={availableRevertTurnCounts}
3462 + onRevertToTurnCount={onRevertTimelineTurnStable}
3463 + onUseArtifactTemplate={insertArtifactTemplateStable}
3464 + onSendAppMessage={sendAppMessageStable}
3465 + isRevertingCheckpoint={isRevertingCheckpoint}
3466 + onImageExpand={onExpandTimelineImageStable}
3467 + onFileOpen={openFileAttachmentStable}
3468 + onFileDownload={downloadFileAttachmentStable}
3469 + markdownCwd={gitCwd ?? undefined}
3470 + resolvedTheme={resolvedTheme}
3471 + timestampFormat={timestampFormat}
3472 + workspaceRoot={activeWorkspaceRoot}
3473 + skills={timelineSkills}
3474 + anchorMessageId={timelineAnchorMessageId}
3475 + onAnchorReady={onTimelineAnchorReadyStable}
3476 + onAnchorSizeChanged={onTimelineAnchorSizeChangedStable}
3477 + contentInsetEndAdjustment={composerTimelineInset}
3478 + liveFollowEnabled={timelineLiveFollowEnabled}
3479 + onIsAtEndChange={onIsAtEndChangeStable}
3480 + onViewportAttach={attachTimelineViewport}
3481 + onFooterGrow={onTimelineFooterGrowStable}
3482 + hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}
3483 + emptyPlaceholderInset={composerReservedHeight}
3484 + topFadeEnabled={!hasTimelineTopBanner}
3485 + {...(threadHistoryControls === undefined
3486 + ? {}
3487 + : { historyControls: threadHistoryControls })}
3488 + />
3489 + </WorkspaceMutationIdContext>
3490
3491 {showScrollToBottom && !isThreadFindActive && (
3492 <ScrollToEndButton
apps/web/src/components/chat/ChatMarkdownMedia.tsx
+7 -2
@@ -5,6 +5,7 @@ import { TriangleAlertIcon } from "lucide-react";
5 import {
6 createContext,
7 memo,
8 + use,
9 useState,
10 type ComponentProps,
11 type CSSProperties,
@@ -71,6 +72,8 @@ const CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME = cn(
72 CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME,
73 );
74 export const MarkdownLinkContext = createContext(false);
75 +/** The thread's workspace mutation id, so a host image the agent rewrites gets a fresh URL. */
76 +export const WorkspaceMutationIdContext = createContext<string | null | undefined>(undefined);
77
78 function expandableMarkdownImageProps(
79 onImageExpand: ((preview: ExpandedImagePreview) => void) | undefined,
@@ -339,13 +342,15 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
342 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
343 }) {
344 const resource = props.resource;
345 + const threadWorkspaceMutationId = use(WorkspaceMutationIdContext);
346 + const workspaceMutationId = props.workspaceMutationId ?? threadWorkspaceMutationId;
347 const assetUrl = useAssetUrlState(
348 props.environmentId,
349 resource,
345 - props.workspaceMutationId !== undefined &&
350 + workspaceMutationId !== undefined &&
351 props.kind !== "video" &&
352 (resource._tag === "media-file" || resource._tag === "workspace-file")
348 - ? props.workspaceMutationId
353 + ? workspaceMutationId
354 : undefined,
355 );
356 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
packages/client-runtime/src/state/assets.test.ts
+156 -1
@@ -1,5 +1,11 @@
1 import { describe, expect, it } from "@effect/vitest";
2 -import { type AssetCreateUrlResult, EnvironmentId, WS_METHODS } from "@t3tools/contracts";
2 +import {
3 + type AssetCreateUrlResult,
4 + type AssetResource,
5 + EnvironmentId,
6 + ThreadId,
7 + WS_METHODS,
8 +} from "@t3tools/contracts";
9 import * as Cause from "effect/Cause";
10 import * as Effect from "effect/Effect";
11 import * as Layer from "effect/Layer";
@@ -22,6 +28,7 @@ import {
28 ASSET_URL_MAX_IN_FLIGHT,
29 createAssetEnvironmentAtoms,
30 createProjectFaviconUrlAtomFamily,
31 + makeRevisionedAssetUrlFamily,
32 } from "./assets.ts";
33
34 describe("project favicon URL cache", () => {
@@ -229,3 +236,151 @@ describe("asset URL requests", () => {
236 ),
237 );
238 });
239 +
240 +const revisionedEnvironmentId = EnvironmentId.make("environment-1");
241 +const revisionedResource: AssetResource = {
242 + _tag: "workspace-file",
243 + threadId: ThreadId.make("thread-1"),
244 + path: "docs/diagram.png",
245 +};
246 +
247 +type MintResult = AsyncResult.AsyncResult<{
248 + relativeUrl: string;
249 + expiresAt: number;
250 + fileRevision?: string;
251 +}>;
252 +
253 +const minted = (n: number, fileRevision?: string): MintResult =>
254 + AsyncResult.success({
255 + relativeUrl: `/a/${n}`,
256 + expiresAt: 60 * 60_000,
257 + ...(fileRevision === undefined ? {} : { fileRevision }),
258 + });
259 +
260 +// A stand-in for the asset URL query: a refresh starts a mint (counted, shown as
261 +// waiting) and `settle` completes the latest one.
262 +function setup(initial: MintResult) {
263 + let mints = 0;
264 + // Node removal runs on the registry's scheduler; `unmount` flushes it so the
265 + // next mount of the same revision builds a fresh node.
266 + const scheduled: Array<() => void> = [];
267 + const registry = AtomRegistry.make({
268 + scheduleTask: (task) => {
269 + scheduled.push(task);
270 + return () => {};
271 + },
272 + });
273 + const server = Atom.make(initial).pipe(Atom.keepAlive);
274 + const query = Atom.readable(
275 + (get) => get(server),
276 + () => {
277 + mints += 1;
278 + registry.set(server, AsyncResult.waiting(registry.get(server)));
279 + },
280 + ).pipe(Atom.keepAlive);
281 + const revisioned = makeRevisionedAssetUrlFamily(
282 + () => query,
283 + () => 0,
284 + );
285 + const atom = (revision: string | null) =>
286 + revisioned({
287 + environmentId: revisionedEnvironmentId,
288 + input: { resource: revisionedResource },
289 + revision,
290 + });
291 + const mount = (revision: string | null) => {
292 + const release = registry.mount(atom(revision));
293 + return () => {
294 + release();
295 + for (const task of scheduled.splice(0)) task();
296 + };
297 + };
298 + const settle = (fileRevision?: string) => registry.set(server, minted(mints + 1, fileRevision));
299 + const url = (revision: string | null) => {
300 + const result = registry.get(atom(revision));
301 + return result._tag === "Success" ? result.value.relativeUrl : null;
302 + };
303 + return { mount, settle, url, mints: () => mints };
304 +}
305 +
306 +describe("makeRevisionedAssetUrlFamily", () => {
307 + it("re-mints a settled URL on first read and on each new revision, not on remount", () => {
308 + const { mount, settle, mints } = setup(minted(0));
309 +
310 + mount("mutation-1")();
311 + expect(mints()).toBe(1);
312 + settle();
313 +
314 + mount("mutation-1")();
315 + expect(mints()).toBe(1);
316 +
317 + mount("mutation-2")();
318 + expect(mints()).toBe(2);
319 + });
320 +
321 + it("re-mints when a revert returns to an earlier revision", () => {
322 + const { mount, settle, mints } = setup(minted(0));
323 +
324 + mount("mutation-a")();
325 + settle();
326 + mount("mutation-b")();
327 + settle();
328 + expect(mints()).toBe(2);
329 +
330 + const reverted = mount("mutation-a");
331 + expect(mints()).toBe(3);
332 + reverted();
333 + });
334 +
335 + it("shares a mint in flight on the first read", () => {
336 + const { mount, mints } = setup(AsyncResult.initial(true));
337 +
338 + mount("mutation-1")();
339 + expect(mints()).toBe(0);
340 + });
341 +
342 + it("re-mints after a mint that was in flight when the revision changed", () => {
343 + const { mount, settle, mints } = setup(minted(0));
344 +
345 + const before = mount("mutation-1");
346 + settle();
347 + const edited = mount("mutation-2");
348 + expect(mints()).toBe(2);
349 + before();
350 +
351 + const stillMinting = mount("mutation-3");
352 + edited();
353 + expect(mints()).toBe(2);
354 +
355 + settle();
356 + expect(mints()).toBe(3);
357 + settle();
358 + expect(mints()).toBe(3);
359 + stillMinting();
360 + });
361 +
362 + it("keeps the URL while the file is unchanged and swaps it once the file changes", () => {
363 + const { mount, settle, url } = setup(minted(0, "file-a"));
364 +
365 + const first = mount("mutation-1");
366 + settle("file-a");
367 + first();
368 +
369 + const unchanged = mount("mutation-2");
370 + settle("file-a");
371 + expect(url("mutation-2")).toBe("/a/0");
372 + unchanged();
373 +
374 + // The query now holds /a/3; a later revision must still keep the URL on screen.
375 + const stillUnchanged = mount("mutation-3");
376 + expect(url("mutation-3")).toBe("/a/0");
377 + settle("file-a");
378 + expect(url("mutation-3")).toBe("/a/0");
379 + stillUnchanged();
380 +
381 + const edited = mount("mutation-4");
382 + settle("file-b");
383 + expect(url("mutation-4")).toBe("/a/5");
384 + edited();
385 + });
386 +});
packages/client-runtime/src/state/assets.ts
+107
@@ -131,6 +131,113 @@ export function assetUrlStateFromResult(
131 };
132 }
133
134 +type AssetUrlTarget = {
135 + readonly environmentId: EnvironmentId;
136 + readonly input: { readonly resource: AssetResource };
137 +};
138 +
139 +const decodeRevisionedAssetUrlKey = Schema.decodeUnknownSync(
140 + Schema.Tuple([EnvironmentId, AssetResource, Schema.NullOr(Schema.String)]),
141 +);
142 +
143 +const isSettled = (result: AsyncResult.AsyncResult<unknown, unknown>) =>
144 + !AsyncResult.isInitial(result) && !result.waiting;
145 +
146 +const KEEP_URL_MIN_LIFE_MS = 5 * 60_000;
147 +
148 +/**
149 + * A re-mint signs a new URL even when the file is unchanged, and a new URL reloads the image.
150 + * Keep the shown URL while the server reports the same file revision and it has time left.
151 + */
152 +function keepUnchangedFile(
153 + shown: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
154 + next: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
155 + now: number,
156 +) {
157 + if (
158 + shown._tag !== "Success" ||
159 + next._tag !== "Success" ||
160 + next.value.fileRevision === undefined ||
161 + next.value.fileRevision !== shown.value.fileRevision ||
162 + shown.value.expiresAt - now <= KEEP_URL_MIN_LIFE_MS
163 + ) {
164 + return next;
165 + }
166 + const kept = AsyncResult.success(shown.value);
167 + return next.waiting ? AsyncResult.waiting(kept) : kept;
168 +}
169 +
170 +/**
171 + * The URL is minted per resource and shared across revisions, so reading a
172 + * different revision (even an earlier one after a revert) re-mints it. An
173 + * in-flight mint is shared only on first read; after an edit the server must
174 + * re-read the file, so the re-mint waits for that mint to settle.
175 + */
176 +export function makeRevisionedAssetUrlFamily(
177 + createUrl: (
178 + target: AssetUrlTarget,
179 + ) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>,
180 + now: () => number = Date.now,
181 +) {
182 + // Outside the nodes: a node is dropped once unmounted, and the next read of
183 + // its revision must still see the revisions minted since. Never pruned on
184 + // purpose: pruning would forget the revision and re-mint on the next mount.
185 + // It holds one short entry per file shown, and goes with the registry.
186 + const mintedUnder = new WeakMap<AtomRegistry.AtomRegistry, Map<string, string | null>>();
187 + // Also per resource: a new revision builds a new node, which must keep the URL on screen.
188 + const shownUnder = new WeakMap<
189 + AtomRegistry.AtomRegistry,
190 + Map<string, AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>
191 + >();
192 + const family = Atom.family((key: string) => {
193 + const [environmentId, resource, revision] = decodeRevisionedAssetUrlKey(JSON.parse(key));
194 + const resourceKey = JSON.stringify([environmentId, resource]);
195 + const query = createUrl({ environmentId, input: { resource } });
196 + return Atom.transform(
197 + query,
198 + (get) => {
199 + let minted = mintedUnder.get(get.registry);
200 + if (minted === undefined) {
201 + minted = new Map();
202 + mintedUnder.set(get.registry, minted);
203 + }
204 + const firstRead = !minted.has(resourceKey);
205 + let pending = minted.get(resourceKey) !== revision;
206 + const current = get.once(query);
207 + if (pending && (firstRead || isSettled(current))) {
208 + pending = false;
209 + minted.set(resourceKey, revision);
210 + if (isSettled(current)) get.refresh(query);
211 + }
212 + let shownByResource = shownUnder.get(get.registry);
213 + if (shownByResource === undefined) {
214 + shownByResource = new Map();
215 + shownUnder.set(get.registry, shownByResource);
216 + }
217 + const show = (value: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>) => {
218 + const previous = shownByResource.get(resourceKey);
219 + const shown = previous === undefined ? value : keepUnchangedFile(previous, value, now());
220 + shownByResource.set(resourceKey, shown);
221 + return shown;
222 + };
223 + get.subscribe(query, (value) => {
224 + get.setSelf(show(value));
225 + if (!pending || !isSettled(value)) return;
226 + pending = false;
227 + minted.set(resourceKey, revision);
228 + get.refresh(query);
229 + });
230 + return show(get.once(query));
231 + },
232 + { initialValueTarget: query },
233 + // No idle TTL: each mount rebuilds the node, so a revision read again after
234 + // another one is compared against the record instead of a cached node.
235 + ).pipe(Atom.setIdleTTL(0));
236 + });
237 + return (target: AssetUrlTarget & { readonly revision: string | null }) =>
238 + family(JSON.stringify([target.environmentId, target.input.resource, target.revision]));
239 +}
240 +
241 export function createAssetEnvironmentAtoms<R, E>(
242 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
243 localMediaEnvironment?: Atom.Atom<{
packages/client-runtime/src/state/threadDetail.test.ts
+38 -1
@@ -14,7 +14,12 @@ import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
14
15 import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
16 import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
17 -import { createEnvironmentThreadDetailAtoms, sameThreadStructure } from "./threadDetail.ts";
17 +import type { ThreadStructureVisibleTurnItem } from "./models.ts";
18 +import {
19 + createEnvironmentThreadDetailAtoms,
20 + deriveWorkspaceMutationId,
21 + sameThreadStructure,
22 +} from "./threadDetail.ts";
23 import { mergeOlderHistoryIntoProjection } from "./threadHistoryMerge.ts";
24 import { EMPTY_ENVIRONMENT_THREAD_STATE } from "./threadState.ts";
25
@@ -349,3 +354,35 @@ it("matches full structure comparisons across streamed, batched, and reordered u
354 [assistant.id, 1],
355 ]);
356 });
357 +
358 +describe("deriveWorkspaceMutationId", () => {
359 + const item = (id: string, type: string, status: string) =>
360 + ({
361 + item: { id: TurnItemId.make(id), type, status },
362 + }) as unknown as ThreadStructureVisibleTurnItem;
363 +
364 + it("keys on the latest finished command or file change and the latest checkpoint", () => {
365 + expect(
366 + deriveWorkspaceMutationId(
367 + [
368 + item("edit", "file_change", "completed"),
369 + item("reply", "assistant_message", "completed"),
370 + item("command", "command_execution", "running"),
371 + ],
372 + "2026-01-01T00:00:00.000Z",
373 + ),
374 + ).toBe(JSON.stringify(["edit", "2026-01-01T00:00:00.000Z"]));
375 + expect(
376 + deriveWorkspaceMutationId(
377 + [item("edit", "file_change", "completed"), item("mcp", "dynamic_tool", "completed")],
378 + null,
379 + ),
380 + ).toBe(JSON.stringify(["mcp", null]));
381 + });
382 +
383 + it("is null before anything could have touched the workspace", () => {
384 + expect(deriveWorkspaceMutationId([item("reply", "assistant_message", "completed")], null)).toBe(
385 + null,
386 + );
387 + });
388 +});
packages/client-runtime/src/state/threadDetail.ts
+43
@@ -43,6 +43,38 @@ const EMPTY_THREAD_STRUCTURE_TURN_ITEMS: ReadonlyArray<ThreadStructureVisibleTur
43 Object.freeze([]);
44 const EMPTY_CHECKPOINT_SUMMARIES: ReadonlyArray<ThreadCheckpointSummary> = Object.freeze([]);
45
46 +/**
47 + * Changes when the agent may have changed the workspace, so file views and host images refresh.
48 + * File tools are explicit; commands, MCP or dynamic tools and subagents are included because
49 + * they can mutate the workspace without reporting the paths they touched.
50 + */
51 +export function deriveWorkspaceMutationId(
52 + visibleTurnItems: ReadonlyArray<ThreadStructureVisibleTurnItem>,
53 + latestCheckpointCompletedAt: string | null,
54 +) {
55 + let itemId: string | null = null;
56 + for (let index = visibleTurnItems.length - 1; index >= 0; index -= 1) {
57 + const item = visibleTurnItems[index]?.item;
58 + if (!item) continue;
59 + if (
60 + item.type !== "command_execution" &&
61 + item.type !== "file_change" &&
62 + item.type !== "dynamic_tool" &&
63 + item.type !== "subagent"
64 + ) {
65 + continue;
66 + }
67 + if (item.status === "pending" || item.status === "running" || item.status === "waiting") {
68 + continue;
69 + }
70 + itemId = item.id;
71 + break;
72 + }
73 + return itemId === null && latestCheckpointCompletedAt === null
74 + ? null
75 + : JSON.stringify([itemId, latestCheckpointCompletedAt]);
76 +}
77 +
78 type TurnItem = OrchestrationV2ThreadProjection["turnItems"][number];
79 type VisibleTurnItem = OrchestrationV2ThreadProjection["visibleTurnItems"][number];
80 type AppThread = OrchestrationV2ThreadProjection["thread"];
@@ -501,8 +533,19 @@ export function createEnvironmentThreadDetailAtoms<E>(
533 ),
534 );
535
536 + const workspaceMutationIdAtomFamily = Atom.family((key: string) =>
537 + Atom.make((get) =>
538 + deriveWorkspaceMutationId(
539 + get(quietVisibleTurnItemsAtomFamily(key)),
540 + get(checkpointSummariesAtomFamily(key)).at(-1)?.completedAt ?? null,
541 + ),
542 + ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-workspace-mutation-id:${key}`)),
543 + );
544 +
545 return {
546 worktreePathAtom: (ref: ScopedThreadRef) => worktreePathAtomFamily(threadKey(ref)),
547 + workspaceMutationIdAtom: (ref: ScopedThreadRef) =>
548 + workspaceMutationIdAtomFamily(threadKey(ref)),
549 updatedAtAtom: (ref: ScopedThreadRef) => updatedAtAtomFamily(threadKey(ref)),
550 lastVisitedAtAtom: (ref: ScopedThreadRef) => lastVisitedAtAtomFamily(threadKey(ref)),
551 pendingRequestsAtom: (ref: ScopedThreadRef) => pendingRequestsAtomFamily(threadKey(ref)),