Skip to content

Commit 7d5eec3

Browse files
fix(chat): fetch cited families only when absent from shell
1 parent cda776b commit 7d5eec3

4 files changed

Lines changed: 158 additions & 27 deletions

File tree

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

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -210,19 +210,17 @@ export function useSideChats(ref: ScopedThreadRef) {
210210

211211
export function useLiveThreadLinkLabels(markdown: string, environmentId: EnvironmentId): string {
212212
const refs = hasThreadLinks(markdown) ? threadLinkRefs(markdown, environmentId) : [];
213+
const refsKey = JSON.stringify(refs.map(threadKey));
213214
const titles = useAtomValue(
214-
refs.length === 0
215-
? EMPTY_THREAD_LINK_TITLES_ATOM
216-
: threadLinkTitlesAtom(JSON.stringify(refs.map(threadKey))),
215+
refs.length === 0 ? EMPTY_THREAD_LINK_TITLES_ATOM : threadLinkTitlesAtom(refsKey),
217216
);
218-
// Shells leave out idle subagent children and older settled threads, so a cited thread the
219-
// shell lacks is read with its family until it lands; only a settled empty read proves it gone.
220-
const refsKey = JSON.stringify(refs.map(threadKey));
221-
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps cited families mounted until the links change; releasing on title arrival removes that title again
217+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps cited rows mounted for the message's lifetime, independently of the family data it loads
222218
useEffect(() => {
223-
const releases = (JSON.parse(refsKey) as ReadonlyArray<string>).map((key) => {
219+
const releases = decodeThreadKeys(JSON.parse(refsKey)).map((key) => {
224220
const ref = scopeThreadRef(...decodeThreadKey(JSON.parse(key)));
225-
return threadFamilies.mount(appAtomRegistry, ref.environmentId, ref.threadId);
221+
return threadFamilies.mount(appAtomRegistry, ref.environmentId, ref.threadId, {
222+
onlyWhenMissing: true,
223+
});
226224
});
227225
return () => {
228226
for (const release of releases) release();

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

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,24 +23,21 @@ export function MarkdownThreadLink(props: {
2323
readonly label: string | null;
2424
}) {
2525
const environmentId = props.link.environmentId ?? props.environmentId;
26-
const { threadId } = props.link;
27-
const decodedId = percentDecodedThreadLinkId(threadId);
28-
const written = useThreadShell(scopeThreadRef(environmentId, threadId));
26+
const decodedId = percentDecodedThreadLinkId(props.link.threadId);
27+
const written = useThreadShell(scopeThreadRef(environmentId, props.link.threadId));
2928
const decoded = useThreadShell(
3029
written === null && decodedId !== null ? scopeThreadRef(environmentId, decodedId) : null,
3130
);
3231
const local = written ?? decoded;
33-
// An idle child's shell row can come from this very read. Releasing on title arrival removes it.
34-
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- retains the cited families while the link is displayed
32+
const threadId = props.link.threadId;
33+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps cited rows mounted for the link's lifetime, independently of the family data it loads
3534
useEffect(() => {
36-
const releaseWritten = threadFamilies.mount(appAtomRegistry, environmentId, threadId);
37-
const releaseDecoded =
38-
decodedId === null
39-
? undefined
40-
: threadFamilies.mount(appAtomRegistry, environmentId, decodedId);
35+
const ids = decodedId === null ? [threadId] : [threadId, decodedId];
36+
const releases = ids.map((id) =>
37+
threadFamilies.mount(appAtomRegistry, environmentId, id, { onlyWhenMissing: true }),
38+
);
4139
return () => {
42-
releaseWritten();
43-
releaseDecoded?.();
40+
for (const release of releases) release();
4441
};
4542
}, [environmentId, threadId, decodedId]);
4643
const guess = local === null && props.link.environmentId === null;

‎packages/client-runtime/src/state/threadFamilies.test.ts‎

Lines changed: 90 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,12 @@ describe("createThreadFamilyAtoms", () => {
125125
yield* Queue.unbounded<
126126
Effect.Effect<OrchestrationV2ThreadFamily, OrchestrationV2GetShellSnapshotError>
127127
>();
128+
const requests: ThreadId[] = [];
128129
const client = {
129-
[ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: () => Effect.flatten(Queue.take(replies)),
130+
[ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: ({ threadId }: { threadId: ThreadId }) =>
131+
Effect.sync(() => requests.push(threadId)).pipe(
132+
Effect.andThen(Effect.flatten(Queue.take(replies))),
133+
),
130134
} as unknown as WsRpcProtocolClient;
131135
const session = {
132136
client,
@@ -231,6 +235,91 @@ describe("createThreadFamilyAtoms", () => {
231235
yield* settle;
232236
expect(threadFamilyRead(registry.get(family))).toBe("settled");
233237
expect(mergedIds()).toEqual(["parent", "idle-child"]);
238+
239+
const visible = row("visible-citation");
240+
const omitted = row("omitted-citation");
241+
registry.set(
242+
shellState,
243+
AsyncResult.success({
244+
...shellAt(2),
245+
snapshot: Option.some({ ...shellSnapshot, threads: [parent, visible] }),
246+
}),
247+
);
248+
const releaseVisible = families.mount(registry, TARGET.environmentId, visible.id, {
249+
onlyWhenMissing: true,
250+
});
251+
const releaseOmitted = families.mount(registry, TARGET.environmentId, omitted.id, {
252+
onlyWhenMissing: true,
253+
});
254+
yield* Queue.offerAll(replies, [
255+
Effect.succeed({ snapshotSequence: 5, threads: [omitted] }),
256+
Effect.succeed({ snapshotSequence: 5, threads: [visible] }),
257+
]);
258+
yield* AtomRegistry.getResult(
259+
registry,
260+
families.familyAtom(TARGET.environmentId, omitted.id),
261+
{ suspendOnWaiting: true },
262+
);
263+
expect(requests).toEqual([parent.id, parent.id, parent.id, omitted.id]);
264+
expect(mergedIds()).toEqual([
265+
"parent",
266+
"visible-citation",
267+
"idle-child",
268+
"omitted-citation",
269+
]);
270+
271+
registry.set(shellState, AsyncResult.success(shellAt(2)));
272+
yield* AtomRegistry.getResult(
273+
registry,
274+
families.familyAtom(TARGET.environmentId, visible.id),
275+
{ suspendOnWaiting: true },
276+
);
277+
expect(requests).toEqual([parent.id, parent.id, parent.id, omitted.id, visible.id]);
278+
expect(mergedIds()).toEqual([
279+
"parent",
280+
"idle-child",
281+
"visible-citation",
282+
"omitted-citation",
283+
]);
284+
releaseVisible();
285+
releaseOmitted();
286+
expect(mergedIds()).toEqual(["parent", "idle-child"]);
287+
288+
const unavailable = row("cached-failure");
289+
const unavailableFamily = families.familyAtom(TARGET.environmentId, unavailable.id);
290+
const releaseFailed = families.mount(registry, TARGET.environmentId, unavailable.id);
291+
yield* Queue.offer(
292+
replies,
293+
Effect.fail(new OrchestrationV2GetShellSnapshotError({ message: "read failed" })),
294+
);
295+
yield* AtomRegistry.getResult(registry, unavailableFamily, {
296+
suspendOnWaiting: true,
297+
}).pipe(Effect.ignore);
298+
expect(threadFamilyRead(registry.get(unavailableFamily))).toBe("failed");
299+
releaseFailed();
300+
registry.set(
301+
shellState,
302+
AsyncResult.success({
303+
...shellAt(2),
304+
snapshot: Option.some({ ...shellSnapshot, threads: [parent, unavailable] }),
305+
}),
306+
);
307+
const releaseRetry = families.mount(registry, TARGET.environmentId, unavailable.id, {
308+
onlyWhenMissing: true,
309+
});
310+
expect(requests.filter((id) => id === unavailable.id)).toHaveLength(1);
311+
registry.set(shellState, AsyncResult.success(shellAt(2)));
312+
yield* settle;
313+
expect(threadFamilyRead(registry.get(unavailableFamily))).toBe("pending");
314+
yield* Queue.offer(
315+
replies,
316+
Effect.succeed({ snapshotSequence: 5, threads: [unavailable] }),
317+
);
318+
yield* AtomRegistry.getResult(registry, unavailableFamily, { suspendOnWaiting: true });
319+
expect(requests.filter((id) => id === unavailable.id)).toHaveLength(2);
320+
expect(mergedIds()).toEqual(["parent", "idle-child", "cached-failure"]);
321+
releaseRetry();
322+
expect(mergedIds()).toEqual(["parent", "idle-child"]);
234323
}),
235324
),
236325
);

‎packages/client-runtime/src/state/threadFamilies.ts‎

Lines changed: 52 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,26 @@ export function createThreadFamilyAtoms<R, ER, E>(
151151
}).pipe(Atom.withLabel(`environment-thread-family-rows:${key}`)),
152152
);
153153

154+
const shellThreadIdsAtom = Atom.family((environmentId: EnvironmentId) => {
155+
let previous: ReadonlyArray<OrchestrationV2ThreadShell> | undefined;
156+
let ids: ReadonlySet<ThreadId> = new Set();
157+
return Atom.make((get) => {
158+
const state = shellStateValue(get(shellStateAtom(environmentId)));
159+
const threads = state === null ? undefined : Option.getOrNull(state.snapshot)?.threads;
160+
if (threads !== previous) {
161+
previous = threads;
162+
ids = new Set(threads?.map(({ id }) => id));
163+
}
164+
return ids;
165+
}).pipe(Atom.withLabel(`environment-shell-thread-ids:${environmentId}`));
166+
});
167+
const missingFamilyRowsAtom = Atom.family((key: string) => {
168+
const [environmentId, threadId] = JSON.parse(key) as [EnvironmentId, ThreadId];
169+
return Atom.make((get) =>
170+
get(shellThreadIdsAtom(environmentId)).has(threadId) ? EMPTY_READS : get(familyRowsAtom(key)),
171+
).pipe(Atom.withLabel(`environment-missing-thread-family-rows:${key}`));
172+
});
173+
154174
/**
155175
* Merges `rows` behind the shell rows until the returned release runs. Reads read under `key`
156176
* share one entry; each read's `snapshotSequence` decides which removals drop its rows.
@@ -186,14 +206,41 @@ export function createThreadFamilyAtoms<R, ER, E>(
186206
registry: AtomRegistry.AtomRegistry,
187207
environmentId: EnvironmentId,
188208
threadId: ThreadId,
209+
options: { readonly onlyWhenMissing?: boolean } = {},
189210
): (() => void) => {
190211
const key = familyKey(environmentId, threadId);
191-
const release = mountRows(registry, environmentId, `family:${key}`, familyRowsAtom(key));
192-
// Mounting again after a failure retries instead of keeping the failure until reconnect.
193-
if (threadFamilyRead(registry.get(familyAtom(key))) === "failed") {
194-
refresh(registry, environmentId, threadId);
212+
const onlyWhenMissing = options.onlyWhenMissing === true;
213+
const release = mountRows(
214+
registry,
215+
environmentId,
216+
`${onlyWhenMissing ? "missing-family" : "family"}:${key}`,
217+
onlyWhenMissing ? missingFamilyRowsAtom(key) : familyRowsAtom(key),
218+
);
219+
const retryFailed = () => {
220+
if (threadFamilyRead(registry.get(familyAtom(key))) === "failed") {
221+
refresh(registry, environmentId, threadId);
222+
}
223+
};
224+
if (!onlyWhenMissing) {
225+
retryFailed();
226+
return release;
195227
}
196-
return release;
228+
let wasMissing = false;
229+
// A cached failure must retry when the shell first omits a still-mounted citation.
230+
const unsubscribe = registry.subscribe(
231+
shellThreadIdsAtom(environmentId),
232+
(ids) => {
233+
const missing = !ids.has(threadId);
234+
const becameMissing = missing && !wasMissing;
235+
wasMissing = missing;
236+
if (becameMissing) retryFailed();
237+
},
238+
{ immediate: true },
239+
);
240+
return () => {
241+
unsubscribe();
242+
release();
243+
};
197244
};
198245

199246
const snapshotAtom = Atom.family((environmentId: EnvironmentId) => {

0 commit comments

Comments
 (0)