Skip to content

Commit 36f011d

Browse files
fix(web): file links the agent cited from a checkout it cd'd into open that file (#36364)
1 parent 48cdefe commit 36f011d

6 files changed

Lines changed: 270 additions & 19 deletions

File tree

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 65 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,8 @@ import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
236236
import { readEnvironmentScope, usePreparedConnection } from "../../state/session";
237237
import { environmentProjects, projectEnvironment } from "../../state/projects";
238238
import {
239+
agentWorkingDirectories,
240+
findAgentDirectoryMatch,
239241
needsWorkspaceBasenameLookup,
240242
pickProjectLinkMatch,
241243
pickWorkspaceLinkMatch,
@@ -256,7 +258,11 @@ import { useModelMentions } from "../../state/model-mentions";
256258
import { composerDocumentAttachmentRecord } from "../../lib/composerContext";
257259
import * as Option from "effect/Option";
258260
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";
260266
import { ThreadWorkflowOpening, useWorkflowOpening } from "./thread-workflow-opening";
261267
import { useAtomCommand } from "../../state/use-atom-command";
262268
import { useV2ItemSupport } from "../../state/v2-item-support";
@@ -1072,10 +1078,17 @@ function ThreadMediaVisibility(props: { readonly children: ReactNode }) {
10721078
return <ThreadMediaVisibleContext value={visible}>{props.children}</ThreadMediaVisibleContext>;
10731079
}
10741080

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+
10751084
interface MarkdownLinkHandlers {
1076-
readonly onLinkPress: (href: string) => void;
1085+
readonly onLinkPress: (href: string, reply?: MarkdownLinkReply) => void;
10771086
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;
10791092
readonly onImagePress?: (href: string) => void;
10801093
readonly resolveImageSource?: MarkdownImageSourceResolver;
10811094
readonly fileEmbedLabel?: (href: string, standalone: boolean) => string | null;
@@ -1146,6 +1159,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
11461159
readonly environmentId: EnvironmentId;
11471160
readonly markdownStyles: MarkdownStyleSet;
11481161
readonly linkHandlers: MarkdownLinkHandlers;
1162+
readonly reply?: MarkdownLinkReply | undefined;
11491163
readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;
11501164
readonly renderImage: MarkdownImageRenderer;
11511165
readonly skills?: ReadonlyArray<SelectableMarkdownSkill> | undefined;
@@ -1155,6 +1169,9 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
11551169
const threadIcons = useThreadChipIcons(props.environmentId, liveMarkdown);
11561170
const linkHandlers: MarkdownLinkHandlers = {
11571171
...props.linkHandlers,
1172+
onLinkPress: (href) => props.linkHandlers.onLinkPress(href, props.reply),
1173+
onFileContextMenuAction: (href, actionId) =>
1174+
props.linkHandlers.onFileContextMenuAction(href, actionId, props.reply),
11581175
linkCustomization: (href) =>
11591176
withChipIcon(props.linkHandlers.linkCustomization?.(href), threadIcons.get(href)),
11601177
};
@@ -2289,6 +2306,7 @@ function renderFeedEntry(
22892306
environmentId={props.environmentId}
22902307
markdownStyles={styles}
22912308
linkHandlers={props.markdownLinkHandlers}
2309+
reply={message.projectedItem}
22922310
onUseArtifactTemplate={props.onUseArtifactTemplate}
22932311
renderImage={props.renderMarkdownImage}
22942312
skills={props.skills}
@@ -2878,6 +2896,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
28782896
linkPath: string,
28792897
path: string,
28802898
signal: AbortSignal,
2899+
reply: MarkdownLinkReply | undefined,
28812900
): Promise<string> => {
28822901
const relativePath = resolveWorkspaceRelativeFilePath(props.workspaceRoot, path);
28832902
if (
@@ -2909,6 +2928,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
29092928
root,
29102929
entries: result._tag === "Success" ? result.value.entries : [],
29112930
}));
2931+
const metadataOf = (target: string) =>
2932+
executeAtomQuery(
2933+
appAtomRegistry,
2934+
projectEnvironment.fileMetadata({
2935+
environmentId: props.environmentId,
2936+
input: { path: target },
2937+
}),
2938+
queryOptions,
2939+
);
29122940
const lookup = async () => {
29132941
const own = await searchRoot(workspaceRoot);
29142942
let match = pickWorkspaceLinkMatch(relativePath, workspaceRoot, own.entries);
@@ -2933,15 +2961,35 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
29332961
? null
29342962
: pickProjectLinkMatch(relativePath, await Promise.all(otherRoots.map(searchRoot)));
29352963
}
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+
}
29362991
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);
29452993
// Another project's file never replaces a thread-local file the search missed.
29462994
return metadata._tag === "Success" &&
29472995
(needsWorkspaceBasenameLookup(relativePath) && !otherProject
@@ -2952,7 +3000,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
29523000
};
29533001
return lookup().catch(() => relativePath);
29543002
};
2955-
const onMarkdownLinkPress = (href: string, imageEmbed = false) => {
3003+
const onMarkdownLinkPress = (href: string, imageEmbed = false, reply?: MarkdownLinkReply) => {
29563004
markdownLinkRequest.current?.abort();
29573005
const request = new AbortController();
29583006
markdownLinkRequest.current = request;
@@ -3019,7 +3067,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
30193067
if (presentation.kind === "file") {
30203068
const path = resolveFileLinkPath(props.workspaceRoot, presentation.path);
30213069
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) => {
30233071
if (request.signal.aborted) return;
30243072
void Haptics.selectionAsync();
30253073
navigation.navigate("ThreadFile", {
@@ -3058,7 +3106,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
30583106
},
30593107
standalone,
30603108
),
3061-
onLinkPress: onMarkdownLinkPress,
3109+
onLinkPress: (href, reply) => onMarkdownLinkPress(href, false, reply),
30623110
linkCustomization: enrichedThreadLinkCustomization,
30633111
onImagePress: (href) => onMarkdownLinkPress(href, true),
30643112
resolveImageSource,
@@ -3091,7 +3139,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
30913139
const target = resolveFileChipTarget(href, props.workspaceRoot);
30923140
return target ? fileChipMenu(target) : undefined;
30933141
},
3094-
onFileContextMenuAction: (href, actionId) => {
3142+
onFileContextMenuAction: (href, actionId, reply) => {
30953143
const skill = enrichedSkillReference(href, props.skills);
30963144
if (skill) {
30973145
const instructionsPath = enrichedSkillInstructionsPath(skill);
@@ -3119,7 +3167,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
31193167
markdownLinkRequest.current?.abort();
31203168
const request = new AbortController();
31213169
markdownLinkRequest.current = request;
3122-
void findFileLinkTarget(presentation.path, path, request.signal).then((found) => {
3170+
void findFileLinkTarget(presentation.path, path, request.signal, reply).then((found) => {
31233171
if (request.signal.aborted) return;
31243172
const fullPath =
31253173
props.workspaceRoot && !isAbsolutePath(found)
@@ -3144,7 +3192,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
31443192
return;
31453193
}
31463194
case "open-file":
3147-
onMarkdownLinkPress(href);
3195+
onMarkdownLinkPress(href, false, reply);
31483196
return;
31493197
case "save":
31503198
shareFileChip(target);

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ import { projectEnvironment } from "../state/projects";
173173
import { filesystemEnvironment } from "../state/filesystem";
174174
import {
175175
claimWorkspaceBasenameLookup,
176+
findAgentDirectoryMatch,
176177
needsWorkspaceBasenameLookup,
177178
pickProjectLinkMatch,
178179
pickWorkspaceLinkMatch,
@@ -234,6 +235,8 @@ interface ChatMarkdownProps {
234235
inline?: boolean;
235236
text: string;
236237
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;
237240
threadRef?: ScopedThreadRef | undefined;
238241
pullRequestPanelRef?: ScopedThreadRef | undefined;
239242
environmentId?: EnvironmentId | undefined;
@@ -502,6 +505,7 @@ function useChatMarkdownState({
502505
text,
503506
inline = false,
504507
cwd,
508+
agentDirectories,
505509
threadRef,
506510
pullRequestPanelRef,
507511
environmentId: explicitEnvironmentId,
@@ -818,7 +822,8 @@ function useChatMarkdownState({
818822
? [project.workspaceRoot]
819823
: [],
820824
);
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;
822827
// Another project's file never replaces a thread-local file the search missed.
823828
if (needsWorkspaceBasenameLookup(workspaceRelativePath)) {
824829
const metadata = await getFilesystemMetadata({
@@ -827,10 +832,22 @@ function useChatMarkdownState({
827832
});
828833
if (metadata._tag !== "Success" || metadata.value.entries[0] !== null) return null;
829834
}
830-
return pickProjectLinkMatch(
835+
const projectMatch = pickProjectLinkMatch(
831836
workspaceRelativePath,
832837
await Promise.all(otherRoots.map(searchRoot)),
833838
);
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);
834851
};
835852
const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => {
836853
if (!threadRef) return;

‎apps/web/src/components/chat/TimelineAssistantRows.tsx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
22
import { type RunId, type TurnItemId } from "@t3tools/contracts";
33
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
4+
import { agentWorkingDirectories } from "@t3tools/client-runtime/workspace-basename-lookup";
45
import { memo, use, useState } from "react";
56
import { type ChatMessage, type TurnDiffSummary } from "../../types";
67
import ChatMarkdown from "../ChatMarkdown";
@@ -27,6 +28,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
2728
import { cn } from "~/lib/utils";
2829
import { useUiStateStore } from "~/uiStateStore";
2930
import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
31+
import { readThreadTurnItems } from "../../state/entities";
3032
import { useV2ItemSupport } from "../../state/v2ItemSupport";
3133
import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext";
3234
import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts";
@@ -58,6 +60,11 @@ export function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind
5860
text={messageText}
5961
renderInsights
6062
cwd={ctx.markdownCwd}
63+
agentDirectories={() =>
64+
ctx.threadRef && row.projectedItem
65+
? agentWorkingDirectories(readThreadTurnItems(ctx.threadRef), row.projectedItem)
66+
: []
67+
}
6168
threadRef={ctx.threadRef ?? undefined}
6269
isStreaming={Boolean(row.message.streaming)}
6370
lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}

‎apps/web/src/state/entities.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,14 @@ export function waitForProjectRemoval(ref: ScopedProjectRef, timeoutMs = 5_000):
328328
});
329329
}
330330

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+
331339
export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null {
332340
return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
333341
}

‎apps/web/src/workspaceBasenameLookup.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { describe, expect, it } from "vite-plus/test";
22

33
import {
4+
agentWorkingDirectories,
45
claimWorkspaceBasenameLookup,
6+
findAgentDirectoryMatch,
57
pickProjectLinkMatch,
68
pickWorkspaceBasenameMatch,
79
pickWorkspaceLinkMatch,
@@ -113,6 +115,75 @@ describe("chat file links into another project", () => {
113115
});
114116
});
115117

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+
116187
describe("claimWorkspaceBasenameLookup", () => {
117188
it("keeps only the newest claim, whatever order the lookups settle in", () => {
118189
const first = claimWorkspaceBasenameLookup();

0 commit comments

Comments
 (0)