Skip to content

Commit c0dccbe

Browse files
refactor(web): shared shortcut dispatcher; stores own drafts and previews
Adds the web building blocks the later layers use: one module-level keyboard and menu dispatcher, shared intersection and document-activity stores, keyed asset URL atoms, a composer draft store that promotes drafts and starts uploads itself, and a preview store that hands out agent reveals where snapshots arrive. Effect categories removed: - window keydown and desktop menu listeners replaced by one dispatcher with app-global and element scopes; chat route commands read route, drafts and panels at keypress time - modifier-key tracking and permission polling moved into shared stores read with useSyncExternalStore - visibility observers moved to ref callbacks on a shared IntersectionObserver - workspace image URL fetch effect moved to atoms keyed by revision - draft promotion decided by a store-level state machine - uploads started by the draft store actions that add attachments - preview reveal and device session diffing moved to where snapshots arrive, in an app-lifetime worker Bugs fixed: - A reconnect minted workspace image URLs twice, and every remount re-minted an unchanged image. - Attachments added to a draft not on screen, or a draft moved to another machine, never uploaded, leaving Send blocked behind "still uploading". - A slow image read could overwrite a newer persisted attachment list. - Agent-opened previews in background threads only appeared on the next visit, and a device opened during a disconnect was missed. Temporary compat shims (removed in a later layer of this stack): - composerDraftStore.ts: re-exports useBackgroundDraftSubmissionPending for the base ThreadRouteView, which keeps running draft promotion and missing-thread cleanup until ChatView and ThreadRouteView land in the web-chat-view layer (removed in layer 12) Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent f2e4fed commit c0dccbe

24 files changed

Lines changed: 2237 additions & 190 deletions
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import { EnvironmentId, ThreadId, 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 { makeRevisionedAssetUrlFamily } from "./assetUrls";
6+
7+
const environmentId = EnvironmentId.make("environment-1");
8+
const resource: AssetResource = {
9+
_tag: "workspace-file",
10+
threadId: ThreadId.make("thread-1"),
11+
path: "docs/diagram.png",
12+
};
13+
14+
type MintResult = AsyncResult.AsyncResult<{ relativeUrl: string; expiresAt: number }>;
15+
16+
const minted = (n: number): MintResult =>
17+
AsyncResult.success({ relativeUrl: `/a/${n}`, expiresAt: 0 });
18+
19+
// A stand-in for the asset URL query: a refresh starts a mint (counted, shown as
20+
// waiting) and `settle` completes the latest one.
21+
function setup(initial: MintResult) {
22+
let mints = 0;
23+
// Node removal runs on the registry's scheduler; `unmount` flushes it so the
24+
// next mount of the same revision builds a fresh node.
25+
const scheduled: Array<() => void> = [];
26+
const registry = AtomRegistry.make({
27+
scheduleTask: (task) => {
28+
scheduled.push(task);
29+
return () => {};
30+
},
31+
});
32+
const server = Atom.make(initial).pipe(Atom.keepAlive);
33+
const query = Atom.readable(
34+
(get) => get(server),
35+
() => {
36+
mints += 1;
37+
registry.set(server, AsyncResult.waiting(registry.get(server)));
38+
},
39+
).pipe(Atom.keepAlive);
40+
const revisioned = makeRevisionedAssetUrlFamily(() => query);
41+
const mount = (revision: string | null) => {
42+
const release = registry.mount(revisioned({ environmentId, input: { resource }, revision }));
43+
return () => {
44+
release();
45+
for (const task of scheduled.splice(0)) task();
46+
};
47+
};
48+
const settle = () => registry.set(server, minted(mints + 1));
49+
return { mount, settle, mints: () => mints };
50+
}
51+
52+
describe("makeRevisionedAssetUrlFamily", () => {
53+
it("re-mints a settled URL on first read and on each new revision, not on remount", () => {
54+
const { mount, settle, mints } = setup(minted(0));
55+
56+
mount("mutation-1")();
57+
expect(mints()).toBe(1);
58+
settle();
59+
60+
mount("mutation-1")();
61+
expect(mints()).toBe(1);
62+
63+
mount("mutation-2")();
64+
expect(mints()).toBe(2);
65+
});
66+
67+
it("re-mints when a revert returns to an earlier revision", () => {
68+
const { mount, settle, mints } = setup(minted(0));
69+
70+
mount("mutation-a")();
71+
settle();
72+
mount("mutation-b")();
73+
settle();
74+
expect(mints()).toBe(2);
75+
76+
const reverted = mount("mutation-a");
77+
expect(mints()).toBe(3);
78+
reverted();
79+
});
80+
81+
it("shares a mint in flight on the first read", () => {
82+
const { mount, mints } = setup(AsyncResult.initial(true));
83+
84+
mount("mutation-1")();
85+
expect(mints()).toBe(0);
86+
});
87+
88+
it("re-mints after a mint that was in flight when the revision changed", () => {
89+
const { mount, settle, mints } = setup(minted(0));
90+
91+
const before = mount("mutation-1");
92+
settle();
93+
const edited = mount("mutation-2");
94+
expect(mints()).toBe(2);
95+
before();
96+
97+
const stillMinting = mount("mutation-3");
98+
edited();
99+
expect(mints()).toBe(2);
100+
101+
settle();
102+
expect(mints()).toBe(3);
103+
settle();
104+
expect(mints()).toBe(3);
105+
stillMinting();
106+
});
107+
});

‎apps/web/src/assets/assetUrls.ts‎

Lines changed: 77 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@ import {
77
resolveAssetUrl,
88
} from "@t3tools/client-runtime/state/assets";
99
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
10-
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
11-
import { AsyncResult } from "effect/reactivity";
10+
import { AssetResource, type AssetCreateUrlResult, EnvironmentId } from "@t3tools/contracts";
11+
import * as Schema from "effect/Schema";
12+
import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
1213

1314
import { assetEnvironment } from "~/state/assets";
1415
import { useFilesystemReadAccess } from "~/state/filesystem";
@@ -19,16 +20,89 @@ export { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
1920

2021
export type AssetUrlState = RuntimeAssetUrlState & { readonly waiting?: boolean };
2122

23+
type AssetUrlTarget = {
24+
readonly environmentId: EnvironmentId;
25+
readonly input: { readonly resource: AssetResource };
26+
};
27+
28+
const decodeRevisionedAssetUrlKey = Schema.decodeUnknownSync(
29+
Schema.Tuple([EnvironmentId, AssetResource, Schema.NullOr(Schema.String)]),
30+
);
31+
32+
const isSettled = (result: AsyncResult.AsyncResult<unknown, unknown>) =>
33+
!AsyncResult.isInitial(result) && !result.waiting;
34+
35+
/**
36+
* The URL is minted per resource and shared across revisions, so reading a
37+
* different revision (even an earlier one after a revert) re-mints it. An
38+
* in-flight mint is shared only on first read; after an edit the server must
39+
* re-read the file, so the re-mint waits for that mint to settle.
40+
*/
41+
export function makeRevisionedAssetUrlFamily(
42+
createUrl: (
43+
target: AssetUrlTarget,
44+
) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>,
45+
) {
46+
// Outside the nodes: a node is dropped once unmounted, and the next read of
47+
// its revision must still see the revisions minted since.
48+
const mintedUnder = new WeakMap<AtomRegistry.AtomRegistry, Map<string, string | null>>();
49+
const family = Atom.family((key: string) => {
50+
const [environmentId, resource, revision] = decodeRevisionedAssetUrlKey(JSON.parse(key));
51+
const resourceKey = JSON.stringify([environmentId, resource]);
52+
const query = createUrl({ environmentId, input: { resource } });
53+
return Atom.transform(
54+
query,
55+
(get) => {
56+
let minted = mintedUnder.get(get.registry);
57+
if (minted === undefined) {
58+
minted = new Map();
59+
mintedUnder.set(get.registry, minted);
60+
}
61+
const firstRead = !minted.has(resourceKey);
62+
let pending = minted.get(resourceKey) !== revision;
63+
const current = get.once(query);
64+
if (pending && (firstRead || isSettled(current))) {
65+
pending = false;
66+
minted.set(resourceKey, revision);
67+
if (isSettled(current)) get.refresh(query);
68+
}
69+
get.subscribe(query, (value) => {
70+
get.setSelf(value);
71+
if (!pending || !isSettled(value)) return;
72+
pending = false;
73+
minted.set(resourceKey, revision);
74+
get.refresh(query);
75+
});
76+
return get.once(query);
77+
},
78+
{ initialValueTarget: query },
79+
// No idle TTL: each mount rebuilds the node, so a revision read again after
80+
// another one is compared against the record instead of a cached node.
81+
).pipe(Atom.setIdleTTL(0));
82+
});
83+
return (target: AssetUrlTarget & { readonly revision: string | null }) =>
84+
family(JSON.stringify([target.environmentId, target.input.resource, target.revision]));
85+
}
86+
87+
export const revisionedAssetUrl = makeRevisionedAssetUrlFamily(assetEnvironment.createUrl);
88+
89+
/**
90+
* Pass `revision` for a workspace file whose bytes can change under the same
91+
* path; each new revision gets a freshly minted URL.
92+
*/
2293
export function useAssetUrlState(
2394
environmentId: EnvironmentId | null,
2495
resource: AssetResource | null,
96+
revision?: string | null,
2597
): AssetUrlState {
2698
const blocked = blockedAssetUrlState(resource, useFilesystemReadAccess(environmentId));
2799
const preparedConnection = usePreparedConnection(environmentId);
28100
const result = useAtomValue(
29101
blocked !== null || environmentId === null || resource === null
30102
? EMPTY_ASSET_URL_ATOM
31-
: assetEnvironment.createUrl({ environmentId, input: { resource } }),
103+
: revision === undefined
104+
? assetEnvironment.createUrl({ environmentId, input: { resource } })
105+
: revisionedAssetUrl({ environmentId, input: { resource }, revision }),
32106
);
33107
if (blocked !== null) return blocked;
34108
return {

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

Lines changed: 10 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@ import { TriangleAlertIcon } from "lucide-react";
55
import {
66
createContext,
77
memo,
8-
useEffect,
9-
useRef,
108
useState,
119
type ComponentProps,
1210
type CSSProperties,
@@ -17,7 +15,6 @@ import {
1715
import { useAssetUrlRefresh, useAssetUrlState } from "../../assets/assetUrls";
1816
import { cn } from "../../lib/utils";
1917
import { useRightPanelStore } from "../../rightPanelStore";
20-
import { usePreparedConnection } from "../../state/session";
2118
import { MediaActions, type MediaActionSource } from "../media/MediaActions";
2219
import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
2320
import type { ExpandedImagePreview } from "./ExpandedImagePreview";
@@ -334,44 +331,17 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
334331
readonly workspaceMutationId?: string | null | undefined;
335332
readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
336333
}) {
337-
const assetUrl = useAssetUrlState(props.environmentId, props.resource);
338-
const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, props.resource);
339-
const connectionReady = usePreparedConnection(props.environmentId)._tag === "Some";
340334
const resource = props.resource;
341-
const refreshToken = JSON.stringify([props.environmentId, resource, props.workspaceMutationId]);
342-
const handledRefreshToken = useRef<string | null | undefined>(undefined);
343-
const assetLoading = assetUrl._tag === "Loading" || assetUrl.waiting === true;
344-
useEffect(() => {
345-
if (!connectionReady) {
346-
handledRefreshToken.current = null;
347-
return;
348-
}
349-
if (
350-
props.workspaceMutationId === undefined ||
351-
props.kind === "video" ||
352-
(resource._tag !== "media-file" && resource._tag !== "workspace-file") ||
353-
handledRefreshToken.current === refreshToken
354-
) {
355-
return;
356-
}
357-
if (assetLoading) {
358-
// Only the initial mount shares a pending request; edits and reconnects need a new one.
359-
if (handledRefreshToken.current === undefined) {
360-
handledRefreshToken.current = refreshToken;
361-
}
362-
return;
363-
}
364-
handledRefreshToken.current = refreshToken;
365-
void refreshAssetUrl().catch(() => undefined);
366-
}, [
367-
assetLoading,
368-
connectionReady,
369-
props.kind,
370-
props.workspaceMutationId,
371-
refreshAssetUrl,
372-
refreshToken,
373-
resource._tag,
374-
]);
335+
const assetUrl = useAssetUrlState(
336+
props.environmentId,
337+
resource,
338+
props.workspaceMutationId !== undefined &&
339+
props.kind !== "video" &&
340+
(resource._tag === "media-file" || resource._tag === "workspace-file")
341+
? props.workspaceMutationId
342+
: undefined,
343+
);
344+
const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
375345
const path =
376346
resource._tag === "media-file"
377347
? resource.path

‎apps/web/src/components/diffs/DiffFileLoadingBoundary.tsx‎

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,22 @@
1-
import { useEffect, useRef } from "react";
1+
import { observeIntersection } from "~/lib/observeIntersection";
22
import { DiffFileHeaderSkeleton } from "../DiffPanelShell";
33

44
export function DiffFileLoadingBoundary({ load, count }: { load: () => void; count: number }) {
5-
const ref = useRef<HTMLDivElement>(null);
6-
useEffect(() => {
7-
if (!ref.current) return;
8-
const observer = new IntersectionObserver(
9-
(entries) => {
10-
if (entries.some((entry) => entry.isIntersecting)) load();
11-
},
12-
{ rootMargin: "600px" },
13-
);
14-
observer.observe(ref.current);
15-
return () => observer.disconnect();
16-
}, [load]);
175
return (
18-
<div ref={ref} role="status" aria-label="Loading diff…">
6+
<div
7+
ref={(node) => {
8+
if (!node) return;
9+
return observeIntersection(
10+
node,
11+
(entry) => {
12+
if (entry.isIntersecting) load();
13+
},
14+
{ rootMargin: "600px" },
15+
);
16+
}}
17+
role="status"
18+
aria-label="Loading diff…"
19+
>
1920
{Array.from({ length: Math.min(count, 4) }, (_, index) => (
2021
<div key={index} aria-hidden className="border-b border-border/40">
2122
<DiffFileHeaderSkeleton titleWidth="medium" />
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { describe, expect, it, vi } from "vite-plus/test";
2+
3+
import { render } from "../../../test/render";
4+
import { usePermissionStatus } from "./usePermissionStatus";
5+
6+
function PermissionProbe({
7+
check,
8+
label,
9+
}: {
10+
readonly check: () => Promise<{ screen: boolean }>;
11+
readonly label: string;
12+
}) {
13+
const { status } = usePermissionStatus(async () => check(), { screen: false });
14+
return (
15+
<p>
16+
{label}: {status.screen ? "granted" : "missing"}
17+
</p>
18+
);
19+
}
20+
21+
describe("usePermissionStatus", () => {
22+
it("does not start a new check when the component re-renders", async () => {
23+
// A check that never settles keeps the interval from adding calls, so any
24+
// extra call can only come from the subscription restarting.
25+
const check = vi.fn(() => new Promise<{ screen: boolean }>(() => {}));
26+
await using screen = await render(<PermissionProbe check={check} label="first" />, {
27+
router: false, // the hook does not touch routing
28+
});
29+
await screen.rerender(<PermissionProbe check={check} label="second" />);
30+
await screen.rerender(<PermissionProbe check={check} label="third" />);
31+
32+
await expect.element(screen.getByText("third: missing")).toBeInTheDocument();
33+
expect(check).toHaveBeenCalledTimes(1);
34+
});
35+
});

0 commit comments

Comments
 (0)