Skip to content
TypeScript

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

Julius Marmingee0f69e9ea4cb
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index 5a427ca8033..d0b08ce405d 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -197,6 +197,7 @@ import {
} from "./ThreadComposer";
import { ComposerPopoverHost } from "./ComposerPopoverHost";
import { ThreadFeed, type ThreadFeedHandle, type ThreadFeedHistoryControls } from "./ThreadFeed";
+import { WorkspaceMutationIdProvider } from "./WorkspaceMutationIdProvider";
import { useThreadTurnSubagents } from "./ThreadAgentsSheet";
import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";
import { useThreadQueuedCount } from "./ThreadQueueControl";
@@ -1437,54 +1438,56 @@ function ThreadDetailBody(
/>
)}
>
- <ThreadFeed
- environmentId={props.environmentId}
- threadId={props.selectedThread.id}
- detailRef={props.selectedThreadDetailRef}
- workspaceRoot={props.threadCwd}
- feed={props.selectedThreadFeed}
- pendingHandoff={props.pendingHandoff}
- worktreeSetup={props.worktreeSetup}
- setupWorkingStartedAt={props.setupWorkingStartedAt}
- queuedMessages={props.queuedMessages}
- dispatchingMessageId={props.dispatchingMessageId}
- // A native subagent has no composer to edit a pending message in;
- // Cancel on the edit banner would discard it.
- onEditPendingMessage={
- isProviderSubagent || pendingMessageEditBlocked ? null : handleEditPendingMessage
- }
- contentPresentation={props.contentPresentation}
- threadTitle={props.selectedThread.title}
- latestRun={props.activityRun}
- activeWorkStartedAt={props.activeWorkStartedAt}
- runlessWorkActive={props.runlessWorkActive ?? false}
- listRef={listRef}
- freeze={freeze}
- anchorMessageId={anchorMessageId}
- jumpToMessageId={jumpMessageLoaded ? jumpMessageId : null}
- onJumpedToMessage={() => finishThreadMessageJump(selectedThreadKey)}
- ref={feedRef}
- contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
- keyboardOffset={composerKeyboardOffset}
- sendingWithKeyboard={sendingWithKeyboard}
- fitShortFeedToViewport={questionInFlow && !isKeyboardVisible}
- contentTopInset={0}
- contentBottomInset={
- questionInFlow
- ? 0
- : estimatedOverlayHeight +
- (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
- }
- contentMaxWidth={contentMaxWidth}
- historyControls={props.historyControls}
- contentSideInsets={nativeMetrics?.safeArea}
- layoutVariant={layoutVariant}
- usesAutomaticContentInsets={props.usesAutomaticContentInsets}
- onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
- onEndFollowEnabledChange={handleEndFollowEnabledChange}
- skills={selectedProviderSkills}
- onUseArtifactTemplate={handleUseArtifactTemplate}
- />
+ <WorkspaceMutationIdProvider threadRef={props.selectedThreadDetailRef}>
+ <ThreadFeed
+ environmentId={props.environmentId}
+ threadId={props.selectedThread.id}
+ detailRef={props.selectedThreadDetailRef}
+ workspaceRoot={props.threadCwd}
+ feed={props.selectedThreadFeed}
+ pendingHandoff={props.pendingHandoff}
+ worktreeSetup={props.worktreeSetup}
+ setupWorkingStartedAt={props.setupWorkingStartedAt}
+ queuedMessages={props.queuedMessages}
+ dispatchingMessageId={props.dispatchingMessageId}
+ // A native subagent has no composer to edit a pending message in;
+ // Cancel on the edit banner would discard it.
+ onEditPendingMessage={
+ isProviderSubagent || pendingMessageEditBlocked ? null : handleEditPendingMessage
+ }
+ contentPresentation={props.contentPresentation}
+ threadTitle={props.selectedThread.title}
+ latestRun={props.activityRun}
+ activeWorkStartedAt={props.activeWorkStartedAt}
+ runlessWorkActive={props.runlessWorkActive ?? false}
+ listRef={listRef}
+ freeze={freeze}
+ anchorMessageId={anchorMessageId}
+ jumpToMessageId={jumpMessageLoaded ? jumpMessageId : null}
+ onJumpedToMessage={() => finishThreadMessageJump(selectedThreadKey)}
+ ref={feedRef}
+ contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
+ keyboardOffset={composerKeyboardOffset}
+ sendingWithKeyboard={sendingWithKeyboard}
+ fitShortFeedToViewport={questionInFlow && !isKeyboardVisible}
+ contentTopInset={0}
+ contentBottomInset={
+ questionInFlow
+ ? 0
+ : estimatedOverlayHeight +
+ (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0)
+ }
+ contentMaxWidth={contentMaxWidth}
+ historyControls={props.historyControls}
+ contentSideInsets={nativeMetrics?.safeArea}
+ layoutVariant={layoutVariant}
+ usesAutomaticContentInsets={props.usesAutomaticContentInsets}
+ onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
+ onEndFollowEnabledChange={handleEndFollowEnabledChange}
+ skills={selectedProviderSkills}
+ onUseArtifactTemplate={handleUseArtifactTemplate}
+ />
+ </WorkspaceMutationIdProvider>
</RenderErrorBoundary>
</View>
) : (
diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx
index a0ff3301da4..04005284750 100644
--- a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx
+++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx
@@ -19,6 +19,7 @@ import { PresentationSource } from "../../components/ui/NativePresentation";
import { useMediaActions } from "../../state/mediaActions";
import type { MediaActionsSource } from "../../lib/mediaActionsSource";
import { useAssetUrlState } from "../../state/assets";
+import { WorkspaceMutationIdContext } from "./workspaceMutationIdContext";
import { assetImageCacheKey } from "../../lib/assetImageSource";
import {
MARKDOWN_IMAGE_MAX_WIDTH,
@@ -277,7 +278,12 @@ export function ThreadMarkdownImage(props: {
readonly onPressPreview: (source: FilePreviewSource) => void;
}) {
const withGallery = useFilePreviewGallery();
- const assetUrl = useAssetUrlState(props.environmentId, props.resource);
+ const workspaceMutationId = useContext(WorkspaceMutationIdContext);
+ const assetUrl = useAssetUrlState(
+ props.environmentId,
+ props.resource,
+ props.resource._tag === "media-file" ? workspaceMutationId : undefined,
+ );
const resourceKey =
props.resource._tag === "attachment"
? `attachment:${props.resource.attachmentId}`
diff --git a/apps/mobile/src/features/threads/WorkspaceMutationIdProvider.tsx b/apps/mobile/src/features/threads/WorkspaceMutationIdProvider.tsx
new file mode 100644
index 00000000000..ec078c2b52c
--- /dev/null
+++ b/apps/mobile/src/features/threads/WorkspaceMutationIdProvider.tsx
@@ -0,0 +1,25 @@
+import { useAtomValue } from "@effect/atom-react";
+import type { ScopedThreadRef } from "@t3tools/contracts";
+import { Atom } from "effect/reactivity";
+import type { ReactNode } from "react";
+
+import { environmentThreadDetails } from "../../state/threads";
+import { WorkspaceMutationIdContext } from "./workspaceMutationIdContext";
+
+const NO_WORKSPACE_MUTATION_ID_ATOM = Atom.make<string | null | undefined>(undefined);
+
+export function WorkspaceMutationIdProvider(props: {
+ readonly threadRef: ScopedThreadRef | null;
+ readonly children: ReactNode;
+}) {
+ const workspaceMutationId = useAtomValue(
+ props.threadRef === null
+ ? NO_WORKSPACE_MUTATION_ID_ATOM
+ : environmentThreadDetails.workspaceMutationIdAtom(props.threadRef),
+ );
+ return (
+ <WorkspaceMutationIdContext value={workspaceMutationId}>
+ {props.children}
+ </WorkspaceMutationIdContext>
+ );
+}
diff --git a/apps/mobile/src/features/threads/workspaceMutationIdContext.ts b/apps/mobile/src/features/threads/workspaceMutationIdContext.ts
new file mode 100644
index 00000000000..b564829a14d
--- /dev/null
+++ b/apps/mobile/src/features/threads/workspaceMutationIdContext.ts
@@ -0,0 +1,4 @@
+import { createContext } from "react";
+
+/** The thread's workspace mutation id, so a host image the agent rewrites gets a fresh URL. */
+export const WorkspaceMutationIdContext = createContext<string | null | undefined>(undefined);
diff --git a/apps/mobile/src/state/assets.ts b/apps/mobile/src/state/assets.ts
index c065c057705..d29833dfd42 100644
--- a/apps/mobile/src/state/assets.ts
+++ b/apps/mobile/src/state/assets.ts
@@ -6,6 +6,7 @@ import {
createAssetEnvironmentAtoms,
createProjectFaviconUrlAtomFamily,
EMPTY_ASSET_URL_ATOM,
+ makeRevisionedAssetUrlFamily,
} from "@t3tools/client-runtime/state/assets";
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
@@ -34,9 +35,16 @@ export const projectFaviconUrlAtom = createProjectFaviconUrlAtomFamily({
projectClones: environmentProjectCloneListAtom,
});
+const revisionedAssetUrl = makeRevisionedAssetUrlFamily(assetEnvironment.createUrl);
+
+/**
+ * Pass `revision` for a host file whose bytes can change under the same path; each new
+ * revision re-mints the URL so the image reloads.
+ */
export function useAssetUrlState(
environmentId: EnvironmentId | null,
resource: AssetResource | null,
+ revision?: string | null,
): AssetUrlState {
const fileAccessSession = useEnvironmentQuery(
environmentId === null ? null : environmentSession.sessionStateAtom(environmentId),
@@ -54,7 +62,9 @@ export function useAssetUrlState(
const result = useAtomValue(
blocked !== null || environmentId === null || resource === null
? EMPTY_ASSET_URL_ATOM
- : assetEnvironment.createUrl({ environmentId, input: { resource } }),
+ : revision === undefined
+ ? assetEnvironment.createUrl({ environmentId, input: { resource } })
+ : revisionedAssetUrl({ environmentId, input: { resource }, revision }),
);
const shared =
blocked ??
diff --git a/apps/web/src/assets/assetUrls.test.ts b/apps/web/src/assets/assetUrls.test.ts
deleted file mode 100644
index bb442959f18..00000000000
--- a/apps/web/src/assets/assetUrls.test.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import { EnvironmentId, ThreadId, type AssetResource } from "@t3tools/contracts";
-import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
-import { describe, expect, it } from "vite-plus/test";
-
-import { makeRevisionedAssetUrlFamily } from "./assetUrls";
-
-const environmentId = EnvironmentId.make("environment-1");
-const resource: AssetResource = {
- _tag: "workspace-file",
- threadId: ThreadId.make("thread-1"),
- path: "docs/diagram.png",
-};
-
-type MintResult = AsyncResult.AsyncResult<{ relativeUrl: string; expiresAt: number }>;
-
-const minted = (n: number): MintResult =>
- AsyncResult.success({ relativeUrl: `/a/${n}`, expiresAt: 0 });
-
-// A stand-in for the asset URL query: a refresh starts a mint (counted, shown as
-// waiting) and `settle` completes the latest one.
-function setup(initial: MintResult) {
- let mints = 0;
- // Node removal runs on the registry's scheduler; `unmount` flushes it so the
- // next mount of the same revision builds a fresh node.
- const scheduled: Array<() => void> = [];
- const registry = AtomRegistry.make({
- scheduleTask: (task) => {
- scheduled.push(task);
- return () => {};
- },
- });
- const server = Atom.make(initial).pipe(Atom.keepAlive);
- const query = Atom.readable(
- (get) => get(server),
- () => {
- mints += 1;
- registry.set(server, AsyncResult.waiting(registry.get(server)));
- },
- ).pipe(Atom.keepAlive);
- const revisioned = makeRevisionedAssetUrlFamily(() => query);
- const mount = (revision: string | null) => {
- const release = registry.mount(revisioned({ environmentId, input: { resource }, revision }));
- return () => {
- release();
- for (const task of scheduled.splice(0)) task();
- };
- };
- const settle = () => registry.set(server, minted(mints + 1));
- return { mount, settle, mints: () => mints };
-}
-
-describe("makeRevisionedAssetUrlFamily", () => {
- it("re-mints a settled URL on first read and on each new revision, not on remount", () => {
- const { mount, settle, mints } = setup(minted(0));
-
- mount("mutation-1")();
- expect(mints()).toBe(1);
- settle();
-
- mount("mutation-1")();
- expect(mints()).toBe(1);
-
- mount("mutation-2")();
- expect(mints()).toBe(2);
- });
-
- it("re-mints when a revert returns to an earlier revision", () => {
- const { mount, settle, mints } = setup(minted(0));
-
- mount("mutation-a")();
- settle();
- mount("mutation-b")();
- settle();
- expect(mints()).toBe(2);
-
- const reverted = mount("mutation-a");
- expect(mints()).toBe(3);
- reverted();
- });
-
- it("shares a mint in flight on the first read", () => {
- const { mount, mints } = setup(AsyncResult.initial(true));
-
- mount("mutation-1")();
- expect(mints()).toBe(0);
- });
-
- it("re-mints after a mint that was in flight when the revision changed", () => {
- const { mount, settle, mints } = setup(minted(0));
-
- const before = mount("mutation-1");
- settle();
- const edited = mount("mutation-2");
- expect(mints()).toBe(2);
- before();
-
- const stillMinting = mount("mutation-3");
- edited();
- expect(mints()).toBe(2);
-
- settle();
- expect(mints()).toBe(3);
- settle();
- expect(mints()).toBe(3);
- stillMinting();
- });
-});
diff --git a/apps/web/src/assets/assetUrls.ts b/apps/web/src/assets/assetUrls.ts
index 7b48ed923d7..d14d750894e 100644
--- a/apps/web/src/assets/assetUrls.ts
+++ b/apps/web/src/assets/assetUrls.ts
@@ -4,12 +4,12 @@ import {
assetUrlStateFromResult,
blockedAssetUrlState,
EMPTY_ASSET_URL_ATOM,
+ makeRevisionedAssetUrlFamily,
resolveAssetUrl,
} from "@t3tools/client-runtime/state/assets";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
-import { AssetResource, type AssetCreateUrlResult, EnvironmentId } from "@t3tools/contracts";
-import * as Schema from "effect/Schema";
-import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
+import { AssetResource, EnvironmentId } from "@t3tools/contracts";
+import { AsyncResult } from "effect/reactivity";
import { assetEnvironment } from "~/state/assets";
import { useFilesystemReadAccess } from "~/state/filesystem";
@@ -20,72 +20,6 @@ export { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
export type AssetUrlState = RuntimeAssetUrlState & { readonly waiting?: boolean };
-type AssetUrlTarget = {
- readonly environmentId: EnvironmentId;
- readonly input: { readonly resource: AssetResource };
-};
-
-const decodeRevisionedAssetUrlKey = Schema.decodeUnknownSync(
- Schema.Tuple([EnvironmentId, AssetResource, Schema.NullOr(Schema.String)]),
-);
-
-const isSettled = (result: AsyncResult.AsyncResult<unknown, unknown>) =>
- !AsyncResult.isInitial(result) && !result.waiting;
-
-/**
- * The URL is minted per resource and shared across revisions, so reading a
- * different revision (even an earlier one after a revert) re-mints it. An
- * in-flight mint is shared only on first read; after an edit the server must
- * re-read the file, so the re-mint waits for that mint to settle.
- */
-export function makeRevisionedAssetUrlFamily(
- createUrl: (
- target: AssetUrlTarget,
- ) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>,
-) {
- // Outside the nodes: a node is dropped once unmounted, and the next read of
- // its revision must still see the revisions minted since. Never pruned on
- // purpose: pruning would forget the revision and re-mint on the next mount.
- // It holds one short entry per file shown, and goes with the registry.
- const mintedUnder = new WeakMap<AtomRegistry.AtomRegistry, Map<string, string | null>>();
- const family = Atom.family((key: string) => {
- const [environmentId, resource, revision] = decodeRevisionedAssetUrlKey(JSON.parse(key));
- const resourceKey = JSON.stringify([environmentId, resource]);
- const query = createUrl({ environmentId, input: { resource } });
- return Atom.transform(
- query,
- (get) => {
- let minted = mintedUnder.get(get.registry);
- if (minted === undefined) {
- minted = new Map();
- mintedUnder.set(get.registry, minted);
- }
- const firstRead = !minted.has(resourceKey);
- let pending = minted.get(resourceKey) !== revision;
- const current = get.once(query);
- if (pending && (firstRead || isSettled(current))) {
- pending = false;
- minted.set(resourceKey, revision);
- if (isSettled(current)) get.refresh(query);
- }
- get.subscribe(query, (value) => {
- get.setSelf(value);
- if (!pending || !isSettled(value)) return;
- pending = false;
- minted.set(resourceKey, revision);
- get.refresh(query);
- });
- return get.once(query);
- },
- { initialValueTarget: query },
- // No idle TTL: each mount rebuilds the node, so a revision read again after
- // another one is compared against the record instead of a cached node.
- ).pipe(Atom.setIdleTTL(0));
- });
- return (target: AssetUrlTarget & { readonly revision: string | null }) =>
- family(JSON.stringify([target.environmentId, target.input.resource, target.revision]));
-}
-
const revisionedAssetUrl = makeRevisionedAssetUrlFamily(assetEnvironment.createUrl);
/**
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts
index 87354e0d257..81b6992a59d 100644
--- a/apps/web/src/components/ChatView.logic.test.ts
+++ b/apps/web/src/components/ChatView.logic.test.ts
@@ -7,7 +7,6 @@ import {
snapshotComposerSend,
withMessageContext,
deriveAvailableRevertTurnCounts,
- deriveWorkspaceMutationId,
} from "./ChatView.logic";
import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic";
import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
@@ -1259,29 +1258,3 @@ describe("deriveAvailableRevertTurnCounts", () => {
expect(deriveAvailableRevertTurnCounts(null).size).toBe(0);
});
});
-
-describe("deriveWorkspaceMutationId", () => {
- const item = (id: string, type: string, status: string) =>
- ({
- item: { id: TurnItemId.make(id), type, status },
- }) as unknown as OrchestrationV2ProjectedTurnItem;
-
- it("keys on the latest finished command or file change and the latest checkpoint", () => {
- expect(
- deriveWorkspaceMutationId(
- [
- item("edit", "file_change", "completed"),
- item("reply", "assistant_message", "completed"),
- item("command", "command_execution", "running"),
- ],
- "2026-01-01T00:00:00.000Z",
- ),
- ).toBe(JSON.stringify(["edit", "2026-01-01T00:00:00.000Z"]));
- });
-
- it("is null before anything could have touched the workspace", () => {
- expect(deriveWorkspaceMutationId([item("reply", "assistant_message", "completed")], null)).toBe(
- null,
- );
- });
-});
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index 229b72b035e..4e17fdebf7b 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -1618,28 +1618,3 @@ export function deriveAvailableRevertTurnCounts(projection: ThreadStructure | nu
}
return available;
}
-
-/**
- * Changes when the agent may have changed the workspace, so file views refresh. File tools are
- * explicit; completed commands are included because a shell command can mutate the workspace
- * without reporting the paths it touched.
- */
-export function deriveWorkspaceMutationId(
- visibleTurnItems: ReadonlyArray<ThreadStructureRow>,
- latestCheckpointCompletedAt: string | null,
-) {
- let itemId: string | null = null;
- for (let index = visibleTurnItems.length - 1; index >= 0; index -= 1) {
- const item = visibleTurnItems[index]?.item;
- if (!item) continue;
- if (item.type !== "command_execution" && item.type !== "file_change") continue;
- if (item.status === "pending" || item.status === "running" || item.status === "waiting") {
- continue;
- }
- itemId = item.id;
- break;
- }
- return itemId === null && latestCheckpointCompletedAt === null
- ? null
- : JSON.stringify([itemId, latestCheckpointCompletedAt]);
-}
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 6fd54db6bd5..6ec89f8c362 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -9,7 +9,6 @@ import { announcedRun, isDetailBehindShell } from "./chat/threadActivityAnnounce
import {
deriveAvailableRevertTurnCounts,
deriveThreadPendingBackgroundTasks,
- deriveWorkspaceMutationId,
presentThreadShellFromProjection,
} from "./ChatView.logic";
import { usePullRequestDraftThread } from "./chat/usePullRequestDraftThread";
@@ -93,6 +92,7 @@ import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
import { HandoffRow } from "./chat/V2LifecycleRow";
import {
codexFeedbackMessage,
+ deriveWorkspaceMutationId,
isCompleteTurnItemRow,
shouldShowLoadEarlierControl,
type CodexFeedbackSubmission,
@@ -111,6 +111,7 @@ import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
import { useAtomValue } from "@effect/atom-react";
import { type SetStateAction, use, useEffect, useLayoutEffect, useRef, useState } from "react";
import { BackgroundThreadContext } from "./chat/backgroundThread";
+import { WorkspaceMutationIdContext } from "./chat/ChatMarkdownMedia";
import { useLocation, useNavigate } from "@tanstack/react-router";
import { assistantCitationFromLocation } from "../lib/assistantCitationNavigation";
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
@@ -3386,104 +3387,106 @@ export default function ChatView(props: ChatViewProps) {
{...conversationArea}
className="relative flex min-h-0 flex-1 flex-col bg-background"
>
- <ThreadTimeline
- pendingApprovals={pendingApprovals}
- heldApprovalRequestIds={heldApprovalRequestIds}
- respondingRequestIds={respondingRequestIds}
- onRespondToApproval={onRespondToApprovalStable}
- canOperateThread={canOperateThread}
- threadDetailRef={routeThreadDetailRef}
- entriesInput={timelineEntriesInput}
- draftEntries={isServerThread ? null : draftTimelineEntries}
- activeThreadKey={activeThreadKey}
- syncing={threadSyncPhase !== null}
- detailLoading={threadDetailLoading}
- citationRequest={citationRequest}
- citationHistory={citationHistory}
- onCiteAssistantText={citeAssistantTextStable}
- {...(activeProject
- ? { onRunShellCommand: parentPanel?.runShellCommand ?? runShellCommandStable }
- : {})}
- isWorking={isWorking}
- runlessWorkActive={runlessWorkStartedAt !== null}
- isCompacting={isCompacting}
- awaitingUser={
- activePendingApproval !== null
- ? "approval"
- : activePendingUserInput !== null ||
- // A secret request has no runtime request; the shell carries it.
- activeThreadShell?.hasPendingUserInput === true
- ? "input"
- : null
- }
- awaitingRequestId={
- activePendingApproval?.requestId ?? activePendingUserInput?.requestId ?? null
- }
- activeTurnStartedAt={activeWorkStartedAt}
- worktreeSetup={worktreeSetup}
- onCancelWorktreeSetup={onCancelWorktreeSetupStable}
- retryableWorkspacePreparationRunIds={retryableWorkspacePreparationRunIds}
- onRetryWorkspacePreparation={onRetryWorkspacePreparationStable}
- {...(draftId
- ? { onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocallyStable }
- : {})}
- {...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})}
- isPreparingWorktree={isPreparingWorktree}
- footer={timelineFooter}
- listRef={legendListRef}
- runs={serverProjection?.runs ?? []}
- latestRun={activeActivityRun}
- announcedRun={announcedRun(activeActivityRun, serverProjection?.runs ?? [])}
- detailBehindShell={isDetailBehindShell(
- activeLatestRun,
- activeThreadShell?.latestRun ?? null,
- )}
- runningRunId={activeRunningTurnId}
- turnDiffSummaries={turnDiffSummaries}
- activeThreadEnvironmentId={
- displayedThreadRef?.environmentId ?? activeThread.environmentId
- }
- routeThreadKey={displayedTimelineKey}
- displayThreadKey={displayedTimelineKey}
- announceTurnStatus={!isProviderSubagent}
- onOpenToolDiff={parentPanel?.openToolDiff ?? onOpenToolDiffStable}
- // Side chat runs keep no checkpoints to diff, and a fork would promote the side chat.
- {...(embedded
- ? {}
- : { onOpenTurnDiff: onOpenTurnDiffStable, onForkFromRun: onForkFromRunStable })}
- onOpenThread={onOpenRelatedThreadStable}
- parentThreadLink={parentThreadLink}
- workflowOpening={workflowOpening}
- supportsConversationRollback={supportsConversationRollback}
- threadStartCheckpointReady={threadStartCheckpointReady}
- availableRevertTurnCounts={availableRevertTurnCounts}
- onRevertToTurnCount={onRevertTimelineTurnStable}
- onUseArtifactTemplate={insertArtifactTemplateStable}
- onSendAppMessage={sendAppMessageStable}
- isRevertingCheckpoint={isRevertingCheckpoint}
- onImageExpand={onExpandTimelineImageStable}
- onFileOpen={openFileAttachmentStable}
- onFileDownload={downloadFileAttachmentStable}
- markdownCwd={gitCwd ?? undefined}
- resolvedTheme={resolvedTheme}
- timestampFormat={timestampFormat}
- workspaceRoot={activeWorkspaceRoot}
- skills={timelineSkills}
- anchorMessageId={timelineAnchorMessageId}
- onAnchorReady={onTimelineAnchorReadyStable}
- onAnchorSizeChanged={onTimelineAnchorSizeChangedStable}
- contentInsetEndAdjustment={composerTimelineInset}
- liveFollowEnabled={timelineLiveFollowEnabled}
- onIsAtEndChange={onIsAtEndChangeStable}
- onViewportAttach={attachTimelineViewport}
- onFooterGrow={onTimelineFooterGrowStable}
- hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}
- emptyPlaceholderInset={composerReservedHeight}
- topFadeEnabled={!hasTimelineTopBanner}
- {...(threadHistoryControls === undefined
- ? {}
- : { historyControls: threadHistoryControls })}
- />
+ <WorkspaceMutationIdContext value={workspaceMutationId}>
+ <ThreadTimeline
+ pendingApprovals={pendingApprovals}
+ heldApprovalRequestIds={heldApprovalRequestIds}
+ respondingRequestIds={respondingRequestIds}
+ onRespondToApproval={onRespondToApprovalStable}
+ canOperateThread={canOperateThread}
+ threadDetailRef={routeThreadDetailRef}
+ entriesInput={timelineEntriesInput}
+ draftEntries={isServerThread ? null : draftTimelineEntries}
+ activeThreadKey={activeThreadKey}
+ syncing={threadSyncPhase !== null}
+ detailLoading={threadDetailLoading}
+ citationRequest={citationRequest}
+ citationHistory={citationHistory}
+ onCiteAssistantText={citeAssistantTextStable}
+ {...(activeProject
+ ? { onRunShellCommand: parentPanel?.runShellCommand ?? runShellCommandStable }
+ : {})}
+ isWorking={isWorking}
+ runlessWorkActive={runlessWorkStartedAt !== null}
+ isCompacting={isCompacting}
+ awaitingUser={
+ activePendingApproval !== null
+ ? "approval"
+ : activePendingUserInput !== null ||
+ // A secret request has no runtime request; the shell carries it.
+ activeThreadShell?.hasPendingUserInput === true
+ ? "input"
+ : null
+ }
+ awaitingRequestId={
+ activePendingApproval?.requestId ?? activePendingUserInput?.requestId ?? null
+ }
+ activeTurnStartedAt={activeWorkStartedAt}
+ worktreeSetup={worktreeSetup}
+ onCancelWorktreeSetup={onCancelWorktreeSetupStable}
+ retryableWorkspacePreparationRunIds={retryableWorkspacePreparationRunIds}
+ onRetryWorkspacePreparation={onRetryWorkspacePreparationStable}
+ {...(draftId
+ ? { onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocallyStable }
+ : {})}
+ {...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})}
+ isPreparingWorktree={isPreparingWorktree}
+ footer={timelineFooter}
+ listRef={legendListRef}
+ runs={serverProjection?.runs ?? []}
+ latestRun={activeActivityRun}
+ announcedRun={announcedRun(activeActivityRun, serverProjection?.runs ?? [])}
+ detailBehindShell={isDetailBehindShell(
+ activeLatestRun,
+ activeThreadShell?.latestRun ?? null,
+ )}
+ runningRunId={activeRunningTurnId}
+ turnDiffSummaries={turnDiffSummaries}
+ activeThreadEnvironmentId={
+ displayedThreadRef?.environmentId ?? activeThread.environmentId
+ }
+ routeThreadKey={displayedTimelineKey}
+ displayThreadKey={displayedTimelineKey}
+ announceTurnStatus={!isProviderSubagent}
+ onOpenToolDiff={parentPanel?.openToolDiff ?? onOpenToolDiffStable}
+ // Side chat runs keep no checkpoints to diff, and a fork would promote the side chat.
+ {...(embedded
+ ? {}
+ : { onOpenTurnDiff: onOpenTurnDiffStable, onForkFromRun: onForkFromRunStable })}
+ onOpenThread={onOpenRelatedThreadStable}
+ parentThreadLink={parentThreadLink}
+ workflowOpening={workflowOpening}
+ supportsConversationRollback={supportsConversationRollback}
+ threadStartCheckpointReady={threadStartCheckpointReady}
+ availableRevertTurnCounts={availableRevertTurnCounts}
+ onRevertToTurnCount={onRevertTimelineTurnStable}
+ onUseArtifactTemplate={insertArtifactTemplateStable}
+ onSendAppMessage={sendAppMessageStable}
+ isRevertingCheckpoint={isRevertingCheckpoint}
+ onImageExpand={onExpandTimelineImageStable}
+ onFileOpen={openFileAttachmentStable}
+ onFileDownload={downloadFileAttachmentStable}
+ markdownCwd={gitCwd ?? undefined}
+ resolvedTheme={resolvedTheme}
+ timestampFormat={timestampFormat}
+ workspaceRoot={activeWorkspaceRoot}
+ skills={timelineSkills}
+ anchorMessageId={timelineAnchorMessageId}
+ onAnchorReady={onTimelineAnchorReadyStable}
+ onAnchorSizeChanged={onTimelineAnchorSizeChangedStable}
+ contentInsetEndAdjustment={composerTimelineInset}
+ liveFollowEnabled={timelineLiveFollowEnabled}
+ onIsAtEndChange={onIsAtEndChangeStable}
+ onViewportAttach={attachTimelineViewport}
+ onFooterGrow={onTimelineFooterGrowStable}
+ hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}
+ emptyPlaceholderInset={composerReservedHeight}
+ topFadeEnabled={!hasTimelineTopBanner}
+ {...(threadHistoryControls === undefined
+ ? {}
+ : { historyControls: threadHistoryControls })}
+ />
+ </WorkspaceMutationIdContext>
{showScrollToBottom && !isThreadFindActive && (
<ScrollToEndButton
diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.tsx
index f2740de785b..c810890ebf9 100644
--- a/apps/web/src/components/chat/ChatMarkdownMedia.tsx
+++ b/apps/web/src/components/chat/ChatMarkdownMedia.tsx
@@ -5,6 +5,7 @@ import { TriangleAlertIcon } from "lucide-react";
import {
createContext,
memo,
+ use,
useState,
type ComponentProps,
type CSSProperties,
@@ -71,6 +72,8 @@ const CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME = cn(
CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME,
);
export const MarkdownLinkContext = createContext(false);
+/** The thread's workspace mutation id, so a host image the agent rewrites gets a fresh URL. */
+export const WorkspaceMutationIdContext = createContext<string | null | undefined>(undefined);
function expandableMarkdownImageProps(
onImageExpand: ((preview: ExpandedImagePreview) => void) | undefined,
@@ -339,13 +342,15 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
}) {
const resource = props.resource;
+ const threadWorkspaceMutationId = use(WorkspaceMutationIdContext);
+ const workspaceMutationId = props.workspaceMutationId ?? threadWorkspaceMutationId;
const assetUrl = useAssetUrlState(
props.environmentId,
resource,
- props.workspaceMutationId !== undefined &&
+ workspaceMutationId !== undefined &&
props.kind !== "video" &&
(resource._tag === "media-file" || resource._tag === "workspace-file")
- ? props.workspaceMutationId
+ ? workspaceMutationId
: undefined,
);
const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
diff --git a/packages/client-runtime/src/state/assets.test.ts b/packages/client-runtime/src/state/assets.test.ts
index b7a3b3403bd..e2334489302 100644
--- a/packages/client-runtime/src/state/assets.test.ts
+++ b/packages/client-runtime/src/state/assets.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from "@effect/vitest";
-import { type AssetCreateUrlResult, EnvironmentId, WS_METHODS } from "@t3tools/contracts";
+import {
+ type AssetCreateUrlResult,
+ type AssetResource,
+ EnvironmentId,
+ ThreadId,
+ WS_METHODS,
+} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -22,6 +28,7 @@ import {
ASSET_URL_MAX_IN_FLIGHT,
createAssetEnvironmentAtoms,
createProjectFaviconUrlAtomFamily,
+ makeRevisionedAssetUrlFamily,
} from "./assets.ts";
describe("project favicon URL cache", () => {
@@ -229,3 +236,151 @@ describe("asset URL requests", () => {
),
);
});
+
+const revisionedEnvironmentId = EnvironmentId.make("environment-1");
+const revisionedResource: AssetResource = {
+ _tag: "workspace-file",
+ threadId: ThreadId.make("thread-1"),
+ path: "docs/diagram.png",
+};
+
+type MintResult = AsyncResult.AsyncResult<{
+ relativeUrl: string;
+ expiresAt: number;
+ fileRevision?: string;
+}>;
+
+const minted = (n: number, fileRevision?: string): MintResult =>
+ AsyncResult.success({
+ relativeUrl: `/a/${n}`,
+ expiresAt: 60 * 60_000,
+ ...(fileRevision === undefined ? {} : { fileRevision }),
+ });
+
+// A stand-in for the asset URL query: a refresh starts a mint (counted, shown as
+// waiting) and `settle` completes the latest one.
+function setup(initial: MintResult) {
+ let mints = 0;
+ // Node removal runs on the registry's scheduler; `unmount` flushes it so the
+ // next mount of the same revision builds a fresh node.
+ const scheduled: Array<() => void> = [];
+ const registry = AtomRegistry.make({
+ scheduleTask: (task) => {
+ scheduled.push(task);
+ return () => {};
+ },
+ });
+ const server = Atom.make(initial).pipe(Atom.keepAlive);
+ const query = Atom.readable(
+ (get) => get(server),
+ () => {
+ mints += 1;
+ registry.set(server, AsyncResult.waiting(registry.get(server)));
+ },
+ ).pipe(Atom.keepAlive);
+ const revisioned = makeRevisionedAssetUrlFamily(
+ () => query,
+ () => 0,
+ );
+ const atom = (revision: string | null) =>
+ revisioned({
+ environmentId: revisionedEnvironmentId,
+ input: { resource: revisionedResource },
+ revision,
+ });
+ const mount = (revision: string | null) => {
+ const release = registry.mount(atom(revision));
+ return () => {
+ release();
+ for (const task of scheduled.splice(0)) task();
+ };
+ };
+ const settle = (fileRevision?: string) => registry.set(server, minted(mints + 1, fileRevision));
+ const url = (revision: string | null) => {
+ const result = registry.get(atom(revision));
+ return result._tag === "Success" ? result.value.relativeUrl : null;
+ };
+ return { mount, settle, url, mints: () => mints };
+}
+
+describe("makeRevisionedAssetUrlFamily", () => {
+ it("re-mints a settled URL on first read and on each new revision, not on remount", () => {
+ const { mount, settle, mints } = setup(minted(0));
+
+ mount("mutation-1")();
+ expect(mints()).toBe(1);
+ settle();
+
+ mount("mutation-1")();
+ expect(mints()).toBe(1);
+
+ mount("mutation-2")();
+ expect(mints()).toBe(2);
+ });
+
+ it("re-mints when a revert returns to an earlier revision", () => {
+ const { mount, settle, mints } = setup(minted(0));
+
+ mount("mutation-a")();
+ settle();
+ mount("mutation-b")();
+ settle();
+ expect(mints()).toBe(2);
+
+ const reverted = mount("mutation-a");
+ expect(mints()).toBe(3);
+ reverted();
+ });
+
+ it("shares a mint in flight on the first read", () => {
+ const { mount, mints } = setup(AsyncResult.initial(true));
+
+ mount("mutation-1")();
+ expect(mints()).toBe(0);
+ });
+
+ it("re-mints after a mint that was in flight when the revision changed", () => {
+ const { mount, settle, mints } = setup(minted(0));
+
+ const before = mount("mutation-1");
+ settle();
+ const edited = mount("mutation-2");
+ expect(mints()).toBe(2);
+ before();
+
+ const stillMinting = mount("mutation-3");
+ edited();
+ expect(mints()).toBe(2);
+
+ settle();
+ expect(mints()).toBe(3);
+ settle();
+ expect(mints()).toBe(3);
+ stillMinting();
+ });
+
+ it("keeps the URL while the file is unchanged and swaps it once the file changes", () => {
+ const { mount, settle, url } = setup(minted(0, "file-a"));
+
+ const first = mount("mutation-1");
+ settle("file-a");
+ first();
+
+ const unchanged = mount("mutation-2");
+ settle("file-a");
+ expect(url("mutation-2")).toBe("/a/0");
+ unchanged();
+
+ // The query now holds /a/3; a later revision must still keep the URL on screen.
+ const stillUnchanged = mount("mutation-3");
+ expect(url("mutation-3")).toBe("/a/0");
+ settle("file-a");
+ expect(url("mutation-3")).toBe("/a/0");
+ stillUnchanged();
+
+ const edited = mount("mutation-4");
+ settle("file-b");
+ expect(url("mutation-4")).toBe("/a/5");
+ edited();
+ });
+});
diff --git a/packages/client-runtime/src/state/assets.ts b/packages/client-runtime/src/state/assets.ts
index f2e2c0e90bb..56b1b5bcd7d 100644
--- a/packages/client-runtime/src/state/assets.ts
+++ b/packages/client-runtime/src/state/assets.ts
@@ -131,6 +131,113 @@ export function assetUrlStateFromResult(
};
}
+type AssetUrlTarget = {
+ readonly environmentId: EnvironmentId;
+ readonly input: { readonly resource: AssetResource };
+};
+
+const decodeRevisionedAssetUrlKey = Schema.decodeUnknownSync(
+ Schema.Tuple([EnvironmentId, AssetResource, Schema.NullOr(Schema.String)]),
+);
+
+const isSettled = (result: AsyncResult.AsyncResult<unknown, unknown>) =>
+ !AsyncResult.isInitial(result) && !result.waiting;
+
+const KEEP_URL_MIN_LIFE_MS = 5 * 60_000;
+
+/**
+ * A re-mint signs a new URL even when the file is unchanged, and a new URL reloads the image.
+ * Keep the shown URL while the server reports the same file revision and it has time left.
+ */
+function keepUnchangedFile(
+ shown: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
+ next: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
+ now: number,
+) {
+ if (
+ shown._tag !== "Success" ||
+ next._tag !== "Success" ||
+ next.value.fileRevision === undefined ||
+ next.value.fileRevision !== shown.value.fileRevision ||
+ shown.value.expiresAt - now <= KEEP_URL_MIN_LIFE_MS
+ ) {
+ return next;
+ }
+ const kept = AsyncResult.success(shown.value);
+ return next.waiting ? AsyncResult.waiting(kept) : kept;
+}
+
+/**
+ * The URL is minted per resource and shared across revisions, so reading a
+ * different revision (even an earlier one after a revert) re-mints it. An
+ * in-flight mint is shared only on first read; after an edit the server must
+ * re-read the file, so the re-mint waits for that mint to settle.
+ */
+export function makeRevisionedAssetUrlFamily(
+ createUrl: (
+ target: AssetUrlTarget,
+ ) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>,
+ now: () => number = Date.now,
+) {
+ // Outside the nodes: a node is dropped once unmounted, and the next read of
+ // its revision must still see the revisions minted since. Never pruned on
+ // purpose: pruning would forget the revision and re-mint on the next mount.
+ // It holds one short entry per file shown, and goes with the registry.
+ const mintedUnder = new WeakMap<AtomRegistry.AtomRegistry, Map<string, string | null>>();
+ // Also per resource: a new revision builds a new node, which must keep the URL on screen.
+ const shownUnder = new WeakMap<
+ AtomRegistry.AtomRegistry,
+ Map<string, AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>
+ >();
+ const family = Atom.family((key: string) => {
+ const [environmentId, resource, revision] = decodeRevisionedAssetUrlKey(JSON.parse(key));
+ const resourceKey = JSON.stringify([environmentId, resource]);
+ const query = createUrl({ environmentId, input: { resource } });
+ return Atom.transform(
+ query,
+ (get) => {
+ let minted = mintedUnder.get(get.registry);
+ if (minted === undefined) {
+ minted = new Map();
+ mintedUnder.set(get.registry, minted);
+ }
+ const firstRead = !minted.has(resourceKey);
+ let pending = minted.get(resourceKey) !== revision;
+ const current = get.once(query);
+ if (pending && (firstRead || isSettled(current))) {
+ pending = false;
+ minted.set(resourceKey, revision);
+ if (isSettled(current)) get.refresh(query);
+ }
+ let shownByResource = shownUnder.get(get.registry);
+ if (shownByResource === undefined) {
+ shownByResource = new Map();
+ shownUnder.set(get.registry, shownByResource);
+ }
+ const show = (value: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>) => {
+ const previous = shownByResource.get(resourceKey);
+ const shown = previous === undefined ? value : keepUnchangedFile(previous, value, now());
+ shownByResource.set(resourceKey, shown);
+ return shown;
+ };
+ get.subscribe(query, (value) => {
+ get.setSelf(show(value));
+ if (!pending || !isSettled(value)) return;
+ pending = false;
+ minted.set(resourceKey, revision);
+ get.refresh(query);
+ });
+ return show(get.once(query));
+ },
+ { initialValueTarget: query },
+ // No idle TTL: each mount rebuilds the node, so a revision read again after
+ // another one is compared against the record instead of a cached node.
+ ).pipe(Atom.setIdleTTL(0));
+ });
+ return (target: AssetUrlTarget & { readonly revision: string | null }) =>
+ family(JSON.stringify([target.environmentId, target.input.resource, target.revision]));
+}
+
export function createAssetEnvironmentAtoms<R, E>(
runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
localMediaEnvironment?: Atom.Atom<{
diff --git a/packages/client-runtime/src/state/threadDetail.test.ts b/packages/client-runtime/src/state/threadDetail.test.ts
index 3e66202d0bb..cde705bdfb1 100644
--- a/packages/client-runtime/src/state/threadDetail.test.ts
+++ b/packages/client-runtime/src/state/threadDetail.test.ts
@@ -14,7 +14,12 @@ import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";
-import { createEnvironmentThreadDetailAtoms, sameThreadStructure } from "./threadDetail.ts";
+import type { ThreadStructureVisibleTurnItem } from "./models.ts";
+import {
+ createEnvironmentThreadDetailAtoms,
+ deriveWorkspaceMutationId,
+ sameThreadStructure,
+} from "./threadDetail.ts";
import { mergeOlderHistoryIntoProjection } from "./threadHistoryMerge.ts";
import { EMPTY_ENVIRONMENT_THREAD_STATE } from "./threadState.ts";
@@ -349,3 +354,35 @@ it("matches full structure comparisons across streamed, batched, and reordered u
[assistant.id, 1],
]);
});
+
+describe("deriveWorkspaceMutationId", () => {
+ const item = (id: string, type: string, status: string) =>
+ ({
+ item: { id: TurnItemId.make(id), type, status },
+ }) as unknown as ThreadStructureVisibleTurnItem;
+
+ it("keys on the latest finished command or file change and the latest checkpoint", () => {
+ expect(
+ deriveWorkspaceMutationId(
+ [
+ item("edit", "file_change", "completed"),
+ item("reply", "assistant_message", "completed"),
+ item("command", "command_execution", "running"),
+ ],
+ "2026-01-01T00:00:00.000Z",
+ ),
+ ).toBe(JSON.stringify(["edit", "2026-01-01T00:00:00.000Z"]));
+ expect(
+ deriveWorkspaceMutationId(
+ [item("edit", "file_change", "completed"), item("mcp", "dynamic_tool", "completed")],
+ null,
+ ),
+ ).toBe(JSON.stringify(["mcp", null]));
+ });
+
+ it("is null before anything could have touched the workspace", () => {
+ expect(deriveWorkspaceMutationId([item("reply", "assistant_message", "completed")], null)).toBe(
+ null,
+ );
+ });
+});
diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.ts
index eeeda6a2f34..7a17e7326b8 100644
--- a/packages/client-runtime/src/state/threadDetail.ts
+++ b/packages/client-runtime/src/state/threadDetail.ts
@@ -43,6 +43,38 @@ const EMPTY_THREAD_STRUCTURE_TURN_ITEMS: ReadonlyArray<ThreadStructureVisibleTur
Object.freeze([]);
const EMPTY_CHECKPOINT_SUMMARIES: ReadonlyArray<ThreadCheckpointSummary> = Object.freeze([]);
+/**
+ * Changes when the agent may have changed the workspace, so file views and host images refresh.
+ * File tools are explicit; commands, MCP or dynamic tools and subagents are included because
+ * they can mutate the workspace without reporting the paths they touched.
+ */
+export function deriveWorkspaceMutationId(
+ visibleTurnItems: ReadonlyArray<ThreadStructureVisibleTurnItem>,
+ latestCheckpointCompletedAt: string | null,
+) {
+ let itemId: string | null = null;
+ for (let index = visibleTurnItems.length - 1; index >= 0; index -= 1) {
+ const item = visibleTurnItems[index]?.item;
+ if (!item) continue;
+ if (
+ item.type !== "command_execution" &&
+ item.type !== "file_change" &&
+ item.type !== "dynamic_tool" &&
+ item.type !== "subagent"
+ ) {
+ continue;
+ }
+ if (item.status === "pending" || item.status === "running" || item.status === "waiting") {
+ continue;
+ }
+ itemId = item.id;
+ break;
+ }
+ return itemId === null && latestCheckpointCompletedAt === null
+ ? null
+ : JSON.stringify([itemId, latestCheckpointCompletedAt]);
+}
+
type TurnItem = OrchestrationV2ThreadProjection["turnItems"][number];
type VisibleTurnItem = OrchestrationV2ThreadProjection["visibleTurnItems"][number];
type AppThread = OrchestrationV2ThreadProjection["thread"];
@@ -501,8 +533,19 @@ export function createEnvironmentThreadDetailAtoms<E>(
),
);
+ const workspaceMutationIdAtomFamily = Atom.family((key: string) =>
+ Atom.make((get) =>
+ deriveWorkspaceMutationId(
+ get(quietVisibleTurnItemsAtomFamily(key)),
+ get(checkpointSummariesAtomFamily(key)).at(-1)?.completedAt ?? null,
+ ),
+ ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-workspace-mutation-id:${key}`)),
+ );
+
return {
worktreePathAtom: (ref: ScopedThreadRef) => worktreePathAtomFamily(threadKey(ref)),
+ workspaceMutationIdAtom: (ref: ScopedThreadRef) =>
+ workspaceMutationIdAtomFamily(threadKey(ref)),
updatedAtAtom: (ref: ScopedThreadRef) => updatedAtAtomFamily(threadKey(ref)),
lastVisitedAtAtom: (ref: ScopedThreadRef) => lastVisitedAtAtomFamily(threadKey(ref)),
pendingRequestsAtom: (ref: ScopedThreadRef) => pendingRequestsAtomFamily(threadKey(ref)),