Skip to content

Commit 24e141c

Browse files
refactor(web): rich content, work rows and thread find attach to elements
Rich chat content, work rows and the chat header measure and mount from ref callbacks, thread find state moves into a per-thread store, and the timeline gets its citation procedure, ready-timeline memory and MCP app display-mode handling outside effects. Effect categories removed: - widget mounts, observers and measurement moved to ref callbacks (Mermaid, tables, media players, HTML and MCP frames, header breadcrumb, work log and command output) - elapsed-time clocks moved to the shared second tick - asset URL minting moved to a long-lived atom family - thread find window events and the bar's focus effect replaced by a per-thread store and a keyed input - thread overlay cleanup moved from host unmount effects to a route listener - ready-timeline memory recorded by the entries producer instead of a layout effect - MCP app fullscreen listeners replaced by native popover dismissal; tool info read from a query atom - Escape and copy timers moved to dialog handlers and the shared clipboard hook Bugs fixed: - Escape in the expanded media dialog closed it over a nested popup. - HEIC images with no source never reported their load error. - Copying code or tables now falls back when the clipboard API is missing. - MCP apps switched to fullscreen styling in browsers without popover support. - The chat header breadcrumb re-measures after an interface font change. Kept effects: - MCP app host mirror, context and tool-call pushes: long-lived host. - Find highlight registry and navigation scroll listener: external registry, and the listener must see the rendered entries. - Find reveal retry: positioning depends on the list as well. - Citation source observer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 913263c commit 24e141c

45 files changed

Lines changed: 2301 additions & 1024 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import { EnvironmentId, type AssetResource } from "@t3tools/contracts";
2+
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
3+
import { describe, expect, it } from "vite-plus/test";
4+
5+
import { makeLongLivedAssetUrlFamily } from "./longLivedAssetUrls";
6+
7+
const environmentId = EnvironmentId.make("environment-1");
8+
const resource: AssetResource = {
9+
_tag: "attachment",
10+
attachmentId: "attachment-1",
11+
fileName: "page.html",
12+
mimeType: "text/html",
13+
disposition: "inline",
14+
} as AssetResource;
15+
16+
type MintResult = AsyncResult.AsyncResult<{ relativeUrl: string; expiresAt: number }>;
17+
18+
const url = (relativeUrl: string, expiresAt: number): MintResult =>
19+
AsyncResult.success({ relativeUrl, expiresAt });
20+
21+
function setup(initial: MintResult) {
22+
let mints = 0;
23+
const registry = AtomRegistry.make({ scheduleTask: () => () => {} });
24+
const server = Atom.make(initial).pipe(Atom.keepAlive);
25+
const query = Atom.readable(
26+
(get) => get(server),
27+
() => {
28+
mints += 1;
29+
registry.set(server, AsyncResult.waiting(registry.get(server)));
30+
},
31+
).pipe(Atom.keepAlive);
32+
const family = makeLongLivedAssetUrlFamily(() => query, { minLifeMs: 100, now: () => 1_000 });
33+
const atom = family({ environmentId, input: { resource } });
34+
registry.mount(atom);
35+
const relativeUrl = () => {
36+
const value = registry.get(atom);
37+
return value._tag === "Success" && !value.waiting ? value.value.relativeUrl : null;
38+
};
39+
return {
40+
relativeUrl,
41+
mints: () => mints,
42+
serve: (result: MintResult) => registry.set(server, result),
43+
};
44+
}
45+
46+
describe("makeLongLivedAssetUrlFamily", () => {
47+
it("reuses a cached URL with enough life left", () => {
48+
const { relativeUrl, mints } = setup(url("/cached", 2_000));
49+
expect(relativeUrl()).toBe("/cached");
50+
expect(mints()).toBe(0);
51+
});
52+
53+
it("mints a URL near expiry and hides it until the new one arrives", () => {
54+
const { relativeUrl, mints, serve } = setup(url("/stale", 1_050));
55+
expect(mints()).toBe(1);
56+
expect(relativeUrl()).toBeNull();
57+
58+
serve(url("/fresh", 5_000));
59+
expect(relativeUrl()).toBe("/fresh");
60+
});
61+
62+
it("mints at most once when the clock disagrees with the server", () => {
63+
const { relativeUrl, mints, serve } = setup(url("/stale", 1_050));
64+
serve(url("/still-short", 1_050));
65+
expect(relativeUrl()).toBe("/still-short");
66+
expect(mints()).toBe(1);
67+
});
68+
69+
it("waits for a URL still loading", () => {
70+
const { relativeUrl, mints, serve } = setup(AsyncResult.initial(true));
71+
expect(relativeUrl()).toBeNull();
72+
serve(url("/loaded", 5_000));
73+
expect(relativeUrl()).toBe("/loaded");
74+
expect(mints()).toBe(0);
75+
});
76+
});
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import { useAtomValue } from "@effect/atom-react";
2+
import {
3+
type AssetUrlState,
4+
assetUrlStateFromResult,
5+
blockedAssetUrlState,
6+
EMPTY_ASSET_URL_ATOM,
7+
} from "@t3tools/client-runtime/state/assets";
8+
import { AssetResource, type AssetCreateUrlResult, EnvironmentId } from "@t3tools/contracts";
9+
import * as Schema from "effect/Schema";
10+
import { AsyncResult, Atom } from "effect/reactivity";
11+
12+
import { assetEnvironment } from "~/state/assets";
13+
import { useFilesystemReadAccess } from "~/state/filesystem";
14+
import { usePreparedConnection } from "~/state/session";
15+
16+
type AssetUrlTarget = {
17+
readonly environmentId: EnvironmentId;
18+
readonly input: { readonly resource: AssetResource };
19+
};
20+
21+
const decodeAssetUrlKey = Schema.decodeUnknownSync(Schema.Tuple([EnvironmentId, AssetResource]));
22+
23+
/**
24+
* Asset URLs for documents that cannot report a failed load, such as frames. A
25+
* cached URL with `minLifeMs` left is reused; one closer to expiry is re-minted.
26+
* A node mints at most once, so a skewed client clock cannot mint on every update.
27+
*/
28+
export function makeLongLivedAssetUrlFamily(
29+
createUrl: (
30+
target: AssetUrlTarget,
31+
) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>,
32+
options: { readonly minLifeMs: number; readonly now?: () => number },
33+
) {
34+
const now = options.now ?? Date.now;
35+
const family = Atom.family((key: string) => {
36+
const [environmentId, resource] = decodeAssetUrlKey(JSON.parse(key));
37+
const query = createUrl({ environmentId, input: { resource } });
38+
return Atom.transform(
39+
query,
40+
(get) => {
41+
let minting = false;
42+
const settle = (
43+
value: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
44+
): AsyncResult.AsyncResult<AssetCreateUrlResult, unknown> => {
45+
if (value._tag !== "Success") return value;
46+
// The URL being replaced must not be handed out while its successor mints.
47+
if (value.waiting) return minting ? AsyncResult.initial(true) : value;
48+
if (minting || value.value.expiresAt - now() > options.minLifeMs) return value;
49+
minting = true;
50+
get.refresh(query);
51+
return AsyncResult.initial(true);
52+
};
53+
get.subscribe(query, (value) => get.setSelf(settle(value)));
54+
return settle(get.once(query));
55+
},
56+
{ initialValueTarget: query },
57+
// Each mount gets its own node, so a later mount may mint again.
58+
).pipe(Atom.setIdleTTL(0));
59+
});
60+
return (target: AssetUrlTarget) =>
61+
family(JSON.stringify([target.environmentId, target.input.resource]));
62+
}
63+
64+
const longLivedAssetUrl = makeLongLivedAssetUrlFamily(assetEnvironment.createUrl, {
65+
minLifeMs: 5 * 60_000,
66+
});
67+
68+
/** Pass a null environment once the URL is adopted, so later mints do not re-render. */
69+
export function useLongLivedAssetUrl(
70+
environmentId: EnvironmentId | null,
71+
resource: AssetResource,
72+
): AssetUrlState {
73+
const blocked = blockedAssetUrlState(resource, useFilesystemReadAccess(environmentId));
74+
const preparedConnection = usePreparedConnection(environmentId);
75+
const result = useAtomValue(
76+
blocked !== null || environmentId === null
77+
? EMPTY_ASSET_URL_ATOM
78+
: longLivedAssetUrl({ environmentId, input: { resource } }),
79+
);
80+
if (blocked !== null) return blocked;
81+
return assetUrlStateFromResult(
82+
result,
83+
preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null,
84+
);
85+
}

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

Lines changed: 29 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,6 @@ import React, {
7474
type ClipboardEvent as ReactClipboardEvent,
7575
use,
7676
memo,
77-
useLayoutEffect,
7877
useRef,
7978
useState,
8079
type ReactNode,
@@ -453,36 +452,17 @@ function useChatMarkdownState({
453452
const resolvedTheme = useRenderedAppearance();
454453
const markdownRef = useRef<HTMLElement>(null);
455454
const mediaRequestId = useRef(0);
456-
const mediaScopeKey = [
457-
threadRef?.environmentId,
458-
threadRef?.threadId,
459-
explicitEnvironmentId,
460-
cwd,
461-
imageBaseDir,
462-
].join("\u0000");
463-
// Hide requests from an old scope even if they resolve before effect cleanup.
464-
const [localMedia, setLocalMedia] = useState<{
465-
scope: string;
466-
preview: ExpandedImagePreview;
467-
} | null>(null);
468-
const localMediaPreview = localMedia?.scope === mediaScopeKey ? localMedia.preview : null;
469-
const closeLocalMediaPreview = () => setLocalMedia(null);
470-
const expandMedia =
471-
onImageExpand ??
472-
((preview: ExpandedImagePreview) => setLocalMedia({ scope: mediaScopeKey, preview }));
473-
const [mediaScope, setMediaScope] = useState(mediaScopeKey);
474-
if (mediaScope !== mediaScopeKey) {
475-
setMediaScope(mediaScopeKey);
476-
setLocalMedia(null);
477-
}
478-
// Layout cleanup blocks stale requests from reaching onImageExpand before paint.
479-
useLayoutEffect(
480-
() => () => {
455+
const [localMediaPreview, setLocalMediaPreview] = useState<ExpandedImagePreview | null>(null);
456+
const closeLocalMediaPreview = () => setLocalMediaPreview(null);
457+
const expandMedia = onImageExpand ?? setLocalMediaPreview;
458+
// Unmounting, which a media scope change does through the key, drops requests still loading.
459+
const bindMarkdownRoot = (node: HTMLElement | null) => {
460+
markdownRef.current = node;
461+
return () => {
462+
markdownRef.current = null;
481463
mediaRequestId.current += 1;
482-
},
483-
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Leaving the scope invalidates media requests still loading for it.
484-
[mediaScopeKey],
485-
);
464+
};
465+
};
486466
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
487467
reportFailure: false,
488468
refresh: true,
@@ -909,7 +889,7 @@ function useChatMarkdownState({
909889
return {
910890
componentState,
911891
handleCopy,
912-
markdownRef,
892+
bindMarkdownRoot,
913893
markdownUrlTransform,
914894
localMediaPreview,
915895
closeLocalMediaPreview,
@@ -1551,7 +1531,22 @@ const CHAT_MARKDOWN_COMPONENTS = {
15511531
},
15521532
} satisfies Components;
15531533

1554-
function ChatMarkdown({
1534+
/** A media preview, or a media request still loading, never carries over to another thread or workspace. */
1535+
function chatMarkdownMediaScope(props: ChatMarkdownProps): string {
1536+
return [
1537+
props.threadRef?.environmentId,
1538+
props.threadRef?.threadId,
1539+
props.environmentId,
1540+
props.cwd,
1541+
props.imageBaseDir,
1542+
].join("\u0000");
1543+
}
1544+
1545+
function ChatMarkdown(props: ChatMarkdownProps) {
1546+
return <ChatMarkdownContent key={chatMarkdownMediaScope(props)} {...props} />;
1547+
}
1548+
1549+
function ChatMarkdownContent({
15551550
text,
15561551
className,
15571552
inline = false,
@@ -1563,7 +1558,7 @@ function ChatMarkdown({
15631558
const {
15641559
componentState,
15651560
handleCopy,
1566-
markdownRef,
1561+
bindMarkdownRoot,
15671562
markdownUrlTransform,
15681563
localMediaPreview,
15691564
closeLocalMediaPreview,
@@ -1573,9 +1568,6 @@ function ChatMarkdown({
15731568
extraRemarkPlugins.length === 0 &&
15741569
/(?:^|\n) {0,3}(?:`{3}|~{3})/.test(text);
15751570
const Root = inline ? "span" : "div";
1576-
const bindMarkdownRef = (node: HTMLElement | null) => {
1577-
markdownRef.current = node;
1578-
};
15791571
const remarkPlugins = [
15801572
...(lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS),
15811573
...extraRemarkPlugins,
@@ -1586,7 +1578,7 @@ function ChatMarkdown({
15861578

15871579
return (
15881580
<Root
1589-
ref={bindMarkdownRef}
1581+
ref={bindMarkdownRoot}
15901582
className={cn(
15911583
"chat-markdown w-full min-w-0 [overflow-wrap:anywhere] [word-break:break-word]",
15921584
!inline &&

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2-
import { findForMessageMatch, requestThreadFindQuery } from "./chat/threadFindActionBus";
2+
import { findForMessageMatch, openThreadFindOnQuery } from "./chat/threadFindStore";
33
import {
44
claimThreadOpen,
55
nextShownOrder,
@@ -203,7 +203,7 @@ export function useCommandPaletteThreadItems(input: {
203203
// Opens the thread with find on the word at the matched message, so it is in view.
204204
run: async () => {
205205
await item.run();
206-
requestThreadFindQuery(
206+
openThreadFindOnQuery(
207207
scopedThreadKey(scopeThreadRef(match.environmentId, match.threadId)),
208208
findForMessageMatch(match, messageSearch.query),
209209
);
Lines changed: 10 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { RuntimeSubagent } from "@t3tools/client-runtime/state/subagentRuntime";
22
import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
33
import { deriveSubagentElapsedMs } from "@t3tools/shared/orchestrationTiming";
4-
import { useEffect, useRef } from "react";
4+
import { tickTextContent } from "~/lib/tickTextContent";
55

66
function formatElapsedSeconds(totalSeconds: number): string {
77
const seconds = Math.max(0, Math.floor(totalSeconds));
@@ -33,38 +33,18 @@ export function AgentElapsed({
3333
compact?: boolean;
3434
}) {
3535
const format = compact ? formatCompactElapsedSeconds : formatElapsedSeconds;
36-
const textRef = useRef<HTMLSpanElement>(null);
3736
const live = isOrchestrationV2WorkActive(agent.status);
38-
const startedAt = agent.startedAt;
39-
const completedAt = agent.completedAt;
40-
41-
useEffect(() => {
42-
if (!startedAt) {
43-
return;
44-
}
45-
const update = () => {
46-
if (textRef.current) {
47-
const elapsedMs = deriveSubagentElapsedMs(
48-
{ status: agent.status, startedAt, completedAt },
49-
Date.now(),
50-
);
51-
const text = elapsedMs === null ? "" : format(elapsedMs / 1000);
52-
if (textRef.current.textContent !== text) textRef.current.textContent = text;
53-
}
54-
};
55-
update();
56-
if (!live) return;
57-
const id = setInterval(update, 1000);
58-
return () => clearInterval(id);
59-
}, [live, startedAt, completedAt, agent.status, format]);
60-
61-
const elapsedMs = deriveSubagentElapsedMs(agent, 0);
62-
if (elapsedMs === null) {
37+
const { status, startedAt, completedAt } = agent;
38+
if (deriveSubagentElapsedMs(agent, 0) === null) {
6339
return null;
6440
}
6541
return (
66-
<span ref={textRef} className="tabular-nums">
67-
{format(elapsedMs / 1000)}
68-
</span>
42+
<span
43+
ref={tickTextContent((nowMs) => {
44+
const elapsedMs = deriveSubagentElapsedMs({ status, startedAt, completedAt }, nowMs);
45+
return elapsedMs === null ? "" : format(elapsedMs / 1000);
46+
}, live)}
47+
className="tabular-nums"
48+
/>
6949
);
7050
}

0 commit comments

Comments
 (0)