feat(desktop): mount terminal sessions in app shell

Co-authored-by: npub1mprnacetjua2xx3p5eddmhxyk6wv929ymm5py8kd2xfxurxahspqqlgyta <d8473ee32b973aa31a21a65adddcc4b69cc2a8a4dee8121ecd51926e0cddbc02@buzz.block.builderlab.xyz>
Signed-off-by: npub1mprnacetjua2xx3p5eddmhxyk6wv929ymm5py8kd2xfxurxahspqqlgyta <d8473ee32b973aa31a21a65adddcc4b69cc2a8a4dee8121ecd51926e0cddbc02@buzz.block.builderlab.xyz>
This commit is contained in:
npub1mprnacetjua2xx3p5eddmhxyk6wv929ymm5py8kd2xfxurxahspqqlgyta
2026-08-01 22:21:52 -04:00
parent bb7bfba148
commit 407db04792
5 changed files with 557 additions and 40 deletions

View File

@@ -2,6 +2,7 @@ import * as React from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Outlet, useLocation } from "@tanstack/react-router";
import { deriveShellRoute } from "@/app/AppShell.helpers";
import { useTerminalContext } from "@/app/useTerminalContext";
import { AppShellProvider } from "@/app/AppShellContext";
import * as BuzzTheme from "@/app/BuzzThemeSurfaces";
import { AppShellOverlays, TerminalBootstrap } from "@/app/AppShellOverlays";
@@ -253,7 +254,6 @@ export function AppShell() {
return;
}
hasRestoredCommunityDestinationRef.current = true;
// Restoration belongs to an explicit community transition. Cold boot and
// reconnect remounts must preserve the route the user explicitly opened.
if (!consumePendingCommunityRestore(activeCommunityId)) {
@@ -289,13 +289,13 @@ export function AppShell() {
selectedView,
sidebarChannels,
]);
const activeChannel = React.useMemo(
() =>
selectedChannelId
? (channels.find((channel) => channel.id === selectedChannelId) ?? null)
: null,
[channels, selectedChannelId],
);
const { activeChannel, terminalContext } = useTerminalContext({
channelId: selectedChannelId,
channels,
locationSearch: location.search,
pubkey: identityQuery.data?.pubkey,
relayUrl: communitiesHook.activeCommunity?.relayUrl,
});
const managedChannel = React.useMemo(() => {
const targetChannelId = managedChannelId ?? selectedChannelId;
return targetChannelId
@@ -740,7 +740,7 @@ export function AppShell() {
className="buzz-huddle-shell relative h-dvh overflow-hidden overscroll-none"
data-huddle-open={isHuddleDrawerOpen}
>
<TerminalBootstrap channelName={activeChannel?.name ?? null} />
<TerminalBootstrap {...terminalContext} />
<div
className={cn(
"buzz-huddle-app-surface z-10 flex min-h-0 flex-row overflow-hidden bg-background",

View File

@@ -0,0 +1,56 @@
import * as React from "react";
import type { Channel } from "@/shared/api/types";
import { safeNpub } from "@/shared/lib/nostrUtils";
type TerminalContext = {
channelId: string | null;
channelName: string | null;
threadId: string | null;
npub: string | null;
relayUrl: string | null;
};
type TerminalContextResult = {
activeChannel: Channel | null;
terminalContext: TerminalContext;
};
export function useTerminalContext({
channelId,
channels,
locationSearch,
pubkey,
relayUrl,
}: {
channelId: string | null;
channels: Channel[];
locationSearch: unknown;
pubkey?: string;
relayUrl?: string;
}): TerminalContextResult {
return React.useMemo(() => {
const search = locationSearch as {
thread?: unknown;
threadRootId?: unknown;
};
const threadId = search.threadRootId ?? search.thread;
const activeChannel = channelId
? (channels.find((candidate) => candidate.id === channelId) ?? null)
: null;
return {
activeChannel,
terminalContext: {
channelId,
channelName: activeChannel?.name ?? null,
threadId:
channelId && typeof threadId === "string" && threadId.length > 0
? threadId
: null,
npub: pubkey ? safeNpub(pubkey) : null,
relayUrl: relayUrl ?? null,
},
};
}, [channelId, channels, locationSearch, pubkey, relayUrl]);
}

View File

@@ -0,0 +1,161 @@
import assert from "node:assert/strict";
import { after, before, test } from "node:test";
import { JSDOM } from "jsdom";
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
url: "http://localhost",
});
const callbacks = new Map();
const calls = [];
let nextCallback = 1;
let channel;
before(async () => {
Object.assign(globalThis, {
document: dom.window.document,
HTMLElement: dom.window.HTMLElement,
HTMLCanvasElement: dom.window.HTMLCanvasElement,
KeyboardEvent: dom.window.KeyboardEvent,
IS_REACT_ACT_ENVIRONMENT: true,
isTauri: true,
window: dom.window,
});
dom.window.localStorage.setItem("buzz-follow-system", "false");
dom.window.isTauri = true;
dom.window.matchMedia = () => ({
matches: false,
addEventListener() {},
removeEventListener() {},
});
dom.window.ResizeObserver = class {
observe() {}
disconnect() {}
};
dom.window.HTMLElement.prototype.animate = () => ({
cancel() {},
currentTime: 0,
finished: new Promise(() => {}),
play() {},
playbackRate: 1,
reverse() {},
});
dom.window.HTMLCanvasElement.prototype.getBoundingClientRect = () => ({
bottom: 408,
height: 408,
left: 0,
right: 840,
top: 0,
width: 840,
x: 0,
y: 0,
toJSON() {},
});
dom.window.HTMLCanvasElement.prototype.getContext = () => ({
fillRect() {},
fillStyle: "",
fillText() {},
font: "",
restore() {},
save() {},
setTransform() {},
textBaseline: "",
});
dom.window.__TAURI_INTERNALS__ = {
invoke(command, args) {
calls.push({ command, args });
if (command === "terminal_attach") {
channel = args.onFrame;
return Promise.resolve({
sessionId: "session-1",
subscriptionId: "subscription-1",
viewport: { columns: 100, generation: 0, screenLines: 24 },
});
}
return Promise.resolve();
},
transformCallback(callback) {
const id = nextCallback++;
callbacks.set(id, callback);
return id;
},
unregisterCallback(id) {
callbacks.delete(id);
},
};
});
after(() => dom.window.close());
function emit(message, index = 0) {
const id = Number(channel.toJSON().slice("__CHANNEL__:".length));
callbacks.get(id)({ index, message });
}
test("mounted bootstrap passes GUI context and ACKs only after consuming a frame", async () => {
const { createElement } = await import("react");
const { act, render, waitFor } = await import("@testing-library/react");
const { ThemeProvider } = await import("@/shared/theme/ThemeProvider");
const { TerminalBootstrap } = await import("./TerminalBootstrap.tsx");
render(
createElement(
ThemeProvider,
null,
createElement("div", {
className: "buzz-huddle-app-surface",
tabIndex: -1,
}),
createElement(TerminalBootstrap, {
channelId: "channel-1",
channelName: "general",
npub: "npub1owner",
relayUrl: "wss://relay.example",
threadId: "thread-1",
}),
),
);
await waitFor(() =>
assert.ok(calls.some(({ command }) => command === "terminal_attach")),
);
const attach = calls.find(({ command }) => command === "terminal_attach");
assert.deepEqual(attach.args.request, {
channelId: "channel-1",
channelName: "general",
columns: 100,
npub: "npub1owner",
pixelHeight: 408,
pixelWidth: 840,
relayUrl: "wss://relay.example",
rows: 24,
threadId: "thread-1",
});
await act(async () => {
emit({
type: "frame",
payload: {
bracketedPaste: true,
cursor: { column: 0, line: 0, visible: true },
focusReporting: true,
full: true,
rows: [],
sequence: 7,
subscriptionId: "subscription-1",
viewport: { columns: 100, generation: 0, screenLines: 24 },
},
});
});
await waitFor(() =>
assert.ok(calls.some(({ command }) => command === "terminal_ack")),
);
assert.deepEqual(
calls.find(({ command }) => command === "terminal_ack").args,
{
sequence: 7,
sessionId: "session-1",
subscriptionId: "subscription-1",
},
);
});

View File

@@ -1,25 +1,259 @@
import { TerminalSubstrate } from "./TerminalSubstrate";
import * as React from "react";
import { isTauri } from "@tauri-apps/api/core";
import {
type TerminalDelivery,
TerminalConnection,
type TerminalFrameMessage,
type TerminalMessage,
} from "./terminalClient";
import {
TerminalSubstrate,
type TerminalViewportSize,
} from "./TerminalSubstrate";
type TerminalContext = {
channelId: string;
channelName: string;
threadId: string | null;
npub: string;
relayUrl: string;
};
type Session = {
key: string;
connection: TerminalConnection | null;
delivery: TerminalDelivery | null;
frame: TerminalFrameMessage | undefined;
title: string;
closing: boolean;
};
const INITIAL_SIZE: TerminalViewportSize = {
columns: 80,
rows: 24,
pixelWidth: 672,
pixelHeight: 408,
};
function report(error: unknown) {
console.error("terminal session failed", error);
}
/** Temporary frontend boundary until the Rust session commands land. */
export function TerminalBootstrap({
channelId,
channelName,
threadId,
npub,
relayUrl,
}: {
channelId: string | null;
channelName: string | null;
threadId: string | null;
npub: string | null;
relayUrl: string | null;
}) {
const context =
channelId && npub && relayUrl
? {
channelId,
channelName: channelName ?? channelId,
threadId,
npub,
relayUrl,
}
: null;
const contextRef = React.useRef<TerminalContext | null>(context);
contextRef.current = context;
const mountedRef = React.useRef(true);
const sizeRef = React.useRef(INITIAL_SIZE);
const resizeChainRef = React.useRef(Promise.resolve());
const [sessions, setSessions] = React.useState<Session[]>([]);
const [activeKey, setActiveKey] = React.useState<string | null>(null);
const [available, setAvailable] = React.useState(() => isTauri());
const acknowledgedFramesRef = React.useRef(new Set<string>());
const sessionsRef = React.useRef(sessions);
sessionsRef.current = sessions;
const fail = React.useCallback((error: unknown) => {
report(error);
setAvailable(false);
}, []);
const removeSession = React.useCallback((key: string) => {
setSessions((current) => current.filter((session) => session.key !== key));
setActiveKey((current) => {
if (current !== key) return current;
const remaining = sessionsRef.current.filter(
(session) => session.key !== key,
);
return remaining.at(-1)?.key ?? null;
});
}, []);
const createSession = React.useCallback(() => {
const spawnContext = contextRef.current;
if (!available || !spawnContext) return;
const key = crypto.randomUUID();
const initial: Session = {
key,
connection: null,
delivery: null,
frame: undefined,
title: "SHELL",
closing: false,
};
setSessions((current) => [...current, initial]);
setActiveKey(key);
const update = (apply: (session: Session) => Session) => {
if (!mountedRef.current) return;
setSessions((current) =>
current.map((session) =>
session.key === key ? apply(session) : session,
),
);
};
const onMessage = (
message: Exclude<TerminalMessage, { type: "frame" }>,
) => {
if (message.type === "exit") {
removeSession(key);
} else if (message.type === "title") {
update((session) => ({
...session,
title: message.payload || "SHELL",
}));
} else if (message.type === "resetTitle") {
update((session) => ({ ...session, title: "SHELL" }));
}
};
const onFrame = (delivery: TerminalDelivery) => {
update((session) => ({ ...session, delivery, frame: delivery.frame }));
};
const size = sizeRef.current;
void TerminalConnection.attach(
{
...spawnContext,
threadId: spawnContext.threadId ?? undefined,
...size,
},
onMessage,
onFrame,
)
.then((connection) => {
if (!mountedRef.current) return connection.detach();
update((session) => ({ ...session, connection }));
if (sizeRef.current !== size) {
const currentSize = sizeRef.current;
return connection
.resize(
currentSize.columns,
currentSize.rows,
currentSize.pixelWidth,
currentSize.pixelHeight,
)
.then((viewport) => connection.viewportReady(viewport));
}
})
.catch((error) => {
removeSession(key);
fail(error);
});
}, [available, fail, removeSession]);
React.useEffect(() => {
if (available && context && sessions.length === 0) createSession();
}, [available, context, createSession, sessions.length]);
React.useEffect(
() => () => {
mountedRef.current = false;
for (const session of sessionsRef.current) {
void session.connection?.detach().catch(report);
}
},
[],
);
const active = sessions.find((session) => session.key === activeKey) ?? null;
const send = (operation: Promise<void> | undefined) => operation?.catch(fail);
const handleSize = React.useCallback(
(size: TerminalViewportSize) => {
sizeRef.current = size;
const connection = sessionsRef.current.find(
(session) => session.key === activeKey,
)?.connection;
if (!connection) return;
resizeChainRef.current = resizeChainRef.current
.then(async () => {
const viewport = await connection.resize(
size.columns,
size.rows,
size.pixelWidth,
size.pixelHeight,
);
await connection.viewportReady(viewport);
})
.catch(fail);
},
[activeKey, fail],
);
return (
<TerminalSubstrate
bracketedPaste={false}
focusReportingEnabled={false}
bracketedPaste={active?.frame?.bracketedPaste ?? false}
channelName={channelName}
onCloseSession={() => {}}
onInput={() => {}}
onNewSession={() => {}}
enabled={available && Boolean(active?.connection)}
focusReportingEnabled={active?.frame?.focusReporting ?? false}
frame={active?.frame}
sessionFrames={sessions.flatMap((session) =>
session.frame ? [{ sessionId: session.key, frame: session.frame }] : [],
)}
onCloseSession={(key) => {
setSessions((current) =>
current.map((session) =>
session.key === key ? { ...session, closing: true } : session,
),
);
const connection = sessionsRef.current.find(
(session) => session.key === key,
)?.connection;
if (!connection) {
removeSession(key);
return;
}
void connection.close().catch(fail);
}}
onFrameConsumed={(frame) => {
const delivery = sessionsRef.current.find(
(session) => session.delivery?.frame === frame,
)?.delivery;
if (!delivery) return;
const deliveryKey = `${delivery.frame.subscriptionId}:${delivery.frame.sequence}`;
if (acknowledgedFramesRef.current.has(deliveryKey)) return;
acknowledgedFramesRef.current.add(deliveryKey);
delivery.acknowledge().catch((error) => {
acknowledgedFramesRef.current.delete(deliveryKey);
fail(error);
});
}}
onInput={(text) => send(active?.connection?.input(text))}
onNewSession={createSession}
onScroll={() => {}}
onSelectSession={() => {}}
onTerminalFocusChange={() => {}}
sessions={[
{ active: true, closing: false, id: "bootstrap", title: "SHELL" },
]}
onSelectSession={setActiveKey}
onTerminalFocusChange={(focused) =>
send(active?.connection?.focus(focused))
}
onViewportSize={handleSize}
sessions={sessions.map((session) => ({
active: session.key === activeKey,
closing: session.closing,
id: session.key,
title: session.title,
}))}
/>
);
}

View File

@@ -14,6 +14,13 @@ import {
} from "./terminalState";
import { type TerminalFrame, TerminalGrid } from "./terminalRenderer";
export type TerminalViewportSize = {
columns: number;
rows: number;
pixelWidth: number;
pixelHeight: number;
};
export type TerminalSessionTab = {
id: string;
title: string;
@@ -25,9 +32,13 @@ type TerminalSubstrateProps = {
appSurfaceRef?: React.RefObject<HTMLDivElement | null>;
channelName: string | null;
frame?: TerminalFrame;
sessionFrames?: readonly { sessionId: string; frame: TerminalFrame }[];
sessions: readonly TerminalSessionTab[];
bracketedPaste: boolean;
focusReportingEnabled: boolean;
enabled?: boolean;
onFrameConsumed?: (frame: TerminalFrame) => void;
onViewportSize?: (size: TerminalViewportSize) => void;
onInput: (text: string) => void;
onScroll: (deltaPx: number) => void;
onTerminalFocusChange: (focused: boolean) => void;
@@ -85,9 +96,13 @@ export function TerminalSubstrate({
appSurfaceRef,
channelName,
frame,
sessionFrames,
sessions,
bracketedPaste,
focusReportingEnabled,
enabled = true,
onFrameConsumed,
onViewportSize,
onInput,
onScroll,
onTerminalFocusChange,
@@ -100,12 +115,21 @@ export function TerminalSubstrate({
const textareaRef = React.useRef<HTMLTextAreaElement>(null);
const fadeRef = React.useRef<FadeController | null>(null);
const handoffRef = React.useRef(INITIAL_HANDOFF_STATE);
const gridsRef = React.useRef(new Map<string, TerminalGrid>());
const appliedFramesRef = React.useRef(new WeakSet<TerminalFrame>());
const gridRef = React.useRef<TerminalGrid | null>(null);
const paintedPaletteRef = React.useRef(terminalPalette);
const previousFocusRef = React.useRef<HTMLElement | null>(null);
const reportedFocusRef = React.useRef<boolean | null>(null);
const scrollBySessionRef = React.useRef(new Map<string, number>());
const activeSession = sessions.find((session) => session.active);
const activeSessionId = activeSession?.id ?? null;
const frames = React.useMemo(
() =>
sessionFrames ??
(activeSessionId && frame ? [{ sessionId: activeSessionId, frame }] : []),
[activeSessionId, frame, sessionFrames],
);
const [owner, setOwner] = React.useState<"buzz" | "terminal">("buzz");
const [welcome, setWelcome] = React.useState<WelcomeState>({
visible: true,
@@ -159,6 +183,38 @@ export function TerminalSubstrate({
setWelcome((current) => ({ ...current, visible: false }));
onInput(text);
});
const consumeFrame = React.useEffectEvent((nextFrame: TerminalFrame) => {
onFrameConsumed?.(nextFrame);
});
const reportViewportSize = React.useEffectEvent(() => {
const canvas = canvasRef.current;
if (!canvas || !onViewportSize) return;
const bounds = canvas.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
const pixelWidth = Math.max(1, Math.round(bounds.width * dpr));
const pixelHeight = Math.max(1, Math.round(bounds.height * dpr));
onViewportSize({
columns: Math.max(1, Math.floor(bounds.width / 8.4)),
rows: Math.max(1, Math.floor(bounds.height / CELL_HEIGHT)),
pixelWidth,
pixelHeight,
});
});
React.useEffect(() => {
if (!enabled) forceBuzzFallback();
}, [enabled]);
React.useEffect(() => {
const canvas = canvasRef.current;
if (!canvas || !onViewportSize) return;
reportViewportSize();
const ResizeObserverConstructor = window.ResizeObserver;
if (!ResizeObserverConstructor) return;
const observer = new ResizeObserverConstructor(reportViewportSize);
observer.observe(canvas);
return () => observer.disconnect();
}, [onViewportSize]);
React.useEffect(() => {
if (!focusReportingEnabled) {
@@ -185,7 +241,7 @@ export function TerminalSubstrate({
if (!appSurface) return;
fadeRef.current = new FadeController(appSurface);
const handleKeyDown = (event: KeyboardEvent) => {
if (!isToggleChord(event)) return;
if (!enabled || !isToggleChord(event)) return;
if (event.isComposing) {
handoffRef.current = reduceHandoff(handoffRef.current, {
type: "focus-lost",
@@ -201,7 +257,7 @@ export function TerminalSubstrate({
handoffRef.current = result.state;
};
const handleKeyUp = (event: KeyboardEvent) => {
if (!isToggleChord(event)) return;
if (!enabled || !isToggleChord(event)) return;
event.preventDefault();
event.stopImmediatePropagation();
if (event.isComposing) return;
@@ -232,27 +288,37 @@ export function TerminalSubstrate({
window.removeEventListener("blur", cancelChord);
document.removeEventListener("visibilitychange", cancelChord);
};
}, [getAppSurface]);
}, [enabled, getAppSurface]);
React.useEffect(() => {
if (frame) {
setWelcome((current) =>
updateWelcomeForOutput(
{ ...current, reserved: welcomeRect(frame) },
frameDamageRects(frame),
),
);
const current = gridRef.current;
if (!current) gridRef.current = new TerminalGrid(frame.viewport);
else if (
current.viewport.generation !== frame.viewport.generation ||
current.viewport.columns !== frame.viewport.columns ||
current.viewport.screenLines !== frame.viewport.screenLines
for (const delivered of frames) {
if (appliedFramesRef.current.has(delivered.frame)) continue;
appliedFramesRef.current.add(delivered.frame);
let grid = gridsRef.current.get(delivered.sessionId);
if (!grid) {
grid = new TerminalGrid(delivered.frame.viewport);
gridsRef.current.set(delivered.sessionId, grid);
} else if (
grid.viewport.generation !== delivered.frame.viewport.generation ||
grid.viewport.columns !== delivered.frame.viewport.columns ||
grid.viewport.screenLines !== delivered.frame.viewport.screenLines
) {
current.resize(frame.viewport);
grid.resize(delivered.frame.viewport);
}
grid.apply(delivered.frame);
consumeFrame(delivered.frame);
if (delivered.sessionId === activeSessionId) {
setWelcome((current) =>
updateWelcomeForOutput(
{ ...current, reserved: welcomeRect(delivered.frame) },
frameDamageRects(delivered.frame),
),
);
}
gridRef.current?.apply(frame);
}
gridRef.current = activeSessionId
? (gridsRef.current.get(activeSessionId) ?? null)
: null;
const canvas = canvasRef.current;
if (!canvas) return;
@@ -296,7 +362,7 @@ export function TerminalSubstrate({
},
terminalPalette,
);
}, [frame, terminalPalette]);
}, [activeSessionId, frames, terminalPalette]);
return (
<section