Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(web): free resting avatar motions and reuse per-Run projections
jeffrey231f61079079
diff --git a/apps/web/src/features/rooms/chat/message-timeline-card.test.tsx b/apps/web/src/features/rooms/chat/message-timeline-card.test.tsxindex 664cead1..3acd88f9 100644--- a/apps/web/src/features/rooms/chat/message-timeline-card.test.tsx+++ b/apps/web/src/features/rooms/chat/message-timeline-card.test.tsx@@ -17,7 +17,11 @@ import type {TeamHubRuntimePresentationEventRecord,} from "@/features/teamhub/teamhub-types";-import { AgentStreamingStatusDock, MessageTimeline } from "./message-timeline";+import {+ AgentStreamingStatusDock,+ buildRuntimeTimelineViews,+ MessageTimeline,+} from "./message-timeline";import { AGENT_STATUS_LINE_TIMING } from "./agent-status-line";import {createDocumentTestRuntime,@@ -3161,3 +3165,48 @@ function readDocumentVersion(client: TeamHubClient, documentVersionId: string) {}),);}++describe("Runtime timeline projection reuse", () => {+ it("re-projects only the Run whose status or events changed", () => {+ const first = runStatus({ id: "run-status-1" });+ const second = runStatus({+ agent: { display_name: "Claude", id: "agent-2", kind: "agent" },+ id: "run-status-2",+ });+ const firstEvents = [runtimeStatusRecord("1", "working", "Reading")];+ const secondEvents = [runtimeStatusRecord("1", "thinking")];+ const cache = new Map();+ const [firstView, secondView] = buildRuntimeTimelineViews({+ cache,+ runStatuses: [first, second],+ runtimePresentationEventsByRunStatusId: {+ "run-status-1": firstEvents,+ "run-status-2": secondEvents,+ },+ });++ const next = buildRuntimeTimelineViews({+ cache,+ runStatuses: [first, second],+ runtimePresentationEventsByRunStatusId: {+ "run-status-1": firstEvents,+ "run-status-2": [+ ...secondEvents,+ runtimeStatusRecord("2", "working", "Writing"),+ ],+ },+ });+ expect(next).toHaveLength(2);+ expect(next[0]).toBe(firstView);+ expect(next[1]).not.toBe(secondView);++ const revised = buildRuntimeTimelineViews({+ cache,+ runStatuses: [{ ...first, revision: 2 }],+ runtimePresentationEventsByRunStatusId: { "run-status-1": firstEvents },+ });+ expect(revised[0]).not.toBe(firstView);+ // A Run that leaves the list leaves the cache too.+ expect([...cache.keys()]).toEqual(["run-status-1"]);+ });+});diff --git a/apps/web/src/features/rooms/chat/message-timeline.tsx b/apps/web/src/features/rooms/chat/message-timeline.tsxindex ae15b630..dac19206 100644--- a/apps/web/src/features/rooms/chat/message-timeline.tsx+++ b/apps/web/src/features/rooms/chat/message-timeline.tsx@@ -18,7 +18,7 @@ import {} from "../members/agent-avatar-status-context";import { runtimeFailureMessage } from "../runtime-status/runtime-failure-message";import type { RuntimeExecutionFailure } from "../runtime-status/runtime-presentation-events";-import { Fragment, type ReactNode, useMemo, useState } from "react";+import { Fragment, type ReactNode, useMemo, useRef, useState } from "react";import { cn } from "@/lib/cn";import { Button } from "@/components/ui/button";@@ -190,9 +190,11 @@ export function MessageTimeline({useMessageFilePreview(onOpenMessageFile);const { candidateMessages, openedAtNewest, startsOwnGroup } =useTimelineMessageGroups(messages, currentActorId);+ const runtimeViewCache = useRef<RuntimeTimelineViewCache>(new Map());const runtimeStatusViews = useMemo(() =>buildRuntimeTimelineViews({+ cache: runtimeViewCache.current,runStatuses,runtimePresentationEventsByRunStatusId,}),@@ -373,35 +375,63 @@ export function MessageTimeline({);}+/**+ * Each Run's last view, kept while the Run stays listed. A Run is projected+ * again only when its status or its event list is a new object, so one Run's+ * runtime event does not re-project every other Run.+ */+type RuntimeTimelineViewCache = Map<+ string,+ {+ records: readonly TeamHubRuntimePresentationEventRecord[] | undefined;+ runStatus: TeamHubRunStatus;+ view: AgentRunStatusView | undefined;+ }+>;+export function buildRuntimeTimelineViews({+ cache,runStatuses,runtimePresentationEventsByRunStatusId,}: {+ /** Reused and pruned to the given Runs on every pass. */+ cache?: RuntimeTimelineViewCache;runStatuses: readonly TeamHubRunStatus[];runtimePresentationEventsByRunStatusId: Readonly<Record<string, readonly TeamHubRuntimePresentationEventRecord[]>>;}) {const runtimeStatusViews: AgentRunStatusView[] = [];+ const listed = new Set<string>();for (const runStatus of runStatuses) {const records = runtimePresentationEventsByRunStatusId[runStatus.id];- const presentation = records- ? projectRuntimeChatPresentation(records)- : undefined;- const history = resolveAgentRunStatusHistory({ runStatus, presentation });- if (history.length === 0) continue;-- const latestSegmentKey = history.at(-1)!.key;- const runtimeStatus = createAgentRunStatusView(- runStatus,- history,- latestSegmentKey,- );- runtimeStatusViews.push(runtimeStatus);+ const cached = cache?.get(runStatus.id);+ const view =+ cached?.runStatus === runStatus && cached.records === records+ ? cached.view+ : runtimeTimelineView(runStatus, records);+ listed.add(runStatus.id);+ cache?.set(runStatus.id, { records, runStatus, view });+ if (view) runtimeStatusViews.push(view);+ }+ for (const runStatusId of cache?.keys() ?? []) {+ if (!listed.has(runStatusId)) cache?.delete(runStatusId);}return runtimeStatusViews;}+function runtimeTimelineView(+ runStatus: TeamHubRunStatus,+ records: readonly TeamHubRuntimePresentationEventRecord[] | undefined,+) {+ const presentation = records+ ? projectRuntimeChatPresentation(records)+ : undefined;+ const history = resolveAgentRunStatusHistory({ runStatus, presentation });+ if (history.length === 0) return undefined;+ return createAgentRunStatusView(runStatus, history, history.at(-1)!.key);+}+function TypingDots({ className = "" }: { className?: string }) {return (<span aria-hidden="true" className={`town-dots shrink-0 ${className}`}>@@ -815,9 +845,14 @@ export function AgentStreamingStatusDock({/** Shown only while that Agent has no Run status; it offers no Stop. */typingAgent?: AgentStreamingTypingAgent;}) {+ const runtimeViewCache = useRef<RuntimeTimelineViewCache>(new Map());const runtimeStatuses = useMemo(() =>- dockRuntimeStatuses(runStatuses, runtimePresentationEventsByRunStatusId),+ dockRuntimeStatuses(+ runStatuses,+ runtimePresentationEventsByRunStatusId,+ runtimeViewCache.current,+ ),[runStatuses, runtimePresentationEventsByRunStatusId],);const entries = useMemo<AgentStreamingDockEntry[]>(() => {@@ -1042,6 +1077,7 @@ function dockRuntimeStatuses(runtimePresentationEventsByRunStatusId: Readonly<Record<string, readonly TeamHubRuntimePresentationEventRecord[]>>,+ cache: RuntimeTimelineViewCache,) {const latestByAgent = new Map<string, TeamHubRunStatus>();for (const runStatus of runStatuses) {@@ -1063,6 +1099,7 @@ function dockRuntimeStatuses(}// Select before projection: a completed Run may have no displayable history.return buildRuntimeTimelineViews({+ cache,runStatuses: [...latestByAgent.values()],runtimePresentationEventsByRunStatusId,}).filter(diff --git a/apps/web/src/features/rooms/chat/use-room-agent-streaming-status.ts b/apps/web/src/features/rooms/chat/use-room-agent-streaming-status.tsindex be9ba46d..db6b5af9 100644--- a/apps/web/src/features/rooms/chat/use-room-agent-streaming-status.ts+++ b/apps/web/src/features/rooms/chat/use-room-agent-streaming-status.ts@@ -59,12 +59,16 @@ export function useRoomAgentStreamingStatus({roomId,tenantId,});- const progressVersion = [- ...visibleRunStatuses.map(- (runStatus) => `${runStatus.id}:${runStatus.revision}`,- ),- runtimePresentations.progressVersion,- ].join("|");+ const runStatusVersion = useMemo(+ () =>+ visibleRunStatuses+ .map((runStatus) => `${runStatus.id}:${runStatus.revision}`)+ .join("|"),+ [visibleRunStatuses],+ );+ const progressVersion = runStatusVersion+ ? `${runStatusVersion}|${runtimePresentations.progressVersion}`+ : runtimePresentations.progressVersion;return {runStatuses: visibleRunStatuses,diff --git a/apps/web/src/features/rooms/members/agent-avatar-motion.tsx b/apps/web/src/features/rooms/members/agent-avatar-motion.tsxindex 9f77b4ea..aca86a79 100644--- a/apps/web/src/features/rooms/members/agent-avatar-motion.tsx+++ b/apps/web/src/features/rooms/members/agent-avatar-motion.tsx@@ -38,22 +38,25 @@ function motionUrl(figure: string) {/*** The figure's Lottie motion (peek, blink and smile), drawn over its still- * portrait. It loads the first time the figure moves and stays mounted, so- * later moves start at once. Each time `playing` turns on, the figure plays- * the motion once and stops on its last frame, which is the resting pose; it- * never loops, because every SVG frame forces a style and layout pass.- * `hold` leans in and keeps the smile until it turns off, taking precedence- * over playing; each new `blink` blinks once while it holds.+ * portrait. Each time `playing` turns on, the figure plays the motion once and+ * stops on its last frame, which is the resting pose; it never loops, because+ * every SVG frame forces a style and layout pass. `hold` leans in and keeps+ * the smile until it turns off, taking precedence over playing; each new+ * `blink` blinks once while it holds. `onIdle` fires once the figure rests and+ * neither `playing` nor `hold` asks for more, so the owner can unmount it and+ * free the parsed animation.*/export default function AgentAvatarMotion({blink = 0,figure,hold = false,+ onIdle,playing,}: {blink?: number;figure: string;hold?: boolean;+ onIdle?: () => void;playing: boolean;}) {const boxRef = useRef<HTMLSpanElement>(null);@@ -95,13 +98,25 @@ export default function AgentAvatarMotion({setAnimation(undefined);};}, [figure]);+ // The complete listener reads the latest wishes without re-subscribing.+ const idleRef = useRef({ hold, onIdle, playing });+ useEffect(() => {+ idleRef.current = { hold, onIdle, playing };+ });+ useEffect(() => {+ if (!animation) return;+ return animation.addEventListener("complete", () => {+ const { hold: held, onIdle: idle, playing: wanted } = idleRef.current;+ if (!held && !wanted) idle?.();+ });+ }, [animation]);const heldRef = useRef(false);useEffect(() => {if (!animation) return;if (hold || heldRef.current) {heldRef.current = hold;playHold(animation, hold);- if (hold || !playing) return;+ if (hold) return;}if (playing) {// A hold leaves a shorter segment behind; one play runs the whole one.@@ -110,6 +125,9 @@ export default function AgentAvatarMotion({}animation.setLoop(false);animation.play();+ } else if (animation.isPaused) {+ // Nothing is left to play; a running segment reports idle on complete.+ idleRef.current.onIdle?.();}}, [animation, hold, playing]);const blinkedRef = useRef(blink);diff --git a/apps/web/src/features/rooms/members/agent-avatar-portrait.test.tsx b/apps/web/src/features/rooms/members/agent-avatar-portrait.test.tsxindex 00bfb7a1..e331c15d 100644--- a/apps/web/src/features/rooms/members/agent-avatar-portrait.test.tsx+++ b/apps/web/src/features/rooms/members/agent-avatar-portrait.test.tsx@@ -1,14 +1,37 @@-import { act, render, waitFor } from "@testing-library/react";+import { act, cleanup, render, waitFor } from "@testing-library/react";import { afterEach, beforeEach, expect, it, vi } from "vitest";import { figureKey } from "./agent-avatar";import { AgentAvatarPortrait } from "./agent-avatar-portrait";-const animation = vi.hoisted(() => ({- destroy: vi.fn(),- play: vi.fn(),- setLoop: vi.fn(),-}));+const animation = vi.hoisted(() => {+ const listeners = new Set<() => void>();+ const item = {+ addEventListener: vi.fn((_name: string, listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ }),+ currentFrame: 0,+ destroy: vi.fn(),+ firstFrame: 0,+ isPaused: true,+ play: vi.fn(() => {+ item.isPaused = false;+ }),+ playSegments: vi.fn(() => {+ item.isPaused = false;+ }),+ resetSegments: vi.fn(),+ setLoop: vi.fn(),+ /** Lottie pauses on the last frame of a segment, then fires complete. */+ complete() {+ item.isPaused = true;+ item.currentFrame = 83;+ listeners.forEach((listener) => listener());+ },+ };+ return item;+});const loadAnimation = vi.hoisted(() => vi.fn(() => animation));vi.mock("lottie-web/build/player/lottie_light", () => ({default: { loadAnimation },@@ -17,6 +40,8 @@ vi.mock("lottie-web/build/player/lottie_light", () => ({let reducedMotion = false;beforeEach(() => {reducedMotion = false;+ animation.isPaused = true;+ animation.currentFrame = 0;vi.stubGlobal("matchMedia",vi.fn(() => ({ matches: reducedMotion })),@@ -31,22 +56,24 @@ beforeEach(() => {);});afterEach(() => {+ // Unmount first so a test's own teardown does not count in the next one.+ cleanup();vi.unstubAllGlobals();vi.clearAllMocks();});-it("loads a figure's motion on its first move and keeps it for later moves", async () => {+function motionReady() {+ return document.querySelector('.agent-avatar-motion[data-ready="true"]');+}++it("loads a figure's motion when it moves and frees it once it rests", async () => {const key = figureKey("fox");const view = render(<AgentAvatarPortrait avatarKey={key} />);expect(document.querySelector(".agent-avatar-motion")).toBeNull();expect(fetch).not.toHaveBeenCalled();view.rerender(<AgentAvatarPortrait animate avatarKey={key} />);- await waitFor(() =>- expect(- document.querySelector('.agent-avatar-motion[data-ready="true"]'),- ).not.toBeNull(),- );+ await waitFor(() => expect(motionReady()).not.toBeNull());expect(fetch).toHaveBeenCalledWith(expect.stringContaining("agent-avatar-motion/fox.json"),);@@ -58,14 +85,57 @@ it("loads a figure's motion on its first move and keeps it for later moves", asy);// Playing starts in an effect after the ready render commits.await waitFor(() => expect(animation.play).toHaveBeenCalledTimes(1));-- // The motion plays once and never loops; moving again replays it at once.expect(animation.setLoop).not.toHaveBeenCalledWith(true);++ // Resting while the Agent still moves keeps the motion.+ act(() => animation.complete());+ expect(motionReady()).not.toBeNull();+ expect(animation.destroy).not.toHaveBeenCalled();++ // Once nothing moves it, the motion unmounts and the still portrait shows.view.rerender(<AgentAvatarPortrait avatarKey={key} />);+ expect(document.querySelector(".agent-avatar-motion")).toBeNull();+ expect(animation.destroy).toHaveBeenCalledTimes(1);++ // The next move loads it again and plays.view.rerender(<AgentAvatarPortrait animate avatarKey={key} />);await waitFor(() => expect(animation.play).toHaveBeenCalledTimes(2));+ expect(fetch).toHaveBeenCalledTimes(2);expect(animation.setLoop).not.toHaveBeenCalledWith(true);- expect(fetch).toHaveBeenCalledTimes(1);+});++it("lets a running motion finish before it unmounts", async () => {+ const key = figureKey("fox");+ const view = render(<AgentAvatarPortrait animate avatarKey={key} />);+ await waitFor(() => expect(animation.play).toHaveBeenCalledTimes(1));++ // Leaving mid-play does not cut the motion off.+ view.rerender(<AgentAvatarPortrait avatarKey={key} />);+ expect(motionReady()).not.toBeNull();+ expect(animation.destroy).not.toHaveBeenCalled();++ act(() => animation.complete());+ expect(document.querySelector(".agent-avatar-motion")).toBeNull();+ expect(animation.destroy).toHaveBeenCalledTimes(1);+});++it("keeps the motion through a held smile and its return", async () => {+ const key = figureKey("fox");+ const view = render(<AgentAvatarPortrait avatarKey={key} hold />);+ await waitFor(() => expect(animation.playSegments).toHaveBeenCalledTimes(1));++ // Reaching the smile completes the segment but the hold keeps it.+ act(() => animation.complete());+ animation.currentFrame = 40;+ expect(motionReady()).not.toBeNull();++ // Releasing plays the return; the motion unmounts once it rests.+ view.rerender(<AgentAvatarPortrait avatarKey={key} />);+ expect(animation.playSegments).toHaveBeenLastCalledWith([40, 83], true);+ expect(motionReady()).not.toBeNull();+ act(() => animation.complete());+ expect(document.querySelector(".agent-avatar-motion")).toBeNull();+ expect(animation.destroy).toHaveBeenCalledTimes(1);});it("stays still when the system asks for reduced motion", async () => {diff --git a/apps/web/src/features/rooms/members/agent-avatar-portrait.tsx b/apps/web/src/features/rooms/members/agent-avatar-portrait.tsxindex 800e1b97..9f6b7b86 100644--- a/apps/web/src/features/rooms/members/agent-avatar-portrait.tsx+++ b/apps/web/src/features/rooms/members/agent-avatar-portrait.tsx@@ -51,10 +51,13 @@ export function AgentAvatarPortrait({return () => window.clearTimeout(settle);}, [cheer]);const holding = hold || cheering;- // Mount the motion on the first move and keep it, so later moves are instant.- const [moved, setMoved] = useState(false);- if ((animate || holding) && !moved && !uploaded && !prefersReducedMotion()) {- setMoved(true);+ // Mount the motion while the figure moves. Once it rests on its still frame+ // with nothing asking for more, unmount it so Lottie frees its SVG and data.+ // The next move loads the motion again, a short wait the HTTP cache keeps+ // small; Lottie mutates the parsed data, so it is not kept between moves.+ const [moving, setMoving] = useState(false);+ if ((animate || holding) && !moving && !uploaded && !prefersReducedMotion()) {+ setMoving(true);}return (<span@@ -75,12 +78,13 @@ export function AgentAvatarPortrait({transition: "opacity 200ms ease",}}/>- {moved && appearance.kind !== "image" ? (+ {moving && appearance.kind !== "image" ? (<Suspense fallback={null}><AgentAvatarMotionblink={blink}figure={appearance.figure}hold={holding}+ onIdle={() => setMoving(false)}playing={animate}/></Suspense>