fix: restore UX after performance improvements (#9799)
Restore status feedback, code-view worker reuse, streaming highlighting recovery, safe outbox recovery, current HTML, and projected live-event budgets. Verified with browser checks, iOS outbox recovery, 281 focused tests, and full CI. CI uses Shivam's HTTPS mirror fix. Created with GPT-6 Astra (preview) in Codex. Co-authored-by: shivam <[email protected]>
This commit is contained in:
1 parent
940e8233c2
commit
ce4712d5b0
31 files changed
+1511
-204
No files matched your search
@@ -52,7 +52,9 @@ jobs:
|
||||
run: vpr typecheck
|
||||
|
||||
- name: Install browser secret helper build libraries
|
||||
run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config
|
||||
run: |
|
||||
sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources
|
||||
sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: vp run build:desktop
|
||||
@@ -89,7 +91,9 @@ jobs:
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Install browser secret helper build libraries
|
||||
run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config
|
||||
run: |
|
||||
sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources
|
||||
sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config
|
||||
|
||||
- name: Test
|
||||
run: vp run --parallel --concurrency-limit 4 --filter '!t3' --filter '!@t3tools/monorepo' test
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { startHomeMotion } from "./homeMotion";
|
||||
|
||||
class ElementStub extends EventTarget {
|
||||
properties = new Map<string, string>();
|
||||
style = { setProperty: (name: string, value: string) => this.properties.set(name, value) };
|
||||
children: ElementStub[] = [];
|
||||
scrollLeft = 0;
|
||||
scrollWidth = 1_200;
|
||||
clientWidth = 400;
|
||||
matches = () => false;
|
||||
contains = (target: EventTarget | null) =>
|
||||
target === this || (target instanceof ElementStub && this.children.includes(target));
|
||||
querySelectorAll = () => this.children;
|
||||
getBoundingClientRect = vi.fn(() => ({ left: 0, top: 0, width: 400, height: 600 }));
|
||||
scrollTo = vi.fn((options: ScrollToOptions) => {
|
||||
this.scrollLeft = options.left ?? this.scrollLeft;
|
||||
});
|
||||
}
|
||||
|
||||
let observers: ObserverStub[] = [];
|
||||
class ObserverStub {
|
||||
constructor(private readonly callback: IntersectionObserverCallback) {
|
||||
observers.push(this);
|
||||
}
|
||||
observe = vi.fn();
|
||||
disconnect = vi.fn();
|
||||
report(target: ElementStub, isIntersecting: boolean) {
|
||||
this.callback(
|
||||
[{ target, isIntersecting } as unknown as IntersectionObserverEntry],
|
||||
this as unknown as IntersectionObserver,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let page = Object.assign(new EventTarget(), { visibilityState: "visible", activeElement: null });
|
||||
let viewport = new EventTarget();
|
||||
let reduced = Object.assign(new EventTarget(), { matches: false });
|
||||
let fine = Object.assign(new EventTarget(), { matches: true });
|
||||
let frames = new Map<number, FrameRequestCallback>();
|
||||
let dispose: (() => void) | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
observers = [];
|
||||
frames = new Map();
|
||||
page = Object.assign(new EventTarget(), { visibilityState: "visible", activeElement: null });
|
||||
viewport = new EventTarget();
|
||||
reduced = Object.assign(new EventTarget(), { matches: false });
|
||||
fine = Object.assign(new EventTarget(), { matches: true });
|
||||
vi.stubGlobal("document", page);
|
||||
vi.stubGlobal(
|
||||
"window",
|
||||
Object.assign(viewport, {
|
||||
matchMedia: (query: string) => (query.includes("reduced-motion") ? reduced : fine),
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("Node", ElementStub);
|
||||
vi.stubGlobal("IntersectionObserver", ObserverStub);
|
||||
let frameId = 0;
|
||||
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
|
||||
frames.set(++frameId, callback);
|
||||
return frameId;
|
||||
});
|
||||
vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
dispose?.();
|
||||
dispose = undefined;
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function fixture() {
|
||||
const hero = new ElementStub();
|
||||
const field = new ElementStub();
|
||||
const mark = new ElementStub();
|
||||
const otherMark = new ElementStub();
|
||||
field.children = [mark, otherMark];
|
||||
const endorsements = new ElementStub();
|
||||
const caret = new ElementStub();
|
||||
dispose = startHomeMotion({ hero, field, endorsements, caret } as unknown as Parameters<
|
||||
typeof startHomeMotion
|
||||
>[0]);
|
||||
return { hero, field, mark, otherMark, endorsements, caret, observer: observers[0]! };
|
||||
}
|
||||
|
||||
function movePointer(hero: ElementStub, x = 400, y = 600) {
|
||||
hero.dispatchEvent(Object.assign(new Event("pointermove"), { clientX: x, clientY: y }));
|
||||
}
|
||||
|
||||
describe("homepage motion", () => {
|
||||
it("gates each mark and caret and batches pointer input into one frame", () => {
|
||||
const { hero, field, mark, otherMark, caret, observer } = fixture();
|
||||
expect(mark.properties.get("--home-motion-state")).toBe("paused");
|
||||
observer.report(mark, true);
|
||||
observer.report(caret, true);
|
||||
expect(mark.properties.get("--home-motion-state")).toBe("running");
|
||||
expect(otherMark.properties.get("--home-motion-state")).toBe("paused");
|
||||
expect(caret.properties.get("--home-motion-state")).toBe("running");
|
||||
|
||||
movePointer(hero, 100, 100);
|
||||
movePointer(hero);
|
||||
expect(frames.size).toBe(1);
|
||||
expect(hero.getBoundingClientRect).not.toHaveBeenCalled();
|
||||
const [id, callback] = [...frames][0]!;
|
||||
frames.delete(id);
|
||||
callback(0);
|
||||
expect(field.properties.get("--px")).toBe("18.0px");
|
||||
expect(field.properties.get("--py")).toBe("14.0px");
|
||||
|
||||
movePointer(hero);
|
||||
page.visibilityState = "hidden";
|
||||
page.dispatchEvent(new Event("visibilitychange"));
|
||||
expect(frames.size).toBe(0);
|
||||
expect(field.properties.get("--px")).toBe("0px");
|
||||
expect(mark.properties.get("--home-motion-state")).toBe("paused");
|
||||
expect(caret.properties.get("--home-motion-state")).toBe("paused");
|
||||
page.visibilityState = "visible";
|
||||
page.dispatchEvent(new Event("visibilitychange"));
|
||||
reduced.matches = true;
|
||||
reduced.dispatchEvent(new Event("change"));
|
||||
movePointer(hero);
|
||||
expect(frames.size).toBe(0);
|
||||
expect(mark.properties.get("--home-motion-state")).toBe("paused");
|
||||
reduced.matches = false;
|
||||
fine.matches = false;
|
||||
reduced.dispatchEvent(new Event("change"));
|
||||
movePointer(hero);
|
||||
expect(frames.size).toBe(0);
|
||||
expect(mark.properties.get("--home-motion-state")).toBe("running");
|
||||
});
|
||||
|
||||
it("pages every eight seconds, reverses at the end, and has no timer without overflow", () => {
|
||||
const { endorsements, observer } = fixture();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
observer.report(endorsements, true);
|
||||
vi.advanceTimersByTime(7_999);
|
||||
expect(endorsements.scrollTo).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(16_001);
|
||||
expect(endorsements.scrollTo.mock.calls.map(([options]) => options.left)).toEqual([
|
||||
400, 800, 400,
|
||||
]);
|
||||
expect(
|
||||
endorsements.scrollTo.mock.calls.every(([options]) => options.behavior === "smooth"),
|
||||
).toBe(true);
|
||||
|
||||
endorsements.clientWidth = endorsements.scrollWidth;
|
||||
viewport.dispatchEvent(new Event("resize"));
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(endorsements.scrollTo).toHaveBeenLastCalledWith({ left: 400, behavior: "instant" });
|
||||
endorsements.clientWidth = 400;
|
||||
viewport.dispatchEvent(new Event("resize"));
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
});
|
||||
|
||||
it("pauses paging for hover, focus, hidden content, and reduced motion", () => {
|
||||
const { endorsements, observer } = fixture();
|
||||
observer.report(endorsements, true);
|
||||
const changeVisibility = (visible: boolean) => {
|
||||
page.visibilityState = visible ? "visible" : "hidden";
|
||||
page.dispatchEvent(new Event("visibilitychange"));
|
||||
};
|
||||
const changeMotion = (matches: boolean) => {
|
||||
reduced.matches = matches;
|
||||
reduced.dispatchEvent(new Event("change"));
|
||||
};
|
||||
const pauses = [
|
||||
[
|
||||
() => endorsements.dispatchEvent(new Event("pointerenter")),
|
||||
() => endorsements.dispatchEvent(new Event("pointerleave")),
|
||||
],
|
||||
[
|
||||
() => endorsements.dispatchEvent(new Event("focusin")),
|
||||
() =>
|
||||
endorsements.dispatchEvent(Object.assign(new Event("focusout"), { relatedTarget: null })),
|
||||
],
|
||||
[() => changeVisibility(false), () => changeVisibility(true)],
|
||||
[() => observer.report(endorsements, false), () => observer.report(endorsements, true)],
|
||||
[() => changeMotion(true), () => changeMotion(false)],
|
||||
] as const;
|
||||
for (const [pause, resume] of pauses) {
|
||||
pause();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
vi.advanceTimersByTime(16_000);
|
||||
resume();
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
}
|
||||
expect(endorsements.scrollTo).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(8_000);
|
||||
expect(endorsements.scrollTo).toHaveBeenCalledWith({ left: 400, behavior: "smooth" });
|
||||
endorsements.dispatchEvent(new Event("pointerenter"));
|
||||
expect(endorsements.scrollTo).toHaveBeenLastCalledWith({ left: 400, behavior: "instant" });
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it.each(["wheel", "pointerdown", "keydown"])("hands control to the user after %s", (event) => {
|
||||
const { endorsements, observer } = fixture();
|
||||
observer.report(endorsements, true);
|
||||
endorsements.dispatchEvent(new Event(event));
|
||||
observer.report(endorsements, false);
|
||||
observer.report(endorsements, true);
|
||||
endorsements.dispatchEvent(new Event("pointerleave"));
|
||||
viewport.dispatchEvent(new Event("resize"));
|
||||
vi.advanceTimersByTime(60_000);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(endorsements.scrollTo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels pending work and ignores events after cleanup", () => {
|
||||
const { hero, mark, endorsements, observer } = fixture();
|
||||
observer.report(mark, true);
|
||||
observer.report(endorsements, true);
|
||||
movePointer(hero);
|
||||
dispose?.();
|
||||
observer.report(mark, true);
|
||||
movePointer(hero);
|
||||
reduced.dispatchEvent(new Event("change"));
|
||||
expect(observer.disconnect).toHaveBeenCalledTimes(1);
|
||||
expect(frames.size).toBe(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(mark.properties.get("--home-motion-state")).toBe("paused");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
/** Runs homepage motion only while its content is visible. Manual scrolling stops paging. */
|
||||
export function startHomeMotion({
|
||||
hero,
|
||||
field,
|
||||
endorsements,
|
||||
caret,
|
||||
}: {
|
||||
hero: HTMLElement;
|
||||
field: HTMLElement;
|
||||
endorsements: HTMLElement;
|
||||
caret: HTMLElement;
|
||||
}) {
|
||||
if (typeof IntersectionObserver === "undefined") return () => {};
|
||||
|
||||
const marks = Array.from(field.querySelectorAll<HTMLElement>(".hero-float-mark"));
|
||||
const visible = new Set<Element>();
|
||||
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
|
||||
const finePointer = window.matchMedia("(pointer: fine)");
|
||||
const events = new AbortController();
|
||||
const eventOptions = { signal: events.signal };
|
||||
let disposed = false;
|
||||
let hovered = endorsements.matches(":hover");
|
||||
let focused = endorsements.contains(document.activeElement);
|
||||
let userControlled = false;
|
||||
let direction = 1;
|
||||
let automaticScroll = false;
|
||||
let pageTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let pointerFrame: number | undefined;
|
||||
let pointer: { x: number; y: number } | null = null;
|
||||
|
||||
const canMove = (element: Element) =>
|
||||
!disposed &&
|
||||
visible.has(element) &&
|
||||
document.visibilityState === "visible" &&
|
||||
!reducedMotion.matches;
|
||||
const canParallax = () => finePointer.matches && marks.some(canMove);
|
||||
const canPage = () =>
|
||||
canMove(endorsements) &&
|
||||
!hovered &&
|
||||
!focused &&
|
||||
!userControlled &&
|
||||
endorsements.scrollWidth > endorsements.clientWidth;
|
||||
|
||||
function resetPointer() {
|
||||
if (pointerFrame !== undefined) cancelAnimationFrame(pointerFrame);
|
||||
pointerFrame = undefined;
|
||||
pointer = null;
|
||||
field.style.setProperty("--px", "0px");
|
||||
field.style.setProperty("--py", "0px");
|
||||
}
|
||||
|
||||
function updatePaging() {
|
||||
if (canPage()) {
|
||||
pageTimer ??= setTimeout(advancePage, 8_000);
|
||||
return;
|
||||
}
|
||||
if (pageTimer !== undefined) clearTimeout(pageTimer);
|
||||
pageTimer = undefined;
|
||||
if (automaticScroll) {
|
||||
automaticScroll = false;
|
||||
endorsements.scrollTo({ left: endorsements.scrollLeft, behavior: "instant" });
|
||||
}
|
||||
}
|
||||
|
||||
function advancePage() {
|
||||
pageTimer = undefined;
|
||||
if (!canPage()) return;
|
||||
const end = endorsements.scrollWidth - endorsements.clientWidth;
|
||||
const current = endorsements.scrollLeft;
|
||||
if (current >= end - 1) direction = -1;
|
||||
else if (current <= 1) direction = 1;
|
||||
automaticScroll = true;
|
||||
endorsements.scrollTo({
|
||||
left: Math.max(0, Math.min(end, current + direction * endorsements.clientWidth)),
|
||||
behavior: "smooth",
|
||||
});
|
||||
updatePaging();
|
||||
}
|
||||
|
||||
function update() {
|
||||
for (const mark of marks) {
|
||||
mark.style.setProperty("--home-motion-state", canMove(mark) ? "running" : "paused");
|
||||
}
|
||||
caret.style.setProperty("--home-motion-state", canMove(caret) ? "running" : "paused");
|
||||
const parallax = canParallax();
|
||||
field.style.setProperty("--parallax-duration", parallax ? "0.7s" : "0s");
|
||||
if (!parallax) resetPointer();
|
||||
updatePaging();
|
||||
}
|
||||
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
if (disposed) return;
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting) visible.add(entry.target);
|
||||
else visible.delete(entry.target);
|
||||
}
|
||||
update();
|
||||
});
|
||||
for (const element of [...marks, endorsements, caret]) observer.observe(element);
|
||||
|
||||
hero.addEventListener(
|
||||
"pointermove",
|
||||
(event) => {
|
||||
if (!canParallax()) return;
|
||||
pointer = { x: event.clientX, y: event.clientY };
|
||||
pointerFrame ??= requestAnimationFrame(() => {
|
||||
pointerFrame = undefined;
|
||||
if (!pointer || !canParallax()) return;
|
||||
const bounds = hero.getBoundingClientRect();
|
||||
if (bounds.width === 0 || bounds.height === 0) return;
|
||||
field.style.setProperty(
|
||||
"--px",
|
||||
`${(((pointer.x - bounds.left) / bounds.width - 0.5) * 36).toFixed(1)}px`,
|
||||
);
|
||||
field.style.setProperty(
|
||||
"--py",
|
||||
`${(((pointer.y - bounds.top) / bounds.height - 0.5) * 28).toFixed(1)}px`,
|
||||
);
|
||||
});
|
||||
},
|
||||
eventOptions,
|
||||
);
|
||||
hero.addEventListener("pointerleave", resetPointer, eventOptions);
|
||||
endorsements.addEventListener(
|
||||
"pointerenter",
|
||||
() => {
|
||||
hovered = true;
|
||||
updatePaging();
|
||||
},
|
||||
eventOptions,
|
||||
);
|
||||
endorsements.addEventListener(
|
||||
"pointerleave",
|
||||
() => {
|
||||
hovered = false;
|
||||
updatePaging();
|
||||
},
|
||||
eventOptions,
|
||||
);
|
||||
endorsements.addEventListener(
|
||||
"focusin",
|
||||
() => {
|
||||
focused = true;
|
||||
updatePaging();
|
||||
},
|
||||
eventOptions,
|
||||
);
|
||||
endorsements.addEventListener(
|
||||
"focusout",
|
||||
(event) => {
|
||||
focused = event.relatedTarget instanceof Node && endorsements.contains(event.relatedTarget);
|
||||
updatePaging();
|
||||
},
|
||||
eventOptions,
|
||||
);
|
||||
const takeControl = () => {
|
||||
userControlled = true;
|
||||
updatePaging();
|
||||
};
|
||||
endorsements.addEventListener("wheel", takeControl, { ...eventOptions, passive: true });
|
||||
endorsements.addEventListener("pointerdown", takeControl, eventOptions);
|
||||
endorsements.addEventListener("keydown", takeControl, eventOptions);
|
||||
document.addEventListener("visibilitychange", update, eventOptions);
|
||||
window.addEventListener("resize", update, eventOptions);
|
||||
reducedMotion.addEventListener("change", update, eventOptions);
|
||||
finePointer.addEventListener("change", update, eventOptions);
|
||||
update();
|
||||
|
||||
return () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
events.abort();
|
||||
observer.disconnect();
|
||||
update();
|
||||
};
|
||||
}
|
||||
@@ -355,6 +355,7 @@ const screenshot = await getImage({
|
||||
|
||||
<script>
|
||||
import { fetchLatestRelease, RELEASES_URL, type ReleaseAsset } from "../lib/releases";
|
||||
import { startHomeMotion } from "../lib/homeMotion";
|
||||
|
||||
type Platform = { os: "mac" | "win" | "linux"; label: string };
|
||||
|
||||
@@ -419,6 +420,14 @@ const screenshot = await getImage({
|
||||
}
|
||||
|
||||
init();
|
||||
|
||||
const hero = document.querySelector<HTMLElement>(".hero");
|
||||
const field = document.querySelector<HTMLElement>(".hero-float");
|
||||
const endorsements = document.querySelector<HTMLElement>(".endorsement-carousel");
|
||||
const caret = document.querySelector<HTMLElement>(".caret");
|
||||
if (hero && field && endorsements && caret) {
|
||||
startHomeMotion({ hero, field, endorsements, caret });
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
@@ -590,12 +599,14 @@ const screenshot = await getImage({
|
||||
:global([data-platform="linux"]) .dl-icon--linux { display: block; }
|
||||
:global(html:not([data-platform])) .dl-icon--apple { display: block; }
|
||||
|
||||
/* Harness marks stay in their final positions after the entry animation. */
|
||||
/* Marks enter once, then drift while visible and lean toward the pointer. */
|
||||
.hero-float {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
z-index: 1;
|
||||
--px: 0px;
|
||||
--py: 0px;
|
||||
}
|
||||
|
||||
.hero-float-mark {
|
||||
@@ -605,6 +616,8 @@ const screenshot = await getImage({
|
||||
width: var(--s);
|
||||
height: var(--s);
|
||||
margin-left: calc(var(--s) / -2);
|
||||
translate: calc(var(--px) * var(--depth)) calc(var(--py) * var(--depth));
|
||||
transition: translate var(--parallax-duration, 0s) cubic-bezier(0.2, 0.7, 0.2, 1);
|
||||
}
|
||||
|
||||
.hero-float-card {
|
||||
@@ -618,7 +631,10 @@ const screenshot = await getImage({
|
||||
box-shadow:
|
||||
0 20px 48px -16px rgba(0, 0, 0, 0.65),
|
||||
0 2px 0 0 rgba(255, 255, 255, 0.04) inset;
|
||||
animation: mark-in 1s cubic-bezier(0.2, 0.7, 0.2, 1) var(--d) both;
|
||||
animation:
|
||||
mark-in 1s cubic-bezier(0.2, 0.7, 0.2, 1) var(--d) both,
|
||||
mark-drift var(--dur) ease-in-out calc(var(--d) + 1s) infinite;
|
||||
animation-play-state: running, var(--home-motion-state, paused);
|
||||
}
|
||||
|
||||
.hero-float-card img {
|
||||
@@ -637,16 +653,21 @@ const screenshot = await getImage({
|
||||
from { opacity: 0; transform: translate(var(--fx), var(--fy)) rotate(calc(var(--rot) + 24deg)) scale(0.6); }
|
||||
to { opacity: 1; transform: translate(0, 0) rotate(var(--rot)) scale(1); }
|
||||
}
|
||||
@keyframes mark-drift {
|
||||
0%, 100% { transform: translate(0, 0) rotate(var(--rot)); }
|
||||
50% { transform: translate(var(--dx), var(--dy)) rotate(calc(var(--rot) + var(--wob))); }
|
||||
}
|
||||
|
||||
.hf-opencode { --x: max(-300px, -19vw); --y: 20px; --s: 64px; --rot: 6deg; --d: 620ms; --fx: -40px; --fy: -80px; }
|
||||
.hf-antigravity { --x: min(300px, 19vw); --y: 20px; --s: 64px; --rot: -5deg; --d: 580ms; --fx: 40px; --fy: -80px; }
|
||||
.hf-claude { --x: max(-560px, -38vw); --y: 128px; --s: 96px; --rot: -8deg; --d: 380ms; --fx: -160px; --fy: -40px; --tint: rgba(217, 119, 87, 0.22); }
|
||||
.hf-codex { --x: min(560px, 38vw); --y: 128px; --s: 96px; --rot: 7deg; --d: 460ms; --fx: 160px; --fy: -40px; }
|
||||
.hf-grok { --x: max(-440px, -30vw); --y: 440px; --s: 80px; --rot: 4deg; --d: 540ms; --fx: -120px; --fy: 80px; }
|
||||
.hf-cursor { --x: min(440px, 30vw); --y: 440px; --s: 80px; --rot: -5deg; --d: 700ms; --fx: 120px; --fy: 80px; }
|
||||
.hf-opencode { --x: max(-300px, -19vw); --y: 20px; --s: 64px; --rot: 6deg; --depth: 0.6; --d: 620ms; --dur: 8.5s; --dx: 2px; --dy: -8px; --wob: 3deg; --fx: -40px; --fy: -80px; }
|
||||
.hf-antigravity { --x: min(300px, 19vw); --y: 20px; --s: 64px; --rot: -5deg; --depth: 0.6; --d: 580ms; --dur: 9.8s; --dx: -2px; --dy: -9px; --wob: -3deg; --fx: 40px; --fy: -80px; }
|
||||
.hf-claude { --x: max(-560px, -38vw); --y: 128px; --s: 96px; --rot: -8deg; --depth: 1.2; --d: 380ms; --dur: 10.5s; --dx: 4px; --dy: -12px; --wob: -2deg; --fx: -160px; --fy: -40px; --tint: rgba(217, 119, 87, 0.22); }
|
||||
.hf-codex { --x: min(560px, 38vw); --y: 128px; --s: 96px; --rot: 7deg; --depth: 1.2; --d: 460ms; --dur: 9.2s; --dx: -4px; --dy: -10px; --wob: 2deg; --fx: 160px; --fy: -40px; }
|
||||
.hf-grok { --x: max(-440px, -30vw); --y: 440px; --s: 80px; --rot: 4deg; --depth: 0.9; --d: 540ms; --dur: 11.5s; --dx: 3px; --dy: -9px; --wob: -3deg; --fx: -120px; --fy: 80px; }
|
||||
.hf-cursor { --x: min(440px, 30vw); --y: 440px; --s: 80px; --rot: -5deg; --depth: 0.9; --d: 700ms; --dur: 7.8s; --dx: -3px; --dy: -11px; --wob: 3deg; --fx: 120px; --fy: 80px; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.hero-float-card { animation: none; transform: rotate(var(--rot)); }
|
||||
.hero-float-mark { translate: none; transition: none; }
|
||||
}
|
||||
|
||||
@media (max-width: 1180px) {
|
||||
@@ -988,6 +1009,16 @@ const screenshot = await getImage({
|
||||
width: 7px; height: 14px;
|
||||
background: var(--fg);
|
||||
margin-left: 4px;
|
||||
animation: blink 1s steps(2) infinite;
|
||||
animation-play-state: var(--home-motion-state, paused);
|
||||
}
|
||||
|
||||
@keyframes blink {
|
||||
50% { opacity: 0; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.caret { animation: none; }
|
||||
}
|
||||
|
||||
.open-pitch {
|
||||
|
||||
@@ -156,13 +156,8 @@ export function useCreateProjectThread() {
|
||||
);
|
||||
return AsyncResult.failure(result.cause);
|
||||
}
|
||||
// The started turn holds its own copy of the bytes; a failed delete is
|
||||
// surfaced without failing the started task.
|
||||
await prepared.releaseUploads().catch((error) => {
|
||||
console.warn("[project-thread] could not delete consumed pending uploads", error);
|
||||
});
|
||||
setPendingConnectionError(null);
|
||||
scheduleUnusedComposerAttachmentCleanup(input.initialAttachments);
|
||||
scheduleUnusedComposerAttachmentCleanup(prepared.draftAttachments);
|
||||
|
||||
return mapAtomCommandResult(result, () =>
|
||||
scopeThreadRef(input.project.environmentId, threadId),
|
||||
|
||||
@@ -33,8 +33,8 @@ import { uuidv4 } from "./uuid";
|
||||
* This module owns the server side of a composer attachment's lifecycle.
|
||||
* `prepareTurnAttachments` acquires pending uploads (verifying and reusing
|
||||
* persisted ones), hands the uploaded ids back to the attachment's durable
|
||||
* owner (queued outbox message or composer draft), and returns a release
|
||||
* handle for after the turn consumed the bytes. Nothing outside this module
|
||||
* owner (queued outbox message or composer draft), and leaves their cleanup
|
||||
* to that owner after it checks shared references. Nothing outside this module
|
||||
* mints or deletes pending uploads. The local-file side of the lifecycle is
|
||||
* owned by `removeThreadOutboxMessage` / the composer draft mutators, which
|
||||
* release files through `releaseUnusedComposerAttachmentFiles`.
|
||||
@@ -149,8 +149,6 @@ export interface PreparedTurnAttachments {
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
|
||||
/** Every pending upload backing this turn (reused and newly minted). */
|
||||
readonly pendingAttachmentIds: ReadonlyArray<string>;
|
||||
/** Deletes all pending uploads once the delivered turn holds the bytes. */
|
||||
readonly releaseUploads: () => Promise<void>;
|
||||
}
|
||||
|
||||
export type PrepareTurnAttachmentsResult =
|
||||
@@ -306,7 +304,6 @@ export async function prepareTurnAttachments(input: {
|
||||
attachments,
|
||||
draftAttachments,
|
||||
pendingAttachmentIds,
|
||||
releaseUploads: () => releasePendingAttachmentUploads(environmentId, pendingAttachmentIds),
|
||||
});
|
||||
|
||||
if (input.attachments.length === 0 || (files.length === 0 && !input.supportsImageUploads)) {
|
||||
|
||||
@@ -19,7 +19,7 @@ vi.mock("./thread-outbox", async () => {
|
||||
harness.manager = createThreadOutboxManager({
|
||||
registry: appAtomRegistry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
load: async () => ({ messages: [], errors: [] }),
|
||||
write: async (message) => {
|
||||
const pending = harness.writeGates.shift();
|
||||
if (pending) {
|
||||
|
||||
@@ -72,16 +72,26 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
options.registry.set(queuedMessagesByThreadKeyAtom, groupQueuedThreadMessages(messages));
|
||||
};
|
||||
|
||||
// Resolves true when hydration completed; false when the read failed (the
|
||||
// next call retries). Destructive callers (the attachment sweep) must not
|
||||
// treat a failed hydration as an empty queue.
|
||||
// Readable messages can be used after a partial load. Only a complete load
|
||||
// returns true, so cleanup cannot delete files owned by unreadable records.
|
||||
// A later call retries failed reads without replacing live message objects.
|
||||
const load = (): Promise<boolean> => {
|
||||
if (loadPromise !== null) {
|
||||
return loadPromise;
|
||||
}
|
||||
loadPromise = serialize(async () => {
|
||||
const persistedMessages = await options.storage.load();
|
||||
setMessages([...persistedMessages, ...currentMessages()]);
|
||||
const result = await options.storage.load();
|
||||
const current = currentMessages();
|
||||
const currentIds = new Set(current.map((message) => message.messageId));
|
||||
const recovered = result.messages.filter(
|
||||
(message) => !currentIds.has(message.messageId) && !revisions.has(message.messageId),
|
||||
);
|
||||
// Accepted edits and removals win over a later disk read. Retaining
|
||||
// current objects also keeps retries from restarting the drain.
|
||||
if (recovered.length > 0) setMessages([...recovered, ...current]);
|
||||
if (result.errors.length > 0) {
|
||||
throw new AggregateError(result.errors, "Some queued messages could not be read.");
|
||||
}
|
||||
return true;
|
||||
}).catch((cause) => {
|
||||
loadPromise = null;
|
||||
@@ -275,15 +285,23 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
|
||||
// changes after this request must not enter the clear set.
|
||||
const revisionsAtRequest = new Map(revisions);
|
||||
return serialize(async () => {
|
||||
const persisted = await options.storage.load().catch((cause) => {
|
||||
throw new ThreadOutboxManagerError({
|
||||
operation: "clear-environment-load",
|
||||
environmentId,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
cause,
|
||||
const persisted = await options.storage
|
||||
.load()
|
||||
.then((result) => {
|
||||
if (result.errors.length > 0) {
|
||||
throw new AggregateError(result.errors, "Some queued messages could not be read.");
|
||||
}
|
||||
return result.messages;
|
||||
})
|
||||
.catch((cause) => {
|
||||
throw new ThreadOutboxManagerError({
|
||||
operation: "clear-environment-load",
|
||||
environmentId,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
cause,
|
||||
});
|
||||
});
|
||||
});
|
||||
const allMessages = flattenQueuedThreadMessages(
|
||||
groupQueuedThreadMessages([...persisted, ...currentMessages()]),
|
||||
);
|
||||
|
||||
@@ -19,7 +19,7 @@ vi.mock("./thread-outbox", async () => {
|
||||
harness.manager = createThreadOutboxManager({
|
||||
registry: appAtomRegistry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
load: async () => ({ messages: [], errors: [] }),
|
||||
write: async () => undefined,
|
||||
remove: async () => undefined,
|
||||
},
|
||||
|
||||
@@ -44,8 +44,13 @@ export class ThreadOutboxStorageError extends Schema.TaggedErrorClass<ThreadOutb
|
||||
}
|
||||
}
|
||||
|
||||
export interface ThreadOutboxLoadResult {
|
||||
readonly messages: ReadonlyArray<QueuedThreadMessage>;
|
||||
readonly errors: ReadonlyArray<ThreadOutboxStorageError>;
|
||||
}
|
||||
|
||||
export interface ThreadOutboxStorage {
|
||||
readonly load: () => Promise<ReadonlyArray<QueuedThreadMessage>>;
|
||||
readonly load: () => Promise<ThreadOutboxLoadResult>;
|
||||
readonly write: (message: QueuedThreadMessage) => Promise<void>;
|
||||
readonly remove: (message: QueuedThreadMessage) => Promise<void>;
|
||||
}
|
||||
@@ -69,6 +74,7 @@ async function getMessageFile(messageId: MessageId) {
|
||||
export const expoThreadOutboxStorage: ThreadOutboxStorage = {
|
||||
load: async () => {
|
||||
const messages: QueuedThreadMessage[] = [];
|
||||
const errors: ThreadOutboxStorageError[] = [];
|
||||
try {
|
||||
const { File } = await import("expo-file-system");
|
||||
const directory = await getOutboxDirectory();
|
||||
@@ -80,20 +86,21 @@ export const expoThreadOutboxStorage: ThreadOutboxStorage = {
|
||||
try {
|
||||
messages.push(decodeQueuedThreadMessage(JSON.parse(await entry.text()) as unknown));
|
||||
} catch (cause) {
|
||||
// A partial queue hides attachment owners from cleanup. Keep all
|
||||
// records untouched until every persisted message can be read.
|
||||
throw new ThreadOutboxStorageError({
|
||||
operation: "read-message",
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
fileName: entry.name,
|
||||
cause,
|
||||
});
|
||||
// Recover readable messages without treating their attachment
|
||||
// owners as the complete inventory needed for cleanup.
|
||||
errors.push(
|
||||
new ThreadOutboxStorageError({
|
||||
operation: "read-message",
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
fileName: entry.name,
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (cause) {
|
||||
if (cause instanceof ThreadOutboxStorageError) throw cause;
|
||||
throw new ThreadOutboxStorageError({
|
||||
operation: "load",
|
||||
environmentId: null,
|
||||
@@ -103,7 +110,7 @@ export const expoThreadOutboxStorage: ThreadOutboxStorage = {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
return messages;
|
||||
return { messages, errors };
|
||||
},
|
||||
write: async (message) => {
|
||||
const fileName = messageFileName(message.messageId);
|
||||
|
||||
@@ -13,8 +13,44 @@ import { onTestFinished, vi } from "vite-plus/test";
|
||||
const outboxFiles = vi.hoisted(() => new Map<string, string | Error>());
|
||||
|
||||
vi.mock("expo-file-system", () => {
|
||||
class Directory {
|
||||
create() {}
|
||||
|
||||
list() {
|
||||
return Array.from(outboxFiles.keys(), (name) => new File(name));
|
||||
}
|
||||
}
|
||||
|
||||
class File {
|
||||
constructor(readonly name: string) {}
|
||||
readonly name: string;
|
||||
readonly parentDirectory = new Directory();
|
||||
|
||||
constructor(...parts: [string] | [Directory, string]) {
|
||||
this.name = parts.length === 1 ? parts[0] : parts[1];
|
||||
}
|
||||
|
||||
get exists() {
|
||||
return outboxFiles.has(this.name);
|
||||
}
|
||||
|
||||
create() {
|
||||
outboxFiles.set(this.name, "");
|
||||
}
|
||||
|
||||
write(contents: string) {
|
||||
outboxFiles.set(this.name, contents);
|
||||
}
|
||||
|
||||
moveSync(file: File) {
|
||||
const contents = outboxFiles.get(this.name);
|
||||
if (contents === undefined) throw new Error("Missing file");
|
||||
outboxFiles.set(file.name, contents);
|
||||
outboxFiles.delete(this.name);
|
||||
}
|
||||
|
||||
delete() {
|
||||
outboxFiles.delete(this.name);
|
||||
}
|
||||
|
||||
async text(): Promise<string> {
|
||||
const contents = outboxFiles.get(this.name);
|
||||
@@ -26,13 +62,7 @@ vi.mock("expo-file-system", () => {
|
||||
|
||||
return {
|
||||
File,
|
||||
Directory: class {
|
||||
create() {}
|
||||
|
||||
list() {
|
||||
return Array.from(outboxFiles.keys(), (name) => new File(name));
|
||||
}
|
||||
},
|
||||
Directory,
|
||||
Paths: { document: "/documents" },
|
||||
};
|
||||
});
|
||||
@@ -52,7 +82,12 @@ import {
|
||||
type QueuedThreadMessage,
|
||||
} from "./thread-outbox-model";
|
||||
import { createThreadOutboxManager, ThreadOutboxManagerError } from "./thread-outbox-manager";
|
||||
import { expoThreadOutboxStorage, type ThreadOutboxStorage } from "./thread-outbox-storage";
|
||||
import {
|
||||
expoThreadOutboxStorage,
|
||||
ThreadOutboxStorageError,
|
||||
type ThreadOutboxLoadResult,
|
||||
type ThreadOutboxStorage,
|
||||
} from "./thread-outbox-storage";
|
||||
|
||||
function queuedMessage(input: {
|
||||
readonly environmentId?: string;
|
||||
@@ -73,7 +108,7 @@ function queuedMessage(input: {
|
||||
|
||||
describe("thread outbox", () => {
|
||||
it.each(["read", "json", "schema"] as const)(
|
||||
"does not load a partial outbox after a record %s failure",
|
||||
"recovers usable messages without permitting cleanup after a record %s failure",
|
||||
async (failure) => {
|
||||
onTestFinished(() => outboxFiles.clear());
|
||||
const first = queuedMessage({
|
||||
@@ -81,10 +116,11 @@ describe("thread outbox", () => {
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const second = queuedMessage({
|
||||
environmentId: "environment-2",
|
||||
messageId: "message-2",
|
||||
createdAt: "2026-06-08T10:00:02.000Z",
|
||||
});
|
||||
outboxFiles.set("message-1.json", JSON.stringify(encodeQueuedThreadMessage(first)));
|
||||
// Put the unreadable record first to check that later records still load.
|
||||
outboxFiles.set(
|
||||
"message-2.json",
|
||||
failure === "read"
|
||||
@@ -93,14 +129,52 @@ describe("thread outbox", () => {
|
||||
? "{"
|
||||
: JSON.stringify({ ...second, schemaVersion: 999 }),
|
||||
);
|
||||
outboxFiles.set("message-1.json", JSON.stringify(encodeQueuedThreadMessage(first)));
|
||||
const unreadable = outboxFiles.get("message-2.json");
|
||||
|
||||
await expect(expoThreadOutboxStorage.load()).rejects.toMatchObject({
|
||||
operation: "read-message",
|
||||
fileName: "message-2.json",
|
||||
await expect(expoThreadOutboxStorage.load()).resolves.toMatchObject({
|
||||
messages: [first],
|
||||
errors: [{ operation: "read-message", fileName: "message-2.json" }],
|
||||
});
|
||||
|
||||
const registry = AtomRegistry.make();
|
||||
onTestFinished(() => registry.dispose());
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: expoThreadOutboxStorage,
|
||||
warn: () => {},
|
||||
});
|
||||
await expect(manager.load()).resolves.toBe(false);
|
||||
const recovered = registry.get(manager.queuedMessagesByThreadKeyAtom)[
|
||||
"environment-1:thread-1"
|
||||
]![0]!;
|
||||
expect(recovered).toEqual(first);
|
||||
await expect(manager.confirmQueued(recovered)).resolves.toBe(true);
|
||||
const edited = { ...recovered, text: "Edited after recovery" };
|
||||
await expect(manager.update(edited)).resolves.toBe(true);
|
||||
const beforeRetry = registry.get(manager.queuedMessagesByThreadKeyAtom);
|
||||
await expect(manager.load()).resolves.toBe(false);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toBe(beforeRetry);
|
||||
await expect(manager.clearEnvironment(first.environmentId)).rejects.toMatchObject({
|
||||
operation: "clear-environment-load",
|
||||
});
|
||||
expect(outboxFiles.get("message-2.json")).toBe(unreadable);
|
||||
expect(outboxFiles.has("message-1.json")).toBe(true);
|
||||
|
||||
// A delivered readable message can leave the queue while the failed
|
||||
// record stays intact. Its attachment cleanup has a separate guard.
|
||||
await expect(manager.remove(edited)).resolves.toBe(edited);
|
||||
expect(outboxFiles.has("message-1.json")).toBe(false);
|
||||
|
||||
outboxFiles.set("message-2.json", JSON.stringify(encodeQueuedThreadMessage(second)));
|
||||
await expect(expoThreadOutboxStorage.load()).resolves.toEqual([first, second]);
|
||||
await expect(manager.load()).resolves.toBe(true);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-2:thread-1": [second],
|
||||
});
|
||||
await expect(expoThreadOutboxStorage.load()).resolves.toEqual({
|
||||
messages: [second],
|
||||
errors: [],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -138,6 +212,59 @@ describe("thread outbox", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps in-session edits and removals when an incomplete load is retried", async () => {
|
||||
const registry = AtomRegistry.make();
|
||||
onTestFinished(() => registry.dispose());
|
||||
const message = queuedMessage({
|
||||
messageId: "message-retried",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const started = Promise.withResolvers<void>();
|
||||
const response = Promise.withResolvers<ThreadOutboxLoadResult>();
|
||||
const load = vi.fn<ThreadOutboxStorage["load"]>(async () => ({
|
||||
messages: [message],
|
||||
errors: [],
|
||||
}));
|
||||
load.mockImplementationOnce(() => {
|
||||
started.resolve();
|
||||
return response.promise;
|
||||
});
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: { load, write: async () => {}, remove: async () => {} },
|
||||
warn: () => {},
|
||||
});
|
||||
const loading = manager.load();
|
||||
await started.promise;
|
||||
const edited = { ...message, text: "Accepted while storage was being read" };
|
||||
const writing = manager.enqueue(edited);
|
||||
response.resolve({
|
||||
messages: [message],
|
||||
errors: [
|
||||
new ThreadOutboxStorageError({
|
||||
operation: "read-message",
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
fileName: "unreadable.json",
|
||||
cause: new Error("unreadable record"),
|
||||
}),
|
||||
],
|
||||
});
|
||||
await expect(loading).resolves.toBe(false);
|
||||
await writing;
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
|
||||
"environment-1:thread-1": [edited],
|
||||
});
|
||||
await expect(manager.confirmQueued(edited)).resolves.toBe(true);
|
||||
|
||||
await manager.remove(edited);
|
||||
// A later repaired record can contain a stale copy of a removed message.
|
||||
await expect(manager.load()).resolves.toBe(true);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("groups messages by scoped thread and preserves creation order", () => {
|
||||
const later = queuedMessage({
|
||||
messageId: "message-2",
|
||||
@@ -335,7 +462,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
load: async () => ({ messages: [], errors: [] }),
|
||||
write: async () => undefined,
|
||||
remove: async () => undefined,
|
||||
},
|
||||
@@ -382,7 +509,7 @@ describe("thread outbox", () => {
|
||||
if (loadCalls === 1) {
|
||||
await initialLoadBlocked;
|
||||
}
|
||||
return [...stored.values()];
|
||||
return { messages: [...stored.values()], errors: [] };
|
||||
},
|
||||
write: async () => undefined,
|
||||
remove: async (candidate) => {
|
||||
@@ -418,7 +545,7 @@ describe("thread outbox", () => {
|
||||
load: async () => {
|
||||
loadCalls += 1;
|
||||
if (loadCalls === 1) throw loadCause;
|
||||
return [];
|
||||
return { messages: [], errors: [] };
|
||||
},
|
||||
write: async () => undefined,
|
||||
remove: async () => undefined,
|
||||
@@ -451,7 +578,7 @@ describe("thread outbox", () => {
|
||||
const removalCause = new Error("remove failed");
|
||||
let failRemoval = true;
|
||||
const storage: ThreadOutboxStorage = {
|
||||
load: async () => [...stored.values()],
|
||||
load: async () => ({ messages: [...stored.values()], errors: [] }),
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
@@ -501,7 +628,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
load: async () => ({ messages: [], errors: [] }),
|
||||
write: async () => writeBlocked,
|
||||
remove: async () => undefined,
|
||||
},
|
||||
@@ -530,7 +657,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
load: async () => ({ messages: [], errors: [] }),
|
||||
write: async () => {
|
||||
throw writeCause;
|
||||
},
|
||||
@@ -561,7 +688,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
load: async () => ({ messages: [], errors: [] }),
|
||||
write: async () => {
|
||||
throw new Error("disk full");
|
||||
},
|
||||
@@ -593,7 +720,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
load: async () => ({ messages: [], errors: [] }),
|
||||
write: async () => {
|
||||
if (failNextWrite) {
|
||||
failNextWrite = false;
|
||||
@@ -630,7 +757,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
load: async () => ({ messages: [], errors: [] }),
|
||||
write: async () => undefined,
|
||||
remove: async () => undefined,
|
||||
},
|
||||
@@ -654,7 +781,7 @@ describe("thread outbox", () => {
|
||||
const registry = AtomRegistry.make();
|
||||
const stored = new Map<MessageId, QueuedThreadMessage>();
|
||||
const storage: ThreadOutboxStorage = {
|
||||
load: async () => [...stored.values()],
|
||||
load: async () => ({ messages: [...stored.values()], errors: [] }),
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
@@ -689,7 +816,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
load: async () => ({ messages: [], errors: [] }),
|
||||
write: async (message) => {
|
||||
writes.push(message.text);
|
||||
},
|
||||
@@ -733,7 +860,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
load: async () => ({ messages: [], errors: [] }),
|
||||
write: async (message) => {
|
||||
writes.push(message.text);
|
||||
if (message.text === "stale upload") {
|
||||
@@ -777,7 +904,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [...stored.values()],
|
||||
load: async () => ({ messages: [...stored.values()], errors: [] }),
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
@@ -826,7 +953,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [...stored.values()],
|
||||
load: async () => ({ messages: [...stored.values()], errors: [] }),
|
||||
write: async (message) => {
|
||||
if (message === retried) {
|
||||
replacementWriteStarted.resolve();
|
||||
@@ -876,7 +1003,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [...stored.values()],
|
||||
load: async () => ({ messages: [...stored.values()], errors: [] }),
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
@@ -915,7 +1042,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [...stored.values()],
|
||||
load: async () => ({ messages: [...stored.values()], errors: [] }),
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
@@ -979,7 +1106,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [...stored.values()],
|
||||
load: async () => ({ messages: [...stored.values()], errors: [] }),
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
@@ -1022,7 +1149,7 @@ describe("thread outbox", () => {
|
||||
const manager = createThreadOutboxManager({
|
||||
registry,
|
||||
storage: {
|
||||
load: async () => [...stored.values()],
|
||||
load: async () => ({ messages: [...stored.values()], errors: [] }),
|
||||
write: async (message) => {
|
||||
stored.set(message.messageId, message);
|
||||
},
|
||||
|
||||
@@ -21,10 +21,6 @@ export async function flushThreadOutbox(): Promise<void> {
|
||||
await flushThreadOutboxWrites();
|
||||
}
|
||||
|
||||
export function ensureThreadOutboxLoaded(): void {
|
||||
void threadOutboxManager.load();
|
||||
}
|
||||
|
||||
export function enqueueThreadOutboxMessage(message: QueuedThreadMessage): Promise<void> {
|
||||
return threadOutboxManager.enqueue(message);
|
||||
}
|
||||
|
||||
@@ -1748,7 +1748,92 @@ describe("mobile composer drafts", () => {
|
||||
expect(composerAttachmentCleanupMocks.remove.mock.calls).toEqual([[first.fileUri]]);
|
||||
});
|
||||
|
||||
// Uses a fresh module instance (hydration is one-shot), so it stays last.
|
||||
// These final tests use fresh module instances for independent hydration.
|
||||
it("keeps attachment files and uploads after a recovered message leaves an incomplete outbox", async () => {
|
||||
vi.resetModules();
|
||||
const drafts = await import("./use-composer-drafts");
|
||||
const { threadOutboxManager: manager } = await import("./thread-outbox");
|
||||
const { expoThreadOutboxStorage: storage, ThreadOutboxStorageError } =
|
||||
await import("./thread-outbox-storage");
|
||||
const { removeThreadOutboxMessage } = await import("./thread-outbox-removal");
|
||||
const { appAtomRegistry: registry } = await import("./atom-registry");
|
||||
onTestFinished(() => registry.dispose());
|
||||
const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
onTestFinished(() => warning.mockRestore());
|
||||
const file = {
|
||||
id: "file-partial-outbox",
|
||||
type: "file" as const,
|
||||
name: "shared.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
fileUri: "file:///documents/t3-composer-attachments/shared.pdf",
|
||||
uploadEnvironmentId: EnvironmentId.make("environment-1"),
|
||||
uploadedAttachmentId: "pending-partial-outbox",
|
||||
};
|
||||
const readable = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
messageId: MessageId.make("message-readable"),
|
||||
commandId: CommandId.make("command-readable"),
|
||||
text: "Send the readable message",
|
||||
attachments: [file],
|
||||
createdAt: "2026-09-04T00:00:00.000Z",
|
||||
};
|
||||
const saved = new Map([[readable.messageId, readable]]);
|
||||
let unreadable = true;
|
||||
const load = vi.spyOn(storage, "load").mockImplementation(async () => ({
|
||||
messages: [...saved.values()],
|
||||
errors: unreadable
|
||||
? [
|
||||
new ThreadOutboxStorageError({
|
||||
operation: "read-message",
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
messageId: null,
|
||||
fileName: "unreadable.json",
|
||||
cause: new Error("unreadable record"),
|
||||
}),
|
||||
]
|
||||
: [],
|
||||
}));
|
||||
const remove = vi.spyOn(storage, "remove").mockImplementation(async (message) => {
|
||||
saved.delete(message.messageId);
|
||||
});
|
||||
onTestFinished(() => {
|
||||
load.mockRestore();
|
||||
remove.mockRestore();
|
||||
});
|
||||
|
||||
await expect(manager.load()).resolves.toBe(false);
|
||||
await expect(manager.confirmQueued(readable)).resolves.toBe(true);
|
||||
await expect(removeThreadOutboxMessage(readable)).resolves.toBe(true);
|
||||
await drafts.releaseUnusedComposerAttachmentFiles([file]);
|
||||
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
|
||||
expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
|
||||
expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();
|
||||
|
||||
const recovered = {
|
||||
...readable,
|
||||
environmentId: EnvironmentId.make("environment-2"),
|
||||
messageId: MessageId.make("message-recovered"),
|
||||
commandId: CommandId.make("command-recovered"),
|
||||
};
|
||||
saved.set(recovered.messageId, recovered);
|
||||
unreadable = false;
|
||||
await expect(manager.load()).resolves.toBe(true);
|
||||
await drafts.releaseUnusedComposerAttachmentFiles([file]);
|
||||
expect(composerAttachmentCleanupMocks.remove).not.toHaveBeenCalled();
|
||||
expect(composerAttachmentCleanupMocks.releaseUploads).not.toHaveBeenCalled();
|
||||
|
||||
await removeThreadOutboxMessage(recovered);
|
||||
await drafts.releaseUnusedComposerAttachmentFiles([file]);
|
||||
expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledWith(file.fileUri);
|
||||
expect(composerAttachmentCleanupMocks.releaseUploads).toHaveBeenCalledWith(
|
||||
file.uploadEnvironmentId,
|
||||
[file.uploadedAttachmentId],
|
||||
);
|
||||
});
|
||||
|
||||
it("hydrates persisted drafts before a cold-start sweep deletes their files", async () => {
|
||||
const file = {
|
||||
id: "file-cold-start",
|
||||
|
||||
@@ -54,6 +54,8 @@ const harness = vi.hoisted(() => ({
|
||||
})(),
|
||||
}));
|
||||
|
||||
vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
|
||||
|
||||
vi.mock("expo-file-system", () => ({
|
||||
Directory: harness.draftFile.Directory,
|
||||
File: harness.draftFile.File,
|
||||
@@ -113,7 +115,7 @@ vi.mock("./thread-outbox", async () => {
|
||||
harness.manager = createThreadOutboxManager({
|
||||
registry: appAtomRegistry,
|
||||
storage: {
|
||||
load: async () => [],
|
||||
load: async () => ({ messages: [], errors: [] }),
|
||||
write: async () => undefined,
|
||||
remove: (message) => harness.removeOutboxMessage(message),
|
||||
},
|
||||
@@ -122,7 +124,6 @@ vi.mock("./thread-outbox", async () => {
|
||||
return {
|
||||
threadOutboxManager: manager,
|
||||
flushThreadOutbox: async () => undefined,
|
||||
ensureThreadOutboxLoaded: () => undefined,
|
||||
confirmThreadOutboxMessageQueued: (message: never) => manager.confirmQueued(message),
|
||||
updateThreadOutboxMessage: (message: never, expectedRevision?: number) =>
|
||||
manager.update(message, expectedRevision),
|
||||
@@ -219,7 +220,6 @@ describe("thread outbox attachment preparation", () => {
|
||||
);
|
||||
const preparationStarted = Promise.withResolvers<void>();
|
||||
const preparationBarrier = Promise.withResolvers<PreparedTurnAttachments>();
|
||||
const releaseUploads = vi.fn(async () => undefined);
|
||||
harness.prepareTurnAttachments.mockImplementationOnce(async () => {
|
||||
preparationStarted.resolve();
|
||||
return preparationBarrier.promise;
|
||||
@@ -237,12 +237,10 @@ describe("thread outbox attachment preparation", () => {
|
||||
attachments: [],
|
||||
draftAttachments: message.attachments,
|
||||
pendingAttachmentIds: ["pending-reused-upload"],
|
||||
releaseUploads,
|
||||
});
|
||||
|
||||
await expect(preparation).resolves.toEqual({ status: "abandoned" });
|
||||
expect(remainingMessages()).toEqual([edited]);
|
||||
expect(releaseUploads).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps an unchanged queued payload ready after attachment reuse", async () => {
|
||||
@@ -254,13 +252,11 @@ describe("thread outbox attachment preparation", () => {
|
||||
}),
|
||||
"pending-reused-upload",
|
||||
);
|
||||
const releaseUploads = vi.fn(async () => undefined);
|
||||
harness.prepareTurnAttachments.mockResolvedValueOnce({
|
||||
status: "ready",
|
||||
attachments: [],
|
||||
draftAttachments: message.attachments,
|
||||
pendingAttachmentIds: ["pending-reused-upload"],
|
||||
releaseUploads,
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
const revision = harness.manager.revisionOf(message.messageId);
|
||||
@@ -271,7 +267,6 @@ describe("thread outbox attachment preparation", () => {
|
||||
persistedMessage: message,
|
||||
deliveryRevision: revision,
|
||||
});
|
||||
expect(releaseUploads).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the known next revision after persisting uploaded references", async () => {
|
||||
@@ -296,7 +291,6 @@ describe("thread outbox attachment preparation", () => {
|
||||
attachments: [],
|
||||
draftAttachments: uploadedAttachments,
|
||||
pendingAttachmentIds: ["pending-new-upload"],
|
||||
releaseUploads: async () => undefined,
|
||||
};
|
||||
});
|
||||
await harness.manager.enqueue(message);
|
||||
|
||||
@@ -15,6 +15,7 @@ import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Alert } from "react-native";
|
||||
|
||||
import { scopedProjectKey, scopedThreadKey } from "../lib/scopedEntities";
|
||||
import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn";
|
||||
@@ -26,7 +27,6 @@ import { useProjects, useServerConfigs, useThreadShells } from "./entities";
|
||||
import { serverEnvironment } from "./server";
|
||||
import {
|
||||
confirmThreadOutboxMessageQueued,
|
||||
ensureThreadOutboxLoaded,
|
||||
threadOutboxManager,
|
||||
threadOutboxRevision,
|
||||
updateThreadOutboxMessage,
|
||||
@@ -583,8 +583,21 @@ export function useThreadOutboxDrain(): void {
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
ensureThreadOutboxLoaded();
|
||||
let mounted = true;
|
||||
const load = async () => {
|
||||
if ((await threadOutboxManager.load()) || !mounted) return;
|
||||
Alert.alert(
|
||||
"Some queued messages could not be loaded",
|
||||
"Unreadable records and attachment files are still saved. Other messages can still be sent.",
|
||||
[
|
||||
{ text: "Dismiss", style: "cancel" },
|
||||
{ text: "Retry", onPress: () => void load() },
|
||||
],
|
||||
);
|
||||
};
|
||||
void load();
|
||||
return () => {
|
||||
mounted = false;
|
||||
for (const timer of retryTimersRef.current.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
@@ -766,12 +779,6 @@ export function useThreadOutboxDrain(): void {
|
||||
(await completeQueuedMessageDelivery(persistedMessage, deliveryRevision)) === "removed";
|
||||
if (delivered) {
|
||||
acknowledgedExistingThreadMessageIdsRef.current.delete(persistedMessage.messageId);
|
||||
// The delivered turn holds its own copy of the bytes. A failed delete
|
||||
// is surfaced (never fails the delivered turn); the server also
|
||||
// expires leaked pending uploads.
|
||||
await prepared.releaseUploads().catch((error) => {
|
||||
console.warn("[thread-outbox] could not delete consumed pending uploads", error);
|
||||
});
|
||||
}
|
||||
return delivered;
|
||||
},
|
||||
@@ -904,13 +911,7 @@ export function useThreadOutboxDrain(): void {
|
||||
// payload as a duplicate creation. Hand it to the thread's composer.
|
||||
return recoverEditedCreationAfterDelivery(persistedMessage);
|
||||
}
|
||||
if (outcome === "removed") {
|
||||
await prepared.releaseUploads().catch((error) => {
|
||||
console.warn("[thread-outbox] could not delete consumed pending uploads", error);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return outcome === "removed";
|
||||
},
|
||||
[makeDeliveryHelpers, restoreQueuedMessage, startTurn],
|
||||
);
|
||||
|
||||
@@ -566,15 +566,20 @@ const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")(
|
||||
}
|
||||
}
|
||||
const fileInfo = opened.info;
|
||||
const mimeType = Mime.getType(filePath) ?? "application/octet-stream";
|
||||
const isHtml = mimeType === "text/html";
|
||||
|
||||
// A hash-like name is not enough: custom static files can use the same naming pattern.
|
||||
const relativePath = path.relative(staticRoot, filePath).replaceAll("\\", "/");
|
||||
const immutable =
|
||||
/^assets\/.+-[\w-]{8}\.[^/]+$/.test(relativePath) && immutableBuildAssets.has(relativePath);
|
||||
!isHtml &&
|
||||
/^assets\/.+-[\w-]{8}\.[^/]+$/.test(relativePath) &&
|
||||
immutableBuildAssets.has(relativePath);
|
||||
const headers: Record<string, string> = {
|
||||
"Cache-Control": immutable ? "public, max-age=31536000, immutable" : "no-cache",
|
||||
};
|
||||
const modifiedAt = Option.getOrUndefined(fileInfo.mtime);
|
||||
// Deployments can preserve HTML size and mtime while changing its bundle URLs.
|
||||
const modifiedAt = isHtml ? undefined : Option.getOrUndefined(fileInfo.mtime);
|
||||
const etag = modifiedAt
|
||||
? `W/"${fileInfo.size.toString(16)}-${modifiedAt.getTime().toString(16)}"`
|
||||
: undefined;
|
||||
@@ -599,17 +604,14 @@ const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")(
|
||||
: ifModifiedSince !== undefined &&
|
||||
modifiedAt !== undefined &&
|
||||
Date.parse(modifiedAt.toUTCString()) <= Date.parse(ifModifiedSince);
|
||||
if (unchanged) {
|
||||
if (!isHtml && unchanged) {
|
||||
return HttpServerResponse.empty({
|
||||
status: 304,
|
||||
headers: { ...headers, Vary: "Accept-Encoding" },
|
||||
});
|
||||
}
|
||||
|
||||
const contentType =
|
||||
path.extname(filePath) === ".html"
|
||||
? "text/html; charset=utf-8"
|
||||
: (Mime.getType(filePath) ?? "application/octet-stream");
|
||||
const contentType = isHtml ? "text/html; charset=utf-8" : mimeType;
|
||||
// The request scope closes the handle for GET, HEAD, 304, errors, and cancellation.
|
||||
// HEAD still passes through compression, which selects headers without reading the stream.
|
||||
return HttpServerResponse.stream(streamStaticFile(opened.file, fileInfo.size), {
|
||||
|
||||
@@ -93,7 +93,7 @@ export const makeLiveStreamBudget = Effect.fn("makeLiveStreamBudget")(function*
|
||||
return Effect.succeed(item);
|
||||
});
|
||||
|
||||
// Replace one coalescing batch atomically. Both raw and projected payloads
|
||||
// Replace one coalescing batch atomically. Queued and coalesced payloads
|
||||
// count against the same budget, and discarded updates release their charge.
|
||||
const replace = <A extends object>(
|
||||
previous: ReadonlyArray<RetainedLiveItem<unknown>>,
|
||||
|
||||
@@ -130,7 +130,7 @@ export const makeThreadLiveEventCoalescer = Effect.fn("makeThreadLiveEventCoales
|
||||
pendingUpdates,
|
||||
coalesceLiveToolUpdatedEvents(pendingUpdates.map((item) => item.value)).map((event) => ({
|
||||
kind: "event" as const,
|
||||
event: projectActivityEvent(event),
|
||||
event,
|
||||
})),
|
||||
(item) => item.event,
|
||||
);
|
||||
@@ -167,7 +167,8 @@ export const makeThreadLiveEventCoalescer = Effect.fn("makeThreadLiveEventCoales
|
||||
Effect.gen(function* () {
|
||||
yield* budget.check;
|
||||
if (input.kind === "event") {
|
||||
yield* budget.retain(input.event).pipe(
|
||||
// Retain only the client payload, not full persisted tool output.
|
||||
yield* budget.retain(projectActivityEvent(input.event)).pipe(
|
||||
Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))),
|
||||
Effect.uninterruptible,
|
||||
);
|
||||
|
||||
+153
-15
@@ -1688,14 +1688,14 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const staticDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-static-cache-" });
|
||||
const indexPath = path.join(staticDir, "index.html");
|
||||
yield* fileSystem.writeFileString(indexPath, "<html>first build</html>");
|
||||
const assetPath = path.join(staticDir, "app.js");
|
||||
yield* fileSystem.writeFileString(assetPath, 'export const build = "first";');
|
||||
yield* buildAppUnderTest({ config: { staticDir } });
|
||||
|
||||
const initial = yield* HttpClient.get("/");
|
||||
const initial = yield* HttpClient.get("/app.js");
|
||||
assert.equal(initial.status, 200);
|
||||
assert.equal(initial.headers["cache-control"], "no-cache");
|
||||
assert.include(yield* initial.text, "first build");
|
||||
assert.include(yield* initial.text, "first");
|
||||
const etag = initial.headers.etag;
|
||||
assert.isDefined(etag);
|
||||
assert.isDefined(initial.headers["last-modified"]);
|
||||
@@ -1706,30 +1706,70 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
{ "if-none-match": "*" },
|
||||
{ "if-modified-since": initial.headers["last-modified"]! },
|
||||
]) {
|
||||
const response = yield* HttpClient.get("/", { headers });
|
||||
const response = yield* HttpClient.get("/app.js", { headers });
|
||||
assert.equal(response.status, 304);
|
||||
assert.equal(response.headers.etag, etag);
|
||||
assert.equal(response.headers["cache-control"], "no-cache");
|
||||
assert.equal(yield* response.text, "");
|
||||
}
|
||||
|
||||
const mismatched = yield* HttpClient.get("/", {
|
||||
const mismatched = yield* HttpClient.get("/app.js", {
|
||||
headers: {
|
||||
"if-none-match": '"another-build"',
|
||||
"if-modified-since": initial.headers["last-modified"]!,
|
||||
},
|
||||
});
|
||||
assert.equal(mismatched.status, 200);
|
||||
assert.include(yield* mismatched.text, "first build");
|
||||
assert.include(yield* mismatched.text, "first");
|
||||
|
||||
yield* fileSystem.writeFileString(indexPath, "<html>the next build is available</html>");
|
||||
const changed = yield* HttpClient.get("/", { headers: { "if-none-match": etag! } });
|
||||
yield* fileSystem.writeFileString(assetPath, 'export const build = "the next build";');
|
||||
const changed = yield* HttpClient.get("/app.js", { headers: { "if-none-match": etag! } });
|
||||
assert.equal(changed.status, 200);
|
||||
assert.notEqual(changed.headers.etag, etag);
|
||||
assert.include(yield* changed.text, "next build");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("serves changed HTML with the same size and timestamp", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const staticDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-static-html-" });
|
||||
const indexPath = path.join(staticDir, "index.html");
|
||||
const modifiedAt = DateTime.toDateUtc(DateTime.makeUnsafe("1985-10-26T08:15:00.000Z"));
|
||||
yield* fileSystem.writeFileString(indexPath, "<html>old build</html>");
|
||||
yield* fileSystem.utimes(indexPath, modifiedAt, modifiedAt);
|
||||
yield* buildAppUnderTest({ config: { staticDir } });
|
||||
|
||||
const initial = yield* HttpClient.get("/");
|
||||
assert.equal(yield* initial.text, "<html>old build</html>");
|
||||
const previousEtag = initial.headers.etag ?? '"previous-html"';
|
||||
const nextHtml = "<html>new build</html>";
|
||||
yield* fileSystem.writeFileString(indexPath, nextHtml);
|
||||
yield* fileSystem.utimes(indexPath, modifiedAt, modifiedAt);
|
||||
|
||||
for (const [resource, headers] of [
|
||||
["/", { "if-none-match": previousEtag }],
|
||||
["/threads/example", { "if-modified-since": modifiedAt.toUTCString() }],
|
||||
["/", { "if-none-match": "*" }],
|
||||
] as const) {
|
||||
const response = yield* HttpClient.get(resource, { headers });
|
||||
assert.equal(response.status, 200);
|
||||
assert.equal(yield* response.text, nextHtml);
|
||||
assert.equal(response.headers["cache-control"], "no-cache");
|
||||
assert.isUndefined(response.headers.etag);
|
||||
assert.isUndefined(response.headers["last-modified"]);
|
||||
}
|
||||
|
||||
const head = yield* HttpClient.head("/", {
|
||||
headers: { "if-none-match": previousEtag, "accept-encoding": "identity" },
|
||||
});
|
||||
assert.equal(head.status, 200);
|
||||
assert.equal(head.headers["content-length"], String(Buffer.byteLength(nextHtml)));
|
||||
assert.equal(yield* head.text, "");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("caches hashed static assets without freezing mutable files or SPA fallbacks", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -1917,8 +1957,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const staticDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-static-close-" });
|
||||
const filePath = path.join(staticDir, "index.html");
|
||||
const body = "<p>file content</p>".repeat(1024);
|
||||
const filePath = path.join(staticDir, "app.txt");
|
||||
const body = "file content\n".repeat(1024);
|
||||
yield* fileSystem.writeFileString(filePath, body);
|
||||
const closed = yield* Queue.unbounded<FileSystem.File>();
|
||||
const blocked = yield* Deferred.make<void>();
|
||||
@@ -1963,14 +2003,14 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.provideService(FileSystem.FileSystem, trackedFileSystem),
|
||||
);
|
||||
|
||||
const get = yield* HttpClient.get("/");
|
||||
const get = yield* HttpClient.get("/app.txt");
|
||||
assert.equal(yield* get.text, body);
|
||||
yield* Queue.take(closed);
|
||||
assert.equal(active.size, 0);
|
||||
assert.isAbove(bodyReads, 0);
|
||||
const readsAfterGet = bodyReads;
|
||||
|
||||
const head = yield* HttpClient.head("/", { headers: { "accept-encoding": "gzip" } });
|
||||
const head = yield* HttpClient.head("/app.txt", { headers: { "accept-encoding": "gzip" } });
|
||||
assert.equal(head.status, 200);
|
||||
assert.equal(head.headers["content-encoding"], "gzip");
|
||||
assert.equal(yield* head.text, "");
|
||||
@@ -1978,7 +2018,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.equal(active.size, 0);
|
||||
assert.equal(bodyReads, readsAfterGet);
|
||||
|
||||
const unchanged = yield* HttpClient.get("/", {
|
||||
const unchanged = yield* HttpClient.get("/app.txt", {
|
||||
headers: { "if-none-match": get.headers.etag! },
|
||||
});
|
||||
assert.equal(unchanged.status, 304);
|
||||
@@ -1987,7 +2027,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.equal(bodyReads, readsAfterGet);
|
||||
|
||||
blockAfterOpen = true;
|
||||
const cancelled = yield* HttpClient.get("/").pipe(Effect.forkChild);
|
||||
const cancelled = yield* HttpClient.get("/app.txt").pipe(Effect.forkChild);
|
||||
yield* Deferred.await(blocked);
|
||||
assert.equal(active.size, 1);
|
||||
yield* Fiber.interrupt(cancelled);
|
||||
@@ -7866,6 +7906,104 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
for (const subscription of ["thread", "shell"] as const) {
|
||||
it.effect("delivers large raw tool results through the " + subscription + " stream", () =>
|
||||
Effect.gen(function* () {
|
||||
const eventThreadId =
|
||||
subscription === "thread" ? defaultThreadId : ThreadId.make("other-live-thread");
|
||||
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
|
||||
const baseEvent = makeLiveToolActivityEvent(2, "tool.completed");
|
||||
const event: OrchestrationEvent = {
|
||||
...baseEvent,
|
||||
aggregateId: eventThreadId,
|
||||
payload: {
|
||||
threadId: eventThreadId,
|
||||
activity: {
|
||||
...baseEvent.payload.activity,
|
||||
summary: "Build complete",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
toolCallId: "call-build",
|
||||
status: "completed",
|
||||
title: "Build complete",
|
||||
data: {
|
||||
item: {
|
||||
command: "build",
|
||||
aggregatedOutput: "Build complete\n" + "x".repeat(9 * 1024 * 1024),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
streamDomainEvents: Stream.concat(Stream.make(event), Stream.never),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadDetailSnapshot: () =>
|
||||
Effect.succeed(Option.some({ snapshotSequence: 1, thread })),
|
||||
getThreadShellById: (threadId) =>
|
||||
Effect.succeed(
|
||||
Option.some({
|
||||
...makeDefaultOrchestrationThreadShell(),
|
||||
id: threadId,
|
||||
title: "Build complete",
|
||||
}),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const items =
|
||||
subscription === "thread"
|
||||
? yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
|
||||
threadId: defaultThreadId,
|
||||
requestCompletionMarker: true,
|
||||
}).pipe(
|
||||
Stream.takeUntil((item) => item.kind === "synchronized"),
|
||||
Stream.runCollect,
|
||||
),
|
||||
),
|
||||
)
|
||||
: yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.subscribeShell]({
|
||||
requestCompletionMarker: true,
|
||||
}).pipe(
|
||||
Stream.takeUntil((item) => item.kind === "synchronized"),
|
||||
Stream.runCollect,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(items[0]?.kind, "snapshot");
|
||||
const update = items[1];
|
||||
if (subscription === "thread") {
|
||||
assertTrue(update?.kind === "event" && update.event.type === "thread.activity-appended");
|
||||
assert.equal(update.event.sequence, 2);
|
||||
assert.deepEqual(update.event.payload.activity.payload, {
|
||||
itemType: "command_execution",
|
||||
toolCallId: "call-build",
|
||||
status: "completed",
|
||||
title: "Build complete",
|
||||
data: { item: { command: "build", aggregatedOutput: "Build complete" } },
|
||||
});
|
||||
} else {
|
||||
assertTrue(update?.kind === "thread-upserted");
|
||||
assert.equal(update.sequence, 2);
|
||||
assert.equal(update.thread.id, eventThreadId);
|
||||
assert.equal(update.thread.title, "Build complete");
|
||||
}
|
||||
assert.deepEqual(items[2], { kind: "synchronized" });
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("coalesces buffered live tool updates to the latest state", () =>
|
||||
Effect.gen(function* () {
|
||||
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
|
||||
|
||||
+27
-11
@@ -38,7 +38,7 @@ import {
|
||||
OrchestrationSearchThreadsError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ProjectId,
|
||||
ProjectId,
|
||||
type ProjectEntriesFailure,
|
||||
type ProjectFileFailure,
|
||||
type ProjectFileOperation,
|
||||
@@ -723,19 +723,33 @@ const makeWsRpcLayer = (
|
||||
});
|
||||
};
|
||||
|
||||
// Shell updates refetch the aggregate. Message and tool bodies are not needed.
|
||||
const toShellEvent = ({
|
||||
type,
|
||||
aggregateKind,
|
||||
aggregateId,
|
||||
sequence,
|
||||
}: OrchestrationEvent) => ({
|
||||
type,
|
||||
aggregateKind,
|
||||
aggregateId,
|
||||
sequence,
|
||||
});
|
||||
type ShellEvent = ReturnType<typeof toShellEvent>;
|
||||
|
||||
const toShellStreamEvent = (
|
||||
event: OrchestrationEvent,
|
||||
event: ShellEvent,
|
||||
): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> => {
|
||||
switch (event.type) {
|
||||
case "project.created":
|
||||
case "project.meta-updated":
|
||||
return projectUpsertOrRemove(event.payload.projectId, event.sequence);
|
||||
return projectUpsertOrRemove(ProjectId.make(event.aggregateId), event.sequence);
|
||||
case "project.deleted":
|
||||
return Effect.succeed(
|
||||
Option.some({
|
||||
kind: "project-removed" as const,
|
||||
sequence: event.sequence,
|
||||
projectId: event.payload.projectId,
|
||||
projectId: ProjectId.make(event.aggregateId),
|
||||
}),
|
||||
);
|
||||
case "thread.deleted":
|
||||
@@ -744,11 +758,11 @@ const makeWsRpcLayer = (
|
||||
Option.some({
|
||||
kind: "thread-removed" as const,
|
||||
sequence: event.sequence,
|
||||
threadId: event.payload.threadId,
|
||||
threadId: ThreadId.make(event.aggregateId),
|
||||
}),
|
||||
);
|
||||
case "thread.unarchived":
|
||||
return threadUpsertOrRemove(event.payload.threadId, event.sequence);
|
||||
return threadUpsertOrRemove(ThreadId.make(event.aggregateId), event.sequence);
|
||||
default:
|
||||
if (event.aggregateKind !== "thread") {
|
||||
return Effect.succeed(Option.none());
|
||||
@@ -862,13 +876,13 @@ const makeWsRpcLayer = (
|
||||
// item. The refetch runs with bounded concurrency (order-preserving).
|
||||
const SHELL_REFETCH_CONCURRENCY = 8;
|
||||
const coalesceShellEvents = (
|
||||
events: ReadonlyArray<OrchestrationEvent>,
|
||||
events: ReadonlyArray<ShellEvent>,
|
||||
): Effect.Effect<ReadonlyArray<OrchestrationShellStreamEvent>, never, never> =>
|
||||
Effect.gen(function* () {
|
||||
if (events.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const latestByAggregate = new Map<string, OrchestrationEvent>();
|
||||
const latestByAggregate = new Map<string, ShellEvent>();
|
||||
for (const event of events) {
|
||||
latestByAggregate.set(`${event.aggregateKind}:${event.aggregateId}`, event);
|
||||
}
|
||||
@@ -891,16 +905,17 @@ const makeWsRpcLayer = (
|
||||
stream: Stream.Stream<OrchestrationEvent, E, R>,
|
||||
): Stream.Stream<OrchestrationShellStreamEvent, E, R> =>
|
||||
stream.pipe(
|
||||
Stream.map(toShellEvent),
|
||||
Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW),
|
||||
Stream.mapEffect(coalesceShellEvents),
|
||||
Stream.flatMap((items) => Stream.fromIterable(items)),
|
||||
);
|
||||
|
||||
type ShellLiveInput =
|
||||
| { readonly kind: "event"; readonly event: OrchestrationEvent }
|
||||
| { readonly kind: "event"; readonly event: ShellEvent }
|
||||
| { readonly kind: "synchronized" };
|
||||
|
||||
// A completion marker is queued alongside raw live events so it cannot
|
||||
// A completion marker is queued alongside live event metadata so it cannot
|
||||
// overtake an event still waiting in the coalescing window. Split each
|
||||
// batch at markers and coalesce only the event segments on either side.
|
||||
const coalesceShellLiveInputs = (
|
||||
@@ -908,7 +923,7 @@ const makeWsRpcLayer = (
|
||||
): Effect.Effect<ReadonlyArray<OrchestrationShellStreamItem>, never, never> =>
|
||||
Effect.gen(function* () {
|
||||
const output: Array<OrchestrationShellStreamItem> = [];
|
||||
let pendingEvents: Array<OrchestrationEvent> = [];
|
||||
let pendingEvents: Array<ShellEvent> = [];
|
||||
|
||||
for (const input of inputs) {
|
||||
if (input.kind === "event") {
|
||||
@@ -1430,6 +1445,7 @@ const makeWsRpcLayer = (
|
||||
);
|
||||
yield* Effect.forkScoped(
|
||||
orchestrationEngine.streamDomainEvents.pipe(
|
||||
Stream.map(toShellEvent),
|
||||
Stream.runForEach((event) =>
|
||||
liveBudget.retain({ kind: "event" as const, event }, event).pipe(
|
||||
Effect.flatMap((item) => Queue.offer(liveBuffer, item)),
|
||||
|
||||
@@ -104,6 +104,50 @@ describe("ChatMarkdown favicon privacy", () => {
|
||||
});
|
||||
|
||||
describe("ChatMarkdown streaming", () => {
|
||||
it("recovers highlighting after a failed fence changes without resetting its controls", async () => {
|
||||
const highlighter = await getSyntaxHighlighterPromise("text");
|
||||
const codeToHtml = highlighter.codeToHtml.bind(highlighter);
|
||||
let fail = true;
|
||||
vi.spyOn(highlighter, "codeToHtml").mockImplementation((...args) => {
|
||||
if (fail) throw new Error("Temporary highlighter failure");
|
||||
return codeToHtml(...args);
|
||||
});
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
<ChatMarkdown cwd="/tmp/project" text={"```text\ninitial\n```"} isStreaming />,
|
||||
);
|
||||
});
|
||||
const mounted = renderer!;
|
||||
const codeBlock = mounted.root.findByProps({ "data-language": "text" });
|
||||
const initialWrap = codeBlock.props["data-wrap"] === "true";
|
||||
const wrap = codeButton(mounted, initialWrap ? "Disable line wrap" : "Wrap lines");
|
||||
await act(async () => {
|
||||
wrap.onClick?.({} as Parameters<NonNullable<typeof wrap.onClick>>[0]);
|
||||
});
|
||||
expect(mounted.root.findAllByProps({ className: "chat-markdown-shiki" })).toHaveLength(0);
|
||||
|
||||
fail = false;
|
||||
await act(async () => {
|
||||
mounted.update(
|
||||
<ChatMarkdown cwd="/tmp/project" text={"```text\nrecovered\n```"} isStreaming />,
|
||||
);
|
||||
});
|
||||
expect(mounted.root.findAllByProps({ className: "chat-markdown-shiki" })).toHaveLength(1);
|
||||
expect(mounted.root.findByProps({ "data-language": "text" })).toBe(codeBlock);
|
||||
expect(codeBlock.props["data-wrap"]).toBe(String(!initialWrap));
|
||||
} finally {
|
||||
await act(async () => renderer?.unmount());
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves code controls and details without highlighting an unchanged fence again", async () => {
|
||||
const highlighter = await getSyntaxHighlighterPromise("text");
|
||||
const highlight = vi.spyOn(highlighter, "codeToHtml");
|
||||
|
||||
@@ -2873,7 +2873,10 @@ const CHAT_MARKDOWN_COMPONENTS = {
|
||||
fenceTitle={fenceTitle}
|
||||
theme={resolvedTheme}
|
||||
>
|
||||
<RenderErrorBoundary fallback={<pre {...props}>{children}</pre>}>
|
||||
<RenderErrorBoundary
|
||||
resetKeys={[codeBlock.code, language, diffThemeName, isStreaming]}
|
||||
fallback={<pre {...props}>{children}</pre>}
|
||||
>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
||||
import { WorkerPoolContext, useWorkerPool } from "@pierre/diffs/react";
|
||||
import { WorkerPoolManager } from "@pierre/diffs/worker";
|
||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";
|
||||
@@ -16,6 +24,46 @@ export class DiffWorkerError extends Schema.TaggedErrorClass<DiffWorkerError>()(
|
||||
}
|
||||
}
|
||||
|
||||
const DIFF_WORKER_IDLE_TTL_MS = 30_000;
|
||||
let sharedWorkerPool:
|
||||
| {
|
||||
readonly pool: WorkerPoolManager;
|
||||
consumers: number;
|
||||
idleTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
/** Create workers after a viewer commits, then reuse them across short panel closures. */
|
||||
function acquireDiffWorkerPool(themeName: DiffThemeName, poolSize: number) {
|
||||
const entry = (sharedWorkerPool ??= {
|
||||
pool: new WorkerPoolManager(
|
||||
{
|
||||
workerFactory: () => {
|
||||
try {
|
||||
return new DiffsWorker();
|
||||
} catch (cause) {
|
||||
throw new DiffWorkerError({ operation: "create-worker", themeName, cause });
|
||||
}
|
||||
},
|
||||
poolSize,
|
||||
totalASTLRUCacheSize: 240,
|
||||
},
|
||||
{
|
||||
theme: themeName,
|
||||
preferredHighlighter: PREFERRED_HIGHLIGHTER,
|
||||
tokenizeMaxLineLength: 1_000,
|
||||
useTokenTransformer: true,
|
||||
},
|
||||
),
|
||||
consumers: 0,
|
||||
idleTimer: undefined,
|
||||
});
|
||||
clearTimeout(entry.idleTimer);
|
||||
entry.idleTimer = undefined;
|
||||
entry.consumers += 1;
|
||||
return entry;
|
||||
}
|
||||
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
const workerPool = useWorkerPool();
|
||||
|
||||
@@ -49,16 +97,17 @@ function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
// Plain-text views do not queue a highlight task that could retry a blank first render.
|
||||
function DiffWorkerReady({ children }: { children?: ReactNode }) {
|
||||
const workerPool = useWorkerPool();
|
||||
const [ready, setReady] = useState(
|
||||
() => !workerPool || workerPool.isInitialized() || !workerPool.isWorkingPool(),
|
||||
);
|
||||
const [readyPool, setReadyPool] = useState<WorkerPoolManager>();
|
||||
const ready = workerPool
|
||||
? readyPool === workerPool || workerPool.isInitialized() || !workerPool.isWorkingPool()
|
||||
: typeof window === "undefined";
|
||||
|
||||
useEffect(() => {
|
||||
if (ready || !workerPool) return;
|
||||
|
||||
let mounted = true;
|
||||
const finish = () => {
|
||||
if (mounted) setReady(true);
|
||||
if (mounted) setReadyPool(workerPool);
|
||||
};
|
||||
// Failed pools use Pierre's existing main-thread highlighter.
|
||||
void workerPool.initialize().then(finish, finish);
|
||||
@@ -87,33 +136,32 @@ export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
||||
return Math.max(2, Math.min(6, Math.floor(cores / 2)));
|
||||
}, []);
|
||||
const workerPool = useSyncExternalStore(
|
||||
useCallback(
|
||||
(onStoreChange) => {
|
||||
if (typeof window === "undefined") return () => {};
|
||||
const entry = acquireDiffWorkerPool(diffThemeName, workerPoolSize);
|
||||
onStoreChange();
|
||||
return () => {
|
||||
entry.consumers -= 1;
|
||||
if (entry.consumers !== 0) return;
|
||||
entry.idleTimer = setTimeout(() => {
|
||||
entry.idleTimer = undefined;
|
||||
entry.pool.terminate();
|
||||
if (sharedWorkerPool === entry) sharedWorkerPool = undefined;
|
||||
}, DIFF_WORKER_IDLE_TTL_MS);
|
||||
};
|
||||
},
|
||||
[diffThemeName, workerPoolSize],
|
||||
),
|
||||
() => sharedWorkerPool?.pool,
|
||||
() => undefined,
|
||||
);
|
||||
|
||||
return (
|
||||
<WorkerPoolContextProvider
|
||||
poolOptions={{
|
||||
workerFactory: () => {
|
||||
try {
|
||||
return new DiffsWorker();
|
||||
} catch (cause) {
|
||||
throw new DiffWorkerError({
|
||||
operation: "create-worker",
|
||||
themeName: diffThemeName,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
},
|
||||
poolSize: workerPoolSize,
|
||||
totalASTLRUCacheSize: 240,
|
||||
}}
|
||||
highlighterOptions={{
|
||||
theme: diffThemeName,
|
||||
preferredHighlighter: PREFERRED_HIGHLIGHTER,
|
||||
tokenizeMaxLineLength: 1_000,
|
||||
useTokenTransformer: true,
|
||||
}}
|
||||
>
|
||||
<WorkerPoolContext value={workerPool}>
|
||||
<DiffWorkerThemeSync themeName={diffThemeName} />
|
||||
<DiffWorkerReady>{children}</DiffWorkerReady>
|
||||
</WorkerPoolContextProvider>
|
||||
</WorkerPoolContext>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,35 @@
|
||||
import { Component, type ReactNode } from "react";
|
||||
|
||||
interface RenderErrorBoundaryProps {
|
||||
readonly children: ReactNode;
|
||||
readonly fallback: ReactNode;
|
||||
readonly resetKeys?: ReadonlyArray<unknown>;
|
||||
}
|
||||
|
||||
interface RenderErrorBoundaryState {
|
||||
readonly failed: boolean;
|
||||
readonly resetKeys?: ReadonlyArray<unknown> | undefined;
|
||||
}
|
||||
|
||||
export class RenderErrorBoundary extends Component<
|
||||
{ readonly children: ReactNode; readonly fallback: ReactNode },
|
||||
{ readonly failed: boolean }
|
||||
RenderErrorBoundaryProps,
|
||||
RenderErrorBoundaryState
|
||||
> {
|
||||
override state = { failed: false };
|
||||
override state = { failed: false, resetKeys: this.props.resetKeys };
|
||||
|
||||
// Retry changed inputs without remounting healthy children or their controls.
|
||||
static getDerivedStateFromProps(
|
||||
{ resetKeys }: RenderErrorBoundaryProps,
|
||||
state: RenderErrorBoundaryState,
|
||||
) {
|
||||
if (
|
||||
resetKeys?.length !== state.resetKeys?.length ||
|
||||
resetKeys?.some((key, index) => !Object.is(key, state.resetKeys?.[index]))
|
||||
) {
|
||||
return { failed: false, resetKeys };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static getDerivedStateFromError() {
|
||||
return { failed: true };
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { LoaderCircleIcon } from "lucide-react";
|
||||
import { observeVisibleAnimation } from "../../lib/visibleAnimation";
|
||||
import { threadSyncLabel, type ThreadSyncPhase } from "../../threadSync";
|
||||
import { ComposerBanner } from "./ComposerBanner";
|
||||
|
||||
export function ComposerActivityRow({ phase }: { readonly phase: ThreadSyncPhase }) {
|
||||
return (
|
||||
<ComposerBanner.Row>
|
||||
<ComposerBanner.Icon>
|
||||
<LoaderCircleIcon />
|
||||
<ComposerBanner.Icon ref={observeVisibleAnimation}>
|
||||
<LoaderCircleIcon className="motion-safe:visible-animate-spin" />
|
||||
</ComposerBanner.Icon>
|
||||
<ComposerBanner.Content>
|
||||
<span
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
|
||||
import { CircleAlertIcon, DownloadIcon, LoaderCircleIcon } from "lucide-react";
|
||||
import { useId, useState } from "react";
|
||||
|
||||
import { observeVisibleAnimation } from "../../lib/visibleAnimation";
|
||||
import { serverUpdateStageLabel } from "../ServerUpdateAction";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { ComposerBanner } from "./ComposerBanner";
|
||||
@@ -12,7 +13,13 @@ export function ComposerServerUpdateIcon({
|
||||
readonly status: ServerUpdateState["status"];
|
||||
}) {
|
||||
if (status === "running") {
|
||||
return <LoaderCircleIcon aria-hidden />;
|
||||
return (
|
||||
<LoaderCircleIcon
|
||||
aria-hidden
|
||||
ref={observeVisibleAnimation}
|
||||
className="motion-safe:visible-animate-spin"
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (status === "failed") {
|
||||
return <CircleAlertIcon aria-hidden className="text-error" />;
|
||||
|
||||
@@ -28,6 +28,7 @@ const NOOP_OPEN_ATTACHMENT = (_attachment: ChatFileAttachment) => {};
|
||||
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { toolActivityFaviconUrl } from "@t3tools/shared/favicon";
|
||||
import { getProjectFaviconCacheKey } from "@t3tools/shared/projectFavicon";
|
||||
import { observeVisibleAnimation } from "../../lib/visibleAnimation";
|
||||
import {
|
||||
createContext,
|
||||
Fragment,
|
||||
@@ -1652,12 +1653,21 @@ function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "workin
|
||||
<div className="flex h-6 min-w-0 items-baseline px-1 text-sm leading-relaxed text-muted-foreground tabular-nums">
|
||||
<span
|
||||
key={isPreparingWorktree ? "setup" : isCompacting ? "compacting" : "working"}
|
||||
ref={isPreparingWorktree || isCompacting ? observeVisibleAnimation : undefined}
|
||||
className="relative shrink-0 overflow-hidden whitespace-nowrap transition-opacity duration-150 starting:opacity-0 motion-reduce:transition-none"
|
||||
>
|
||||
{isPreparingWorktree ? (
|
||||
"Setting up worktree…"
|
||||
<>
|
||||
Setting up worktree…
|
||||
<ActivityShimmerOverlay>Setting up worktree…</ActivityShimmerOverlay>
|
||||
</>
|
||||
) : isCompacting ? (
|
||||
<CompactingLabel />
|
||||
<>
|
||||
<CompactingLabel />
|
||||
<ActivityShimmerOverlay>
|
||||
<CompactingLabel />
|
||||
</ActivityShimmerOverlay>
|
||||
</>
|
||||
) : row.createdAt ? (
|
||||
<>
|
||||
Working for <WorkingTimer createdAt={row.createdAt} />
|
||||
@@ -1677,7 +1687,7 @@ function ThinkingTimelineRow() {
|
||||
return (
|
||||
<div className="min-h-7">
|
||||
{isPreparingWorktree || isCompacting ? null : (
|
||||
<LiveActivityRow label="Thinking" iconName="brain" />
|
||||
<LiveActivityRow label="Thinking" iconName="brain" active shimmer />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -1919,6 +1929,19 @@ function ExpandedWorkGroupEntries({
|
||||
|
||||
const workEntryKey = (entry: TimelineWorkEntry) => entry.id;
|
||||
|
||||
function ActivityShimmerOverlay({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className="live-activity-focus pointer-events-none absolute inset-y-0 select-none"
|
||||
>
|
||||
<span className="live-activity-focus-counter block">
|
||||
<span className="live-activity-focus-aligned block text-foreground">{children}</span>
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const failedToolIconClassName = "text-tool-error-icon/40";
|
||||
|
||||
/** Image icons and the gradient computer-use mark cannot take a currentColor
|
||||
@@ -1936,23 +1959,35 @@ function LiveActivityRow({
|
||||
toolIcon,
|
||||
failed = false,
|
||||
active = false,
|
||||
shimmer = false,
|
||||
}: {
|
||||
label: string;
|
||||
iconName?: WorkEntryIconName;
|
||||
toolIcon?: ToolActivityIcon | undefined;
|
||||
failed?: boolean;
|
||||
active?: boolean;
|
||||
shimmer?: boolean;
|
||||
}) {
|
||||
const animated = active && !failed;
|
||||
const showShimmer = animated && shimmer;
|
||||
return (
|
||||
<div className="min-h-6 w-fit max-w-full min-w-0 overflow-hidden rounded-md text-sm leading-relaxed">
|
||||
<div
|
||||
ref={animated ? observeVisibleAnimation : undefined}
|
||||
className="relative min-h-6 w-fit max-w-full min-w-0 overflow-hidden rounded-md text-sm leading-relaxed"
|
||||
>
|
||||
<LiveActivityContent
|
||||
label={label}
|
||||
iconName={iconName}
|
||||
toolIcon={toolIcon}
|
||||
failed={failed}
|
||||
announceFailure={failed}
|
||||
active={active}
|
||||
active={animated && !shimmer}
|
||||
/>
|
||||
{showShimmer ? (
|
||||
<ActivityShimmerOverlay>
|
||||
<LiveActivityContent label={label} iconName={iconName} toolIcon={toolIcon} highlighted />
|
||||
</ActivityShimmerOverlay>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1964,6 +1999,7 @@ function LiveActivityContent({
|
||||
failed = false,
|
||||
announceFailure = false,
|
||||
active = false,
|
||||
highlighted = false,
|
||||
}: {
|
||||
label: string;
|
||||
iconName: WorkEntryIconName | undefined;
|
||||
@@ -1971,6 +2007,7 @@ function LiveActivityContent({
|
||||
failed?: boolean;
|
||||
announceFailure?: boolean;
|
||||
active?: boolean;
|
||||
highlighted?: boolean;
|
||||
}) {
|
||||
const showTrailingFailureMark =
|
||||
failed && iconName !== undefined && !toolIconAcceptsTint(iconName, toolIcon);
|
||||
@@ -1980,14 +2017,14 @@ function LiveActivityContent({
|
||||
className={cn(
|
||||
"flex min-h-6 min-w-0 items-center gap-1.5 py-0.5",
|
||||
iconName ? "px-0.5" : "px-1",
|
||||
"text-secondary-label",
|
||||
highlighted ? "text-foreground" : "text-secondary-label",
|
||||
)}
|
||||
>
|
||||
{iconName ? (
|
||||
<span
|
||||
className={cn(
|
||||
"flex size-6 shrink-0 items-center justify-center",
|
||||
failed ? failedToolIconClassName : "text-icon-muted",
|
||||
failed ? failedToolIconClassName : highlighted ? "text-foreground" : "text-icon-muted",
|
||||
)}
|
||||
role={announceFailure ? "img" : undefined}
|
||||
aria-label={announceFailure ? "Tool call failed" : undefined}
|
||||
@@ -1996,7 +2033,7 @@ function LiveActivityContent({
|
||||
icon={toolIcon}
|
||||
fallbackName={iconName}
|
||||
className="block size-4 shrink-0 stroke-[1.8]"
|
||||
muted
|
||||
muted={!highlighted}
|
||||
/>
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useWorkerPool, type CodeViewProps } from "@pierre/diffs/react";
|
||||
import { WorkerPoolManager, type WorkerRequest, type WorkerResponse } from "@pierre/diffs/worker";
|
||||
import {
|
||||
act,
|
||||
StrictMode,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
@@ -149,6 +150,14 @@ function Views({ count }: { count: number }) {
|
||||
);
|
||||
}
|
||||
|
||||
function renderViews(count: number) {
|
||||
return (
|
||||
<StrictMode>
|
||||
<Views count={count} />
|
||||
</StrictMode>
|
||||
);
|
||||
}
|
||||
|
||||
describe("StyledDiffCodeView", () => {
|
||||
beforeEach(() => {
|
||||
testState.codeViewClassName = null;
|
||||
@@ -208,6 +217,7 @@ describe("code-view worker lifecycle", () => {
|
||||
vi.stubGlobal("window", {});
|
||||
vi.stubGlobal("navigator", { hardwareConcurrency: 2 });
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) =>
|
||||
setImmediate(() => callback(0)),
|
||||
);
|
||||
@@ -226,14 +236,16 @@ describe("code-view worker lifecycle", () => {
|
||||
afterEach(async () => {
|
||||
await act(async () => renderer?.unmount());
|
||||
renderer = undefined;
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
await Promise.all(testState.terminations);
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("starts on demand, shares one pool, disposes the last view, and reopens without resetting siblings", async () => {
|
||||
it("starts on demand, keeps quick reopens warm, and expires the last closed pool", async () => {
|
||||
await act(async () => {
|
||||
renderer = create(<Views count={0} />);
|
||||
renderer = create(renderViews(0));
|
||||
});
|
||||
const mounted = renderer!;
|
||||
const button = mounted.root.findByType("button");
|
||||
@@ -241,7 +253,7 @@ describe("code-view worker lifecycle", () => {
|
||||
expect(testState.pools.size).toBe(0);
|
||||
await act(async () => {
|
||||
(button.props as { onClick(): void }).onClick();
|
||||
mounted.update(<Views count={1} />);
|
||||
mounted.update(renderViews(1));
|
||||
});
|
||||
const pool = [...testState.pools.keys()][0]!;
|
||||
await act(async () => testState.pools.get(pool));
|
||||
@@ -252,25 +264,39 @@ describe("code-view worker lifecycle", () => {
|
||||
);
|
||||
expect(testState.requests.filter((request) => request.type === "file")).toHaveLength(0);
|
||||
|
||||
await act(async () => mounted.update(<Views count={2} />));
|
||||
await act(async () => mounted.update(renderViews(2)));
|
||||
await act(async () => pool.primeFileHighlightCache(files[1]!));
|
||||
expect(testState.pools.size).toBe(1);
|
||||
expect(testState.workers).toHaveLength(2);
|
||||
expect(testState.renderPools).toEqual([pool, pool]);
|
||||
expect(new Set(testState.renderPools)).toEqual(new Set([pool]));
|
||||
expect(pool.getFileResultCache(files[1]!)).toBeDefined();
|
||||
expect(mounted.root.findByProps({ "data-code-file": "answer.ts" }).children.join("")).toContain(
|
||||
"answer",
|
||||
);
|
||||
|
||||
await act(async () => mounted.update(<Views count={1} />));
|
||||
await act(async () => mounted.update(renderViews(1)));
|
||||
expect(pool.getStats().totalWorkers).toBe(2);
|
||||
expect(testState.terminations).toHaveLength(0);
|
||||
await act(async () => mounted.update(<Views count={0} />));
|
||||
await act(async () => mounted.update(renderViews(0)));
|
||||
await vi.advanceTimersByTimeAsync(29_999);
|
||||
expect(pool.getStats().totalWorkers).toBe(2);
|
||||
expect(testState.terminations).toHaveLength(0);
|
||||
|
||||
await act(async () => mounted.update(renderViews(1)));
|
||||
expect(testState.pools.size).toBe(1);
|
||||
expect(testState.workers).toHaveLength(2);
|
||||
expect(mounted.root.findAllByProps({ role: "status" })).toHaveLength(0);
|
||||
expect(pool.getFileResultCache(files[1]!)).toBeDefined();
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(pool.getStats().totalWorkers).toBe(2);
|
||||
|
||||
await act(async () => mounted.update(renderViews(0)));
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
await Promise.all(testState.terminations);
|
||||
expect(pool.getStats().totalWorkers).toBe(0);
|
||||
expect(testState.terminations).toHaveLength(2);
|
||||
|
||||
await act(async () => mounted.update(<Views count={1} />));
|
||||
await act(async () => mounted.update(renderViews(1)));
|
||||
const reopenedPool = [...testState.pools.keys()][1]!;
|
||||
await act(async () => testState.pools.get(reopenedPool));
|
||||
expect(reopenedPool.isInitialized()).toBe(true);
|
||||
@@ -285,7 +311,7 @@ describe("code-view worker lifecycle", () => {
|
||||
it("renders through Pierre's main-thread fallback when worker creation fails", async () => {
|
||||
testState.failWorkers = true;
|
||||
await act(async () => {
|
||||
renderer = create(<Views count={1} />);
|
||||
renderer = create(renderViews(1));
|
||||
});
|
||||
const pool = [...testState.pools.keys()][0]!;
|
||||
await act(async () => {
|
||||
@@ -309,7 +335,7 @@ describe("code-view worker lifecycle", () => {
|
||||
testState.onInitializationHeld = resolve;
|
||||
});
|
||||
await act(async () => {
|
||||
renderer = create(<Views count={2} />);
|
||||
renderer = create(renderViews(2));
|
||||
});
|
||||
const pool = [...testState.pools.keys()][0]!;
|
||||
const pending = testState.pools.get(pool)!;
|
||||
@@ -319,10 +345,11 @@ describe("code-view worker lifecycle", () => {
|
||||
expect(renderer!.root.findAllByProps({ role: "status" })).toHaveLength(2);
|
||||
expect(testState.renderPools).toHaveLength(0);
|
||||
|
||||
await act(async () => renderer!.update(<Views count={1} />));
|
||||
await act(async () => renderer!.update(renderViews(1)));
|
||||
expect(pool.getStats().totalWorkers).toBe(2);
|
||||
expect(testState.terminations).toHaveLength(0);
|
||||
await act(async () => renderer!.update(<Views count={0} />));
|
||||
await act(async () => renderer!.update(renderViews(0)));
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
await pending;
|
||||
await Promise.all(testState.terminations);
|
||||
await act(async () => {
|
||||
|
||||
@@ -450,9 +450,92 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
background-repeat: no-repeat;
|
||||
background-clip: text;
|
||||
animation: live-tool-shine 2.2s steps(30) infinite;
|
||||
animation-play-state: var(--visible-animation-state, paused);
|
||||
}
|
||||
}
|
||||
|
||||
@utility visible-animate-spin {
|
||||
animation: var(--animate-spin);
|
||||
animation-play-state: var(--visible-animation-state, paused);
|
||||
will-change: var(--visible-animation-will-change, auto);
|
||||
}
|
||||
|
||||
@keyframes live-activity-focus {
|
||||
from {
|
||||
transform: translateX(0);
|
||||
}
|
||||
to {
|
||||
transform: translateX(100%);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes live-activity-focus-counter {
|
||||
from {
|
||||
transform: translateX(0);
|
||||
}
|
||||
to {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
}
|
||||
|
||||
@utility live-activity-focus {
|
||||
--live-activity-focus-width: 4.5rem;
|
||||
|
||||
right: auto;
|
||||
left: calc(-1 * var(--live-activity-focus-width));
|
||||
width: calc(100% + var(--live-activity-focus-width) + var(--live-activity-focus-width));
|
||||
-webkit-mask-image: linear-gradient(
|
||||
to right,
|
||||
transparent 0,
|
||||
rgb(0 0 0 / 12%) 0.675rem,
|
||||
rgb(0 0 0 / 55%) 1.575rem,
|
||||
black 2.25rem,
|
||||
rgb(0 0 0 / 55%) 2.925rem,
|
||||
rgb(0 0 0 / 12%) 3.825rem,
|
||||
transparent var(--live-activity-focus-width),
|
||||
transparent 100%
|
||||
);
|
||||
-webkit-mask-repeat: no-repeat;
|
||||
mask-image: linear-gradient(
|
||||
to right,
|
||||
transparent 0,
|
||||
rgb(0 0 0 / 12%) 0.675rem,
|
||||
rgb(0 0 0 / 55%) 1.575rem,
|
||||
black 2.25rem,
|
||||
rgb(0 0 0 / 55%) 2.925rem,
|
||||
rgb(0 0 0 / 12%) 3.825rem,
|
||||
transparent var(--live-activity-focus-width),
|
||||
transparent 100%
|
||||
);
|
||||
mask-repeat: no-repeat;
|
||||
animation: live-activity-focus 2.2s linear infinite;
|
||||
animation-play-state: var(--visible-animation-state, paused);
|
||||
will-change: var(--visible-animation-will-change, auto);
|
||||
|
||||
@media (prefers-reduced-motion: reduce), (forced-colors: active) {
|
||||
animation: none;
|
||||
opacity: 0;
|
||||
will-change: auto;
|
||||
}
|
||||
}
|
||||
|
||||
@utility live-activity-focus-counter {
|
||||
width: 100%;
|
||||
animation: live-activity-focus-counter 2.2s linear infinite;
|
||||
animation-play-state: var(--visible-animation-state, paused);
|
||||
will-change: var(--visible-animation-will-change, auto);
|
||||
|
||||
@media (prefers-reduced-motion: reduce), (forced-colors: active) {
|
||||
animation: none;
|
||||
will-change: auto;
|
||||
}
|
||||
}
|
||||
|
||||
@utility live-activity-focus-aligned {
|
||||
width: calc(100% - var(--live-activity-focus-width) - var(--live-activity-focus-width));
|
||||
margin-left: var(--live-activity-focus-width);
|
||||
}
|
||||
|
||||
@property --assistant-citation-highlight-opacity {
|
||||
syntax: "<number>";
|
||||
inherits: true;
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { observeVisibleAnimation } from "./visibleAnimation";
|
||||
|
||||
let page = Object.assign(new EventTarget(), { visibilityState: "visible" });
|
||||
let motion = Object.assign(new EventTarget(), { matches: false });
|
||||
let observers: TestIntersectionObserver[] = [];
|
||||
let cleanups: Array<() => void> = [];
|
||||
|
||||
class TestIntersectionObserver {
|
||||
constructor(private readonly callback: IntersectionObserverCallback) {
|
||||
observers.push(this);
|
||||
}
|
||||
|
||||
observe = vi.fn();
|
||||
unobserve = vi.fn();
|
||||
disconnect = vi.fn();
|
||||
|
||||
report(target: Element, isIntersecting: boolean) {
|
||||
this.callback(
|
||||
[{ target, isIntersecting } as IntersectionObserverEntry],
|
||||
this as unknown as IntersectionObserver,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function animationElement() {
|
||||
const properties = new Map<string, string>();
|
||||
const element = {
|
||||
style: { setProperty: (name: string, value: string) => properties.set(name, value) },
|
||||
} as unknown as HTMLElement;
|
||||
return {
|
||||
element,
|
||||
state: () => properties.get("--visible-animation-state"),
|
||||
willChange: () => properties.get("--visible-animation-will-change"),
|
||||
};
|
||||
}
|
||||
|
||||
function attach(element: HTMLElement) {
|
||||
const cleanup = observeVisibleAnimation(element);
|
||||
if (cleanup) cleanups.push(cleanup);
|
||||
return cleanup;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
page = Object.assign(new EventTarget(), { visibilityState: "visible" });
|
||||
motion = Object.assign(new EventTarget(), { matches: false });
|
||||
observers = [];
|
||||
cleanups = [];
|
||||
vi.stubGlobal("document", page);
|
||||
vi.stubGlobal("window", { matchMedia: () => motion });
|
||||
vi.stubGlobal("IntersectionObserver", TestIntersectionObserver);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups) cleanup();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("observeVisibleAnimation", () => {
|
||||
it("runs only intersecting animations in a visible document with motion enabled", () => {
|
||||
const first = animationElement();
|
||||
const second = animationElement();
|
||||
attach(first.element);
|
||||
attach(second.element);
|
||||
expect(first.state()).toBe("paused");
|
||||
|
||||
const observer = observers[0]!;
|
||||
observer.report(first.element, true);
|
||||
expect(first.state()).toBe("running");
|
||||
expect(second.state()).toBe("paused");
|
||||
|
||||
page.visibilityState = "hidden";
|
||||
page.dispatchEvent(new Event("visibilitychange"));
|
||||
observer.report(second.element, true);
|
||||
expect(first.state()).toBe("paused");
|
||||
expect(first.willChange()).toBe("auto");
|
||||
expect(second.state()).toBe("paused");
|
||||
|
||||
page.visibilityState = "visible";
|
||||
page.dispatchEvent(new Event("visibilitychange"));
|
||||
expect(first.state()).toBe("running");
|
||||
expect(second.state()).toBe("running");
|
||||
|
||||
observer.report(first.element, false);
|
||||
motion.matches = true;
|
||||
motion.dispatchEvent(new Event("change"));
|
||||
expect(first.state()).toBe("paused");
|
||||
expect(second.state()).toBe("paused");
|
||||
|
||||
motion.matches = false;
|
||||
motion.dispatchEvent(new Event("change"));
|
||||
expect(first.state()).toBe("paused");
|
||||
expect(second.state()).toBe("running");
|
||||
});
|
||||
|
||||
it.each(["hidden", "reduced motion"])("starts paused with %s already active", (condition) => {
|
||||
page.visibilityState = condition === "hidden" ? "hidden" : "visible";
|
||||
motion.matches = condition === "reduced motion";
|
||||
const animation = animationElement();
|
||||
attach(animation.element);
|
||||
observers[0]!.report(animation.element, true);
|
||||
expect(animation.state()).toBe("paused");
|
||||
|
||||
page.visibilityState = "visible";
|
||||
motion.matches = false;
|
||||
page.dispatchEvent(new Event("visibilitychange"));
|
||||
expect(animation.state()).toBe("running");
|
||||
});
|
||||
|
||||
it("shares observers, releases the final ref, and ignores late callbacks after remount", () => {
|
||||
const addVisibility = vi.spyOn(page, "addEventListener");
|
||||
const removeVisibility = vi.spyOn(page, "removeEventListener");
|
||||
const addMotion = vi.spyOn(motion, "addEventListener");
|
||||
const removeMotion = vi.spyOn(motion, "removeEventListener");
|
||||
const first = animationElement();
|
||||
const second = animationElement();
|
||||
const detachFirst = attach(first.element);
|
||||
const detachSecond = attach(second.element);
|
||||
expect(observers).toHaveLength(1);
|
||||
expect(addVisibility).toHaveBeenCalledTimes(1);
|
||||
expect(addMotion).toHaveBeenCalledTimes(1);
|
||||
|
||||
const previousObserver = observers[0]!;
|
||||
detachFirst?.();
|
||||
previousObserver.report(first.element, true);
|
||||
expect(first.state()).toBe("paused");
|
||||
expect(previousObserver.unobserve).toHaveBeenCalledWith(first.element);
|
||||
expect(previousObserver.disconnect).not.toHaveBeenCalled();
|
||||
|
||||
detachSecond?.();
|
||||
expect(previousObserver.disconnect).toHaveBeenCalledTimes(1);
|
||||
expect(removeVisibility).toHaveBeenCalledTimes(1);
|
||||
expect(removeMotion).toHaveBeenCalledTimes(1);
|
||||
|
||||
attach(second.element);
|
||||
expect(observers).toHaveLength(2);
|
||||
detachSecond?.();
|
||||
previousObserver.report(second.element, true);
|
||||
expect(second.state()).toBe("paused");
|
||||
observers[1]!.report(second.element, true);
|
||||
expect(second.state()).toBe("running");
|
||||
});
|
||||
|
||||
it("keeps unknown visibility static when IntersectionObserver is unavailable", () => {
|
||||
vi.stubGlobal("IntersectionObserver", undefined);
|
||||
const animation = animationElement();
|
||||
attach(animation.element);
|
||||
expect(animation.state()).toBe("paused");
|
||||
expect(animation.willChange()).toBe("auto");
|
||||
expect(observers).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
interface ObservedAnimation {
|
||||
element: HTMLElement | SVGElement;
|
||||
intersecting: boolean;
|
||||
}
|
||||
|
||||
const animations = new Map<Element, ObservedAnimation>();
|
||||
let observer: IntersectionObserver | null = null;
|
||||
let reducedMotion: MediaQueryList | null = null;
|
||||
|
||||
function updateAnimation(animation: ObservedAnimation) {
|
||||
const running =
|
||||
animation.intersecting && document.visibilityState === "visible" && !reducedMotion?.matches;
|
||||
animation.element.style.setProperty("--visible-animation-state", running ? "running" : "paused");
|
||||
animation.element.style.setProperty(
|
||||
"--visible-animation-will-change",
|
||||
running ? "transform" : "auto",
|
||||
);
|
||||
}
|
||||
|
||||
function updateAnimations() {
|
||||
for (const animation of animations.values()) updateAnimation(animation);
|
||||
}
|
||||
|
||||
/** Attach to a stable animation container. All refs share visibility and motion listeners. */
|
||||
export function observeVisibleAnimation(element: HTMLElement | SVGElement | null) {
|
||||
if (element === null) return;
|
||||
element.style.setProperty("--visible-animation-state", "paused");
|
||||
element.style.setProperty("--visible-animation-will-change", "auto");
|
||||
if (typeof IntersectionObserver === "undefined") return;
|
||||
|
||||
if (observer === null) {
|
||||
reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
|
||||
reducedMotion.addEventListener("change", updateAnimations);
|
||||
document.addEventListener("visibilitychange", updateAnimations);
|
||||
observer = new IntersectionObserver((entries, source) => {
|
||||
if (source !== observer) return;
|
||||
for (const entry of entries) {
|
||||
const animation = animations.get(entry.target);
|
||||
if (!animation) continue;
|
||||
animation.intersecting = entry.isIntersecting;
|
||||
updateAnimation(animation);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const animation = { element, intersecting: false };
|
||||
animations.set(element, animation);
|
||||
observer.observe(element);
|
||||
|
||||
return () => {
|
||||
if (animations.get(element) !== animation) return;
|
||||
animations.delete(element);
|
||||
observer?.unobserve(element);
|
||||
element.style.setProperty("--visible-animation-state", "paused");
|
||||
element.style.setProperty("--visible-animation-will-change", "auto");
|
||||
if (animations.size === 0) {
|
||||
observer?.disconnect();
|
||||
observer = null;
|
||||
reducedMotion?.removeEventListener("change", updateAnimations);
|
||||
reducedMotion = null;
|
||||
document.removeEventListener("visibilitychange", updateAnimations);
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user