The best way to control Claude Code, Codex and more from any computer or phone
fix(web): file links the agent cited from a checkout it cd'd into open that file (#36364)
Julius Marminge committed
Nov 13, 2026 at 14:18 UTC
36f011dfb796b7e477c828a0087e2bb80e5906f9
6 files changed
+270
-19
apps/mobile/src/features/threads/ThreadFeed.tsx
+65
-17
@@ -236,6 +236,8 @@ import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
236
import { readEnvironmentScope, usePreparedConnection } from "../../state/session";
237
import { environmentProjects, projectEnvironment } from "../../state/projects";
238
import {
239
+ agentWorkingDirectories,
240
+ findAgentDirectoryMatch,
241
needsWorkspaceBasenameLookup,
242
pickProjectLinkMatch,
243
pickWorkspaceLinkMatch,
@@ -256,7 +258,11 @@ import { useModelMentions } from "../../state/model-mentions";
258
import { composerDocumentAttachmentRecord } from "../../lib/composerContext";
259
import * as Option from "effect/Option";
260
import { appAtomRegistry } from "../../state/atom-registry";
259
-import { environmentThreadShells, threadEnvironment } from "../../state/threads";
261
+import {
262
+ environmentThreadDetails,
263
+ environmentThreadShells,
264
+ threadEnvironment,
265
+} from "../../state/threads";
266
import { ThreadWorkflowOpening, useWorkflowOpening } from "./thread-workflow-opening";
267
import { useAtomCommand } from "../../state/use-atom-command";
268
import { useV2ItemSupport } from "../../state/v2-item-support";
@@ -1072,10 +1078,17 @@ function ThreadMediaVisibility(props: { readonly children: ReactNode }) {
1078
return <ThreadMediaVisibleContext value={visible}>{props.children}</ThreadMediaVisibleContext>;
1079
}
1080
1081
+/** The reply a link sits in; a file it cites may be where the agent worked before writing it. */
1082
+type MarkdownLinkReply = Pick<OrchestrationV2ProjectedTurnItem, "sourceThreadId" | "sourceItemId">;
1083
+
1084
interface MarkdownLinkHandlers {
1076
- readonly onLinkPress: (href: string) => void;
1085
+ readonly onLinkPress: (href: string, reply?: MarkdownLinkReply) => void;
1086
readonly fileContextMenu: (href: string) => MarkdownFileContextMenu | undefined;
1078
- readonly onFileContextMenuAction: (href: string, actionId: string) => void;
1087
+ readonly onFileContextMenuAction: (
1088
+ href: string,
1089
+ actionId: string,
1090
+ reply?: MarkdownLinkReply,
1091
+ ) => void;
1092
readonly onImagePress?: (href: string) => void;
1093
readonly resolveImageSource?: MarkdownImageSourceResolver;
1094
readonly fileEmbedLabel?: (href: string, standalone: boolean) => string | null;
@@ -1146,6 +1159,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
1159
readonly environmentId: EnvironmentId;
1160
readonly markdownStyles: MarkdownStyleSet;
1161
readonly linkHandlers: MarkdownLinkHandlers;
1162
+ readonly reply?: MarkdownLinkReply | undefined;
1163
readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
1164
readonly renderImage: MarkdownImageRenderer;
1165
readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
@@ -1155,6 +1169,9 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
1169
const threadIcons = useThreadChipIcons(props.environmentId, liveMarkdown);
1170
const linkHandlers: MarkdownLinkHandlers = {
1171
...props.linkHandlers,
1172
+ onLinkPress: (href) => props.linkHandlers.onLinkPress(href, props.reply),
1173
+ onFileContextMenuAction: (href, actionId) =>
1174
+ props.linkHandlers.onFileContextMenuAction(href, actionId, props.reply),
1175
linkCustomization: (href) =>
1176
withChipIcon(props.linkHandlers.linkCustomization?.(href), threadIcons.get(href)),
1177
};
@@ -2289,6 +2306,7 @@ function renderFeedEntry(
2306
environmentId={props.environmentId}
2307
markdownStyles={styles}
2308
linkHandlers={props.markdownLinkHandlers}
2309
+ reply={message.projectedItem}
2310
onUseArtifactTemplate={props.onUseArtifactTemplate}
2311
renderImage={props.renderMarkdownImage}
2312
skills={props.skills}
@@ -2878,6 +2896,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2896
linkPath: string,
2897
path: string,
2898
signal: AbortSignal,
2899
+ reply: MarkdownLinkReply | undefined,
2900
): Promise<string> => {
2901
const relativePath = resolveWorkspaceRelativeFilePath(props.workspaceRoot, path);
2902
if (
@@ -2909,6 +2928,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2928
root,
2929
entries: result._tag === "Success" ? result.value.entries : [],
2930
}));
2931
+ const metadataOf = (target: string) =>
2932
+ executeAtomQuery(
2933
+ appAtomRegistry,
2934
+ projectEnvironment.fileMetadata({
2935
+ environmentId: props.environmentId,
2936
+ input: { path: target },
2937
+ }),
2938
+ queryOptions,
2939
+ );
2940
const lookup = async () => {
2941
const own = await searchRoot(workspaceRoot);
2942
let match = pickWorkspaceLinkMatch(relativePath, workspaceRoot, own.entries);
@@ -2933,15 +2961,35 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2961
? null
2962
: pickProjectLinkMatch(relativePath, await Promise.all(otherRoots.map(searchRoot)));
2963
}
2964
+ if (match === null && reply !== undefined && !signal.aborted) {
2965
+ // No project has the file, so it opens where the agent last worked, as written.
2966
+ const agentRoots = agentWorkingDirectories(
2967
+ appAtomRegistry.get(
2968
+ environmentThreadDetails.quietThreadAtom(
2969
+ scopeThreadRef(props.environmentId, props.threadId),
2970
+ ),
2971
+ )?.projection.visibleTurnItems ?? [],
2972
+ reply,
2973
+ ).filter((root) => root !== workspaceRoot);
2974
+ const agentPaths = agentRoots.map((root) => resolveWorkspaceFilePath(root, relativePath));
2975
+ if (agentPaths.length === 0) return relativePath;
2976
+ const [original, ...found] = await Promise.all(
2977
+ [originalPath, ...agentPaths].map(metadataOf),
2978
+ );
2979
+ if (original?._tag !== "Success" || original.value !== null) return relativePath;
2980
+ const index = found.findIndex(
2981
+ (result) => result._tag === "Success" && result.value?.kind === "file",
2982
+ );
2983
+ const literal = agentPaths[index];
2984
+ if (literal !== undefined || !needsWorkspaceBasenameLookup(relativePath)) {
2985
+ return literal ?? relativePath;
2986
+ }
2987
+ return (
2988
+ (await findAgentDirectoryMatch(relativePath, agentRoots, searchRoot)) ?? relativePath
2989
+ );
2990
+ }
2991
if (!match || match === relativePath || signal.aborted) return relativePath;
2937
- const metadata = await executeAtomQuery(
2938
- appAtomRegistry,
2939
- projectEnvironment.fileMetadata({
2940
- environmentId: props.environmentId,
2941
- input: { path: originalPath },
2942
- }),
2943
- queryOptions,
2944
- );
2992
+ const metadata = await metadataOf(originalPath);
2993
// Another project's file never replaces a thread-local file the search missed.
2994
return metadata._tag === "Success" &&
2995
(needsWorkspaceBasenameLookup(relativePath) && !otherProject
@@ -2952,7 +3000,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3000
};
3001
return lookup().catch(() => relativePath);
3002
};
2955
- const onMarkdownLinkPress = (href: string, imageEmbed = false) => {
3003
+ const onMarkdownLinkPress = (href: string, imageEmbed = false, reply?: MarkdownLinkReply) => {
3004
markdownLinkRequest.current?.abort();
3005
const request = new AbortController();
3006
markdownLinkRequest.current = request;
@@ -3019,7 +3067,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3067
if (presentation.kind === "file") {
3068
const path = resolveFileLinkPath(props.workspaceRoot, presentation.path);
3069
if (path === null) return;
3022
- void findFileLinkTarget(presentation.path, path, request.signal).then((target) => {
3070
+ void findFileLinkTarget(presentation.path, path, request.signal, reply).then((target) => {
3071
if (request.signal.aborted) return;
3072
void Haptics.selectionAsync();
3073
navigation.navigate("ThreadFile", {
@@ -3058,7 +3106,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3106
},
3107
standalone,
3108
),
3061
- onLinkPress: onMarkdownLinkPress,
3109
+ onLinkPress: (href, reply) => onMarkdownLinkPress(href, false, reply),
3110
linkCustomization: enrichedThreadLinkCustomization,
3111
onImagePress: (href) => onMarkdownLinkPress(href, true),
3112
resolveImageSource,
@@ -3091,7 +3139,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3139
const target = resolveFileChipTarget(href, props.workspaceRoot);
3140
return target ? fileChipMenu(target) : undefined;
3141
},
3094
- onFileContextMenuAction: (href, actionId) => {
3142
+ onFileContextMenuAction: (href, actionId, reply) => {
3143
const skill = enrichedSkillReference(href, props.skills);
3144
if (skill) {
3145
const instructionsPath = enrichedSkillInstructionsPath(skill);
@@ -3119,7 +3167,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3167
markdownLinkRequest.current?.abort();
3168
const request = new AbortController();
3169
markdownLinkRequest.current = request;
3122
- void findFileLinkTarget(presentation.path, path, request.signal).then((found) => {
3170
+ void findFileLinkTarget(presentation.path, path, request.signal, reply).then((found) => {
3171
if (request.signal.aborted) return;
3172
const fullPath =
3173
props.workspaceRoot && !isAbsolutePath(found)
@@ -3144,7 +3192,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3192
return;
3193
}
3194
case "open-file":
3147
- onMarkdownLinkPress(href);
3195
+ onMarkdownLinkPress(href, false, reply);
3196
return;
3197
case "save":
3198
shareFileChip(target);
apps/web/src/components/ChatMarkdown.tsx
+19
-2
@@ -173,6 +173,7 @@ import { projectEnvironment } from "../state/projects";
173
import { filesystemEnvironment } from "../state/filesystem";
174
import {
175
claimWorkspaceBasenameLookup,
176
+ findAgentDirectoryMatch,
177
needsWorkspaceBasenameLookup,
178
pickProjectLinkMatch,
179
pickWorkspaceLinkMatch,
@@ -234,6 +235,8 @@ interface ChatMarkdownProps {
235
inline?: boolean;
236
text: string;
237
cwd: string | undefined;
238
+ /** Folders the agent worked in before writing `text`, the latest first; read when a link opens. */
239
+ agentDirectories?: (() => ReadonlyArray<string>) | undefined;
240
threadRef?: ScopedThreadRef | undefined;
241
pullRequestPanelRef?: ScopedThreadRef | undefined;
242
environmentId?: EnvironmentId | undefined;
@@ -502,6 +505,7 @@ function useChatMarkdownState({
505
text,
506
inline = false,
507
cwd,
508
+ agentDirectories,
509
threadRef,
510
pullRequestPanelRef,
511
environmentId: explicitEnvironmentId,
@@ -818,7 +822,8 @@ function useChatMarkdownState({
822
? [project.workspaceRoot]
823
: [],
824
);
821
- if (otherRoots.length === 0) return null;
825
+ const agentRoots = (agentDirectories?.() ?? []).filter((root) => root !== cwd);
826
+ if (otherRoots.length === 0 && agentRoots.length === 0) return null;
827
// Another project's file never replaces a thread-local file the search missed.
828
if (needsWorkspaceBasenameLookup(workspaceRelativePath)) {
829
const metadata = await getFilesystemMetadata({
@@ -827,10 +832,22 @@ function useChatMarkdownState({
832
});
833
if (metadata._tag !== "Success" || metadata.value.entries[0] !== null) return null;
834
}
830
- return pickProjectLinkMatch(
835
+ const projectMatch = pickProjectLinkMatch(
836
workspaceRelativePath,
837
await Promise.all(otherRoots.map(searchRoot)),
838
);
839
+ if (projectMatch !== null || agentRoots.length === 0) return projectMatch;
840
+ // No project has the file, so it opens where the agent last worked, as written.
841
+ const agentPaths = agentRoots.map((root) =>
842
+ resolveWorkspaceFilePath(workspaceRelativePath, root),
843
+ );
844
+ const metadata = await getFilesystemMetadata({ environmentId, input: { paths: agentPaths } });
845
+ if (metadata._tag !== "Success") return null;
846
+ const literal = agentPaths.find((_, index) => metadata.value.entries[index]?.kind === "file");
847
+ if (literal !== undefined || !needsWorkspaceBasenameLookup(workspaceRelativePath)) {
848
+ return literal ?? null;
849
+ }
850
+ return findAgentDirectoryMatch(workspaceRelativePath, agentRoots, searchRoot);
851
};
852
const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => {
853
if (!threadRef) return;
apps/web/src/components/chat/TimelineAssistantRows.tsx
+7
@@ -1,6 +1,7 @@
1
import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
2
import { type RunId, type TurnItemId } from "@t3tools/contracts";
3
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
4
+import { agentWorkingDirectories } from "@t3tools/client-runtime/workspace-basename-lookup";
5
import { memo, use, useState } from "react";
6
import { type ChatMessage, type TurnDiffSummary } from "../../types";
7
import ChatMarkdown from "../ChatMarkdown";
@@ -27,6 +28,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
28
import { cn } from "~/lib/utils";
29
import { useUiStateStore } from "~/uiStateStore";
30
import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
31
+import { readThreadTurnItems } from "../../state/entities";
32
import { useV2ItemSupport } from "../../state/v2ItemSupport";
33
import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext";
34
import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts";
@@ -58,6 +60,11 @@ export function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind
60
text={messageText}
61
renderInsights
62
cwd={ctx.markdownCwd}
63
+ agentDirectories={() =>
64
+ ctx.threadRef && row.projectedItem
65
+ ? agentWorkingDirectories(readThreadTurnItems(ctx.threadRef), row.projectedItem)
66
+ : []
67
+ }
68
threadRef={ctx.threadRef ?? undefined}
69
isStreaming={Boolean(row.message.streaming)}
70
lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}
apps/web/src/state/entities.ts
+8
@@ -328,6 +328,14 @@ export function waitForProjectRemoval(ref: ScopedProjectRef, timeoutMs = 5_000):
328
});
329
}
330
331
+/** The thread's loaded timeline, for a handler that reads it once instead of subscribing. */
332
+export function readThreadTurnItems(ref: ScopedThreadRef) {
333
+ return (
334
+ appAtomRegistry.get(environmentThreadDetails.quietThreadAtom(ref))?.projection
335
+ .visibleTurnItems ?? []
336
+ );
337
+}
338
+
339
export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null {
340
return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
341
}
apps/web/src/workspaceBasenameLookup.test.ts
+71
@@ -1,7 +1,9 @@
1
import { describe, expect, it } from "vite-plus/test";
2
3
import {
4
+ agentWorkingDirectories,
5
claimWorkspaceBasenameLookup,
6
+ findAgentDirectoryMatch,
7
pickProjectLinkMatch,
8
pickWorkspaceBasenameMatch,
9
pickWorkspaceLinkMatch,
@@ -113,6 +115,75 @@ describe("chat file links into another project", () => {
115
});
116
});
117
118
+// regression: #35337 a path the agent cited inside a checkout no project is rooted at
119
+describe("agentWorkingDirectories", () => {
120
+ const directories = (...commands: ReadonlyArray<string>) =>
121
+ agentWorkingDirectories(
122
+ [...commands, "the reply", "cd /work/later"].map((input, index) => ({
123
+ sourceThreadId: "thread",
124
+ sourceItemId: `item-${index}`,
125
+ item: { type: "command_execution", input },
126
+ })),
127
+ { sourceThreadId: "thread", sourceItemId: `item-${commands.length}` },
128
+ );
129
+
130
+ it("lists the folders commands above the reply changed into, the latest first", () => {
131
+ expect(
132
+ directories(
133
+ "cd /work/repo-c && cd /work/repo-b && git diff",
134
+ "git status",
135
+ `/bin/zsh -lc "cd '/work/my repo'; ls"`,
136
+ "cd -P /work/repo-a # not this; cd /work/commented",
137
+ "cd /work/repo-c\npwd",
138
+ ),
139
+ ).toEqual(["/work/repo-c", "/work/repo-a", "/work/my repo", "/work/repo-b"]);
140
+ });
141
+
142
+ it("skips operands only the shell can resolve and words that are not the command", () => {
143
+ expect(
144
+ directories(
145
+ "cd docs && cd ../other && cd ~/repo && cd $ROOT/x && cd /work/*/src",
146
+ "abcd /work/a; echo cd /work/b; git -C /work/c status; cd /work/d",
147
+ `echo "cd /work/g"; echo 'x; cd /work/h' && grep -c "cd /work/i" notes`,
148
+ "echo bash -c 'cd /work/j'; cd -",
149
+ "cat <<EOF > notes\ncd /work/k\nEOF",
150
+ "cd /work/e\\ f && cd `pwd`/x",
151
+ ),
152
+ ).toEqual(["/work/d"]);
153
+ });
154
+});
155
+
156
+// regression: #35337 a bare file name the agent cited from a subfolder of an unregistered checkout
157
+describe("findAgentDirectoryMatch", () => {
158
+ const search = (found: Record<string, ReadonlyArray<string>>) => (root: string) =>
159
+ Promise.resolve({
160
+ root,
161
+ entries: (found[root] ?? []).map((path) => ({ path, kind: "file" as const })),
162
+ });
163
+
164
+ it("opens the one file of that name in the latest folder the agent worked in", async () => {
165
+ expect(
166
+ await findAgentDirectoryMatch(
167
+ "config.test.yaml",
168
+ ["/work/repo-b/server", "/work/repo-b", "/work/repo-c"],
169
+ search({
170
+ "/work/repo-b/server": ["config.test.yaml"],
171
+ "/work/repo-b": ["server/config.test.yaml"],
172
+ "/work/repo-c": ["config.test.yaml"],
173
+ }),
174
+ ),
175
+ ).toBe("/work/repo-b/server/config.test.yaml");
176
+ });
177
+
178
+ it("passes over a folder without the file, and opens nothing when none has it", async () => {
179
+ const found = search({ "/work/repo-c": ["etc/config.test.yaml"] });
180
+ expect(
181
+ await findAgentDirectoryMatch("config.test.yaml", ["/work/repo-b", "/work/repo-c"], found),
182
+ ).toBe("/work/repo-c/etc/config.test.yaml");
183
+ expect(await findAgentDirectoryMatch("config.test.yaml", ["/work/repo-b"], found)).toBeNull();
184
+ });
185
+});
186
+
187
describe("claimWorkspaceBasenameLookup", () => {
188
it("keeps only the newest claim, whatever order the lookups settle in", () => {
189
const first = claimWorkspaceBasenameLookup();
packages/client-runtime/src/workspaceBasenameLookup.ts
+100
@@ -1,3 +1,4 @@
1
+import { FILESYSTEM_METADATA_BATCH_LIMIT } from "@t3tools/contracts";
2
import {
3
isAbsolutePath,
4
isWindowsAbsolutePath,
@@ -135,3 +136,102 @@ export function pickProjectLinkMatch(
136
});
137
return matches.length === 1 ? (matches[0] ?? null) : null;
138
}
139
+
140
+const AGENT_DIRECTORY_SEARCH_LIMIT = 4;
141
+
142
+/**
143
+ * The file a bare name cites in the latest folder the agent worked in that has one of that name.
144
+ * Folders are searched one at a time: the latest usually has it, and each search walks a tree.
145
+ */
146
+export async function findAgentDirectoryMatch(
147
+ relativePath: string,
148
+ directories: ReadonlyArray<string>,
149
+ searchRoot: (root: string) => Promise<{
150
+ readonly root: string;
151
+ readonly entries: ReadonlyArray<WorkspaceEntryCandidate>;
152
+ }>,
153
+): Promise<string | null> {
154
+ for (const directory of directories.slice(0, AGENT_DIRECTORY_SEARCH_LIMIT)) {
155
+ const match = pickProjectLinkMatch(relativePath, [await searchRoot(directory)]);
156
+ if (match !== null) return match;
157
+ }
158
+ return null;
159
+}
160
+
161
+// A quoted string or a comment is one token, so `cd` inside either is not read as a command.
162
+const SHELL_TOKEN = /(?<![^\s;&|()])#[^\n]*|"[^"]*"|'[^']*'|[;&|()\n]|[ \t]+|[^\s;&|()"']+/g;
163
+const SHELL_NAME = /(?:^|\/)(?:ba|z|da)?sh$/;
164
+const CD_OPTION = /^-[LPe@]*$|^--$/;
165
+
166
+/** The operands of the `cd` commands in `script`, in order, through `sh -c "<script>"`. */
167
+function cdOperands(script: string): Array<string> {
168
+ const operands: Array<string> = [];
169
+ let words: Array<string> = [];
170
+ let wordOpen = false;
171
+ const endCommand = () => {
172
+ const [name = "", ...rest] = words;
173
+ if (name === "cd") {
174
+ const operand = rest.find((word) => !CD_OPTION.test(word));
175
+ if (operand !== undefined) operands.push(operand);
176
+ } else if (SHELL_NAME.test(name)) {
177
+ const inner = rest[rest.findIndex((word) => /^-[a-z]*c$/.test(word)) + 1];
178
+ if (inner !== undefined && /^(["']).*\1$/s.test(inner)) {
179
+ operands.push(...cdOperands(inner.slice(1, -1)));
180
+ }
181
+ }
182
+ words = [];
183
+ wordOpen = false;
184
+ };
185
+ for (const [token] of script.matchAll(SHELL_TOKEN)) {
186
+ // A here-document's body is data, and where it ends is the shell's to say.
187
+ if (!/^["'#]/.test(token) && token.includes("<<")) break;
188
+ if (/^[;&|()\n]/.test(token)) endCommand();
189
+ else if (/^[ \t]/.test(token) || (!wordOpen && token.startsWith("#"))) wordOpen = false;
190
+ else if (wordOpen) words[words.length - 1] += token;
191
+ else {
192
+ words.push(token);
193
+ wordOpen = true;
194
+ }
195
+ }
196
+ endCommand();
197
+ return operands;
198
+}
199
+
200
+function literalDirectory(operand: string): string | null {
201
+ const path = /^["']/.test(operand) ? operand.slice(1, -1) : operand;
202
+ // The shell would expand these, and only it knows to what.
203
+ if (!isAbsolutePath(path) || /[$`*?[\]{}"']/.test(path)) return null;
204
+ return path.includes("\\") && !isWindowsAbsolutePath(path) ? null : path;
205
+}
206
+
207
+interface TimelineItemSource {
208
+ readonly sourceThreadId: string;
209
+ readonly sourceItemId: string;
210
+}
211
+
212
+/**
213
+ * The folders the commands above `reply` in a thread's timeline changed into, the latest first.
214
+ * A reply cites paths relative to where the agent worked, which no project has to be rooted at.
215
+ * Rows below the reply, a fork's own commands under an inherited one included, came after it.
216
+ */
217
+export function agentWorkingDirectories(
218
+ items: ReadonlyArray<
219
+ TimelineItemSource & { readonly item: { readonly type: string; readonly input?: unknown } }
220
+ >,
221
+ reply: TimelineItemSource,
222
+): ReadonlyArray<string> {
223
+ const directories = new Set<string>();
224
+ const replyIndex = items.findIndex(
225
+ (row) => row.sourceThreadId === reply.sourceThreadId && row.sourceItemId === reply.sourceItemId,
226
+ );
227
+ for (let index = replyIndex - 1; index >= 0; index--) {
228
+ const item = items[index]?.item;
229
+ if (item?.type !== "command_execution" || typeof item.input !== "string") continue;
230
+ for (const operand of cdOperands(item.input).reverse()) {
231
+ const directory = literalDirectory(operand);
232
+ if (directory !== null) directories.add(directory);
233
+ if (directories.size === FILESYSTEM_METADATA_BATCH_LIMIT) return [...directories];
234
+ }
235
+ }
236
+ return [...directories];
237
+}