Skip to content

Commit 4fc510a

Browse files
committed
fix(web): retain thread link lookups and resolve literal IDs first
Keep missing-thread families mounted after their rows appear in the shell. Confirm that a literal thread ID is absent before trying decoded or remote matches.
1 parent 94ca7ce commit 4fc510a

4 files changed

Lines changed: 242 additions & 12 deletions

File tree

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

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { Link } from "@tanstack/react-router";
44
import { MessagesSquareIcon } from "lucide-react";
55

66
import { useProject, useThreadShell } from "~/state/entities";
7-
import { useThreadFamily } from "~/state/threads";
7+
import { useThreadFamilyIfMissing } from "~/state/threads";
88
import { ContextChip, ContextChipLabel } from "./ContextChip";
99
import { ProjectFavicon } from "./ProjectFavicon";
1010
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -16,8 +16,7 @@ export function ThreadContextChip(props: {
1616
}) {
1717
const { environmentId, threadId } = props.record;
1818
const shell = useThreadShell({ environmentId, threadId });
19-
// Shells leave older settled threads out; the family read brings this one in.
20-
useThreadFamily(environmentId, shell === null ? threadId : null);
19+
useThreadFamilyIfMissing({ environmentId, threadId }, shell === null);
2120
const project = useProject(shell ? scopeProjectRef(environmentId, shell.projectId) : null);
2221
const title = shell?.title?.trim() || props.record.title;
2322
return (
Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
import { useAtomValue } from "@effect/atom-react";
2+
import {
3+
EnvironmentId,
4+
ThreadId,
5+
type OrchestrationV2ThreadFamily,
6+
type OrchestrationV2ThreadShell,
7+
type ScopedThreadRef,
8+
} from "@t3tools/contracts";
9+
import { AsyncResult } from "effect/reactivity";
10+
import { describe, expect, it, vi } from "vite-plus/test";
11+
12+
import { act, render } from "../../../test/render";
13+
import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
14+
import { threadFamilies } from "../../state/threads";
15+
import { ThreadContextChip } from "../ThreadContextChip";
16+
import { MarkdownThreadLink } from "./MarkdownThreadLink";
17+
18+
const mocks = await vi.hoisted(async () => {
19+
const { Atom, AsyncResult } = await import("effect/reactivity");
20+
return {
21+
shells: Atom.make<ReadonlyMap<string, OrchestrationV2ThreadShell>>(new Map()).pipe(
22+
Atom.keepAlive,
23+
),
24+
reads: Atom.family((_key: string) =>
25+
Atom.make<AsyncResult.AsyncResult<OrchestrationV2ThreadFamily, never>>(
26+
AsyncResult.initial(),
27+
).pipe(Atom.keepAlive),
28+
),
29+
};
30+
});
31+
32+
const key = (ref: ScopedThreadRef) => JSON.stringify([ref.environmentId, ref.threadId]);
33+
34+
vi.mock("../../state/entities", () => ({
35+
useProject: () => null,
36+
useThreadRefs: () => [],
37+
useThreadShell: (ref: ScopedThreadRef | null) => {
38+
const rows = useAtomValue(mocks.shells);
39+
if (ref === null) return null;
40+
const row = rows.get(key(ref));
41+
return row ? { ...row, environmentId: ref.environmentId } : null;
42+
},
43+
}));
44+
45+
const ENV = EnvironmentId.make("thread-links-test");
46+
const ref = (id: string, environmentId = ENV): ScopedThreadRef => ({
47+
environmentId,
48+
threadId: ThreadId.make(id),
49+
});
50+
const row = (id: string, title: string) =>
51+
({ id: ThreadId.make(id), title }) as OrchestrationV2ThreadShell;
52+
53+
function setup(shells: ReadonlyMap<string, OrchestrationV2ThreadShell> = new Map()) {
54+
appAtomRegistry.set(mocks.shells, shells);
55+
const mounted = new Map<string, OrchestrationV2ThreadFamily>();
56+
const counts = new Map<string, number>();
57+
const requested = new Set<string>();
58+
const queries = vi
59+
.spyOn(threadFamilies, "familyAtom")
60+
.mockImplementation((environmentId, threadId) => {
61+
const id = key({ environmentId, threadId });
62+
if (!requested.has(id)) {
63+
requested.add(id);
64+
appAtomRegistry.set(mocks.reads(id), AsyncResult.initial());
65+
}
66+
return mocks.reads(id);
67+
});
68+
const mounts = vi
69+
.spyOn(threadFamilies, "mount")
70+
.mockImplementation((registry, environmentId, threadId) => {
71+
const id = key({ environmentId, threadId });
72+
const query = threadFamilies.familyAtom(environmentId, threadId);
73+
counts.set(id, (counts.get(id) ?? 0) + 1);
74+
const publish = () => {
75+
const rows = new Map(shells);
76+
for (const [familyKey, family] of mounted) {
77+
const [environmentId] = JSON.parse(familyKey) as [EnvironmentId, ThreadId];
78+
for (const thread of family.threads) {
79+
rows.set(key({ environmentId, threadId: thread.id }), thread);
80+
}
81+
}
82+
registry.set(mocks.shells, rows);
83+
};
84+
const unsubscribe = registry.subscribe(
85+
query,
86+
(result) => {
87+
if (AsyncResult.isSuccess(result)) mounted.set(id, result.value);
88+
else mounted.delete(id);
89+
publish();
90+
},
91+
{ immediate: true },
92+
);
93+
return () => {
94+
unsubscribe();
95+
const count = (counts.get(id) ?? 1) - 1;
96+
counts.set(id, count);
97+
if (count === 0) mounted.delete(id);
98+
publish();
99+
};
100+
});
101+
return {
102+
requested,
103+
resolve: (target: ScopedThreadRef, threads: ReadonlyArray<OrchestrationV2ThreadShell>) =>
104+
act(() =>
105+
appAtomRegistry.set(
106+
mocks.reads(key(target)),
107+
AsyncResult.success({ snapshotSequence: 1, threads }),
108+
),
109+
),
110+
[Symbol.dispose]() {
111+
mounts.mockRestore();
112+
queries.mockRestore();
113+
},
114+
};
115+
}
116+
117+
function view(target: ScopedThreadRef, kind: "context" | "markdown" = "markdown") {
118+
return (
119+
<AppAtomRegistryProvider>
120+
{kind === "context" ? (
121+
<ThreadContextChip record={{ ...target, title: "Saved title" }} />
122+
) : (
123+
<MarkdownThreadLink environmentId={ENV} link={target} label={null} />
124+
)}
125+
</AppAtomRegistryProvider>
126+
);
127+
}
128+
129+
describe("thread link family lookups", () => {
130+
it.each(["context", "markdown"] as const)(
131+
"retains a settled thread until its %s chip unmounts",
132+
async (kind) => {
133+
using fixture = setup();
134+
const target = ref("older-settled");
135+
await using screen = await render(view(target, kind));
136+
await fixture.resolve(target, [row(target.threadId, "Older settled thread")]);
137+
await expect
138+
.element(screen.getByRole("link", { name: "Thread, Older settled thread" }))
139+
.toBeInTheDocument();
140+
await screen.rerender(view(target, kind));
141+
await expect
142+
.element(screen.getByRole("link", { name: "Thread, Older settled thread" }))
143+
.toBeInTheDocument();
144+
expect(appAtomRegistry.get(mocks.shells).has(key(target))).toBe(true);
145+
await screen.unmount();
146+
expect(appAtomRegistry.get(mocks.shells).size).toBe(0);
147+
},
148+
);
149+
150+
it("prefers a literal percent escape to the decoded thread", async () => {
151+
const literal = ref("provider%3A1");
152+
const decoded = ref("provider:1");
153+
using fixture = setup(new Map([[key(decoded), row(decoded.threadId, "Decoded thread")]]));
154+
await using screen = await render(view(literal));
155+
await expect
156+
.element(screen.getByRole("link", { name: "Thread, Decoded thread" }))
157+
.not.toBeInTheDocument();
158+
expect(fixture.requested.has(key(literal))).toBe(true);
159+
expect(fixture.requested.has(key(decoded))).toBe(false);
160+
await fixture.resolve(literal, [row(literal.threadId, "Literal thread")]);
161+
await expect
162+
.element(screen.getByRole("link", { name: "Thread, Literal thread" }))
163+
.toBeInTheDocument();
164+
expect(fixture.requested.has(key(decoded))).toBe(false);
165+
});
166+
167+
it("tries the decoded ID only after a successful empty literal lookup", async () => {
168+
using fixture = setup();
169+
const literal = ref("provider%3A1");
170+
const decoded = ref("provider:1");
171+
await using screen = await render(view(literal));
172+
expect(fixture.requested.has(key(decoded))).toBe(false);
173+
await fixture.resolve(literal, []);
174+
expect(fixture.requested.has(key(decoded))).toBe(true);
175+
await fixture.resolve(decoded, [row(decoded.threadId, "Decoded thread")]);
176+
await expect
177+
.element(screen.getByRole("link", { name: "Thread, Decoded thread" }))
178+
.toBeInTheDocument();
179+
});
180+
181+
it("releases the previous family when the target environment changes", async () => {
182+
using fixture = setup();
183+
const first = ref("same-id");
184+
const second = ref("same-id", EnvironmentId.make("second-environment"));
185+
await using screen = await render(view(first));
186+
await fixture.resolve(first, [row(first.threadId, "First environment")]);
187+
await screen.rerender(view(second));
188+
await fixture.resolve(second, [row(second.threadId, "Second environment")]);
189+
await expect
190+
.element(screen.getByRole("link", { name: "Thread, Second environment" }))
191+
.toBeInTheDocument();
192+
expect(appAtomRegistry.get(mocks.shells).has(key(first))).toBe(false);
193+
});
194+
});

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

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
22
import type { EnvironmentId } from "@t3tools/contracts";
3+
import { AsyncResult } from "effect/reactivity";
34
import {
45
formatThreadLink,
56
guessThreadLinkRef,
@@ -9,7 +10,7 @@ import {
910
} from "@t3tools/shared/threadLinks";
1011

1112
import { useThreadRefs, useThreadShell } from "../../state/entities";
12-
import { useThreadFamily } from "../../state/threads";
13+
import { useThreadFamilyIfMissing } from "../../state/threads";
1314
import { UnresolvedChip } from "../contextChipParts";
1415
import { ThreadContextChip } from "../ThreadContextChip";
1516

@@ -21,14 +22,30 @@ export function MarkdownThreadLink(props: {
2122
}) {
2223
const environmentId = props.link.environmentId ?? props.environmentId;
2324
const decodedId = percentDecodedThreadLinkId(props.link.threadId);
24-
const written = useThreadShell(scopeThreadRef(environmentId, props.link.threadId));
25-
const decoded = useThreadShell(
26-
written === null && decodedId !== null ? scopeThreadRef(environmentId, decodedId) : null,
25+
const writtenRef = scopeThreadRef(environmentId, props.link.threadId);
26+
const written = useThreadShell(writtenRef);
27+
const writtenFamily = useThreadFamilyIfMissing(writtenRef, written === null);
28+
const writtenMissing =
29+
written === null &&
30+
AsyncResult.isSuccess(writtenFamily) &&
31+
!writtenFamily.waiting &&
32+
!writtenFamily.value.threads.some((thread) => thread.id === props.link.threadId);
33+
const decodedRef =
34+
writtenMissing && decodedId !== null ? scopeThreadRef(environmentId, decodedId) : null;
35+
const decoded = useThreadShell(decodedRef);
36+
const decodedFamily = useThreadFamilyIfMissing(
37+
decodedRef,
38+
decodedRef !== null && decoded === null,
2739
);
40+
const decodedMissing =
41+
decodedId === null ||
42+
(decoded === null &&
43+
AsyncResult.isSuccess(decodedFamily) &&
44+
!decodedFamily.waiting &&
45+
!decodedFamily.value.threads.some((thread) => thread.id === decodedId));
2846
const local = written ?? decoded;
29-
// Shells leave older settled threads out; the family read brings the linked one in.
30-
useThreadFamily(environmentId, local === null ? (decodedId ?? props.link.threadId) : null);
31-
const guess = local === null && props.link.environmentId === null;
47+
const guess =
48+
local === null && writtenMissing && decodedMissing && props.link.environmentId === null;
3249
const refs = useThreadRefs(guess);
3350
const remote = useThreadShell(guess ? guessThreadLinkRef(props.link, refs) : null);
3451
const thread = local ?? remote;

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

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,16 @@ import {
1111
createThreadEnvironmentAtoms,
1212
createThreadFamilyAtoms,
1313
} from "@t3tools/client-runtime/state/threads";
14-
import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
14+
import type {
15+
EnvironmentId,
16+
OrchestrationV2ThreadFamily,
17+
OrchestrationV2ThreadShell,
18+
ScopedThreadRef,
19+
ThreadId,
20+
} from "@t3tools/contracts";
1521
import * as Option from "effect/Option";
1622
import { AsyncResult, Atom } from "effect/reactivity";
17-
import { useEffect } from "react";
23+
import { useEffect, useState } from "react";
1824

1925
import { environmentCatalog } from "../connection/catalog";
2026
import { connectionAtomRuntime } from "../connection/runtime";
@@ -54,6 +60,20 @@ export function useThreadFamily(
5460
}, [environmentId, rootThreadId]);
5561
}
5662

63+
const EMPTY_FAMILY_ATOM = Atom.make(AsyncResult.initial<OrchestrationV2ThreadFamily, never>());
64+
65+
export function useThreadFamilyIfMissing(ref: ScopedThreadRef | null, missing: boolean) {
66+
const [lookup, setLookup] = useState(missing ? ref : null);
67+
const active =
68+
ref !== null && lookup?.environmentId === ref.environmentId && lookup.threadId === ref.threadId;
69+
// Family rows make their own shell visible, so retain the lookup until its target changes.
70+
if (ref !== null && missing && !active) setLookup(ref);
71+
useThreadFamily(active ? ref.environmentId : null, active ? ref.threadId : null);
72+
return useAtomValue(
73+
active ? threadFamilies.familyAtom(ref.environmentId, ref.threadId) : EMPTY_FAMILY_ATOM,
74+
);
75+
}
76+
5777
const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(
5878
Atom.withLabel("web-environment-thread:empty"),
5979
);

0 commit comments

Comments
 (0)