Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,646 changes: 0 additions & 1,646 deletions web/bun.lock

This file was deleted.

22 changes: 11 additions & 11 deletions web/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ErrorBoundary } from "./components/ErrorBoundary";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider } from "@tanstack/react-router";
import { TransportProvider } from "@connectrpc/connect-query";
Expand All @@ -15,10 +16,7 @@ const queryClient = new QueryClient({
},
});

// ADR 0051 Task 23: Connect transport targeting /rpc (Vite proxy → orchestrator :8787;
// split-host deployments point RPC_BASE at the api host and ride the session cookie
// cross-origin — see lib/base.ts). TransportProvider makes it available to all
// useQuery/useMutation connect-query hooks without threading a transport prop everywhere.
// Connect requests use the same deployment credentials as REST requests.
const transport = createConnectTransport({
baseUrl: RPC_BASE,
fetch: (input, init) => fetch(input, { ...init, credentials: API_CREDENTIALS }),
Expand All @@ -31,12 +29,14 @@ function InnerApp() {

export function App() {
return (
<TransportProvider transport={transport}>
<QueryClientProvider client={queryClient}>
<AuthProvider>
<InnerApp />
</AuthProvider>
</QueryClientProvider>
</TransportProvider>
<ErrorBoundary>
<TransportProvider transport={transport}>
<QueryClientProvider client={queryClient}>
<AuthProvider>
<InnerApp />
</AuthProvider>
</QueryClientProvider>
</TransportProvider>
</ErrorBoundary>
);
}
29 changes: 29 additions & 0 deletions web/src/components/ErrorBoundary.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import { ErrorBoundary } from "./ErrorBoundary";

afterEach(() => vi.restoreAllMocks());

it("contains a child failure and remounts the child on retry", () => {
vi.spyOn(console, "error").mockImplementation(() => {});
let broken = true;
function Child() {
if (broken) throw new Error("private failure detail");
return <p>Ready</p>;
}
render(
<>
<p>Other pane</p>
<ErrorBoundary>
<Child />
</ErrorBoundary>
</>,
);
expect(screen.getByRole("alert").textContent).toContain("This view could not load");
expect(screen.queryByText("private failure detail")).toBeNull();
expect(screen.getByText("Other pane")).toBeTruthy();
broken = false;
fireEvent.click(screen.getByRole("button", { name: "Try again" }));
expect(screen.getByText("Ready")).toBeTruthy();
expect(screen.queryByRole("alert")).toBeNull();
});
34 changes: 34 additions & 0 deletions web/src/components/ErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Component, type ReactNode } from "react";
import { Button } from "@/components/ui/button";

export function ErrorFallback({ onRetry }: { onRetry: () => void }) {
return (
<div
role="alert"
className="flex min-h-48 flex-1 flex-col items-center justify-center gap-3 rounded-lg border bg-card p-6 text-center text-card-foreground"
>
<h2 className="text-lg font-semibold">This view could not load</h2>
<p className="text-sm text-muted-foreground">
Try again. If the problem continues, reload the page.
</p>
<Button variant="outline" onClick={onRetry}>
Try again
</Button>
</div>
);
}

export class ErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
state = { failed: false };

static getDerivedStateFromError() {
return { failed: true };
}

render() {
if (this.state.failed) {
return <ErrorFallback onRetry={() => this.setState({ failed: false })} />;
}
return this.props.children;
}
}
3 changes: 2 additions & 1 deletion web/src/components/IdePane.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { apiFetch } from "@/lib/api-fetch";
import { useEffect, useRef, useState } from "react";

import { API_BASE } from "../lib/base";
Expand Down Expand Up @@ -65,7 +66,7 @@ export function IdePane({ sessionId }: IdePaneProps) {
async function probe(attempt: number) {
if (disposed) return;
try {
const res = await fetch(healthUrl(sessionId), { credentials: "include" });
const res = await apiFetch(healthUrl(sessionId));
if (disposed) return;
if (res.ok) {
setIdeReady(true);
Expand Down
26 changes: 26 additions & 0 deletions web/src/components/RouteFallbacks.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Link, useRouter, type ErrorComponentProps } from "@tanstack/react-router";
import { ErrorFallback } from "./ErrorBoundary";

export function RouteError({ reset }: ErrorComponentProps) {
const router = useRouter();
return (
<ErrorFallback
onRetry={() => {
void router.invalidate();
reset();
}}
/>
);
}

export function RouteNotFound() {
return (
<div className="flex min-h-48 flex-col items-center justify-center gap-3 p-6 text-center">
<h1 className="text-lg font-semibold">Page not found</h1>
<p className="text-sm text-muted-foreground">Check the address or return to your sessions.</p>
<Link to="/sessions" className="text-sm underline underline-offset-4">
Go to sessions
</Link>
</div>
);
}
198 changes: 171 additions & 27 deletions web/src/components/TerminalPane.test.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,7 @@
// Regression tests for the SHELL-tab "hangs on remount" bug.
//
// Symptom: open SHELL on an active session, navigate away via SPA,
// navigate back, click SHELL, type a command — the keystrokes flow
// over the websocket but no output renders. The underlying error is
// `RuntimeError: memory access out of bounds` thrown from inside
// term.write() the first time the new mount tries to render a chunk
// of any real size (e.g. the colorized output of `ls /`).
//
// Cause: ghostty-web 0.4 Terminal.dispose() already frees the WASM
// terminal via cleanupComponents(). An earlier version of this
// component called wasmTerm.free() ourselves first, which made
// dispose()'s subsequent free a *double-free* — that corrupted the
// allocator's free list and the next Terminal's grid landed on top
// of poisoned memory. Small writes survived; a multi-line write hit
// the corrupted region and threw.
//
// The mount-side workaround (clear-after-fit) addresses a separate,
// older "stale glyphs on remount" bug and is preserved.
//
// Both bugs have come back from "fixed" before because nothing pinned
// the cleanup contract. These tests assert it via mock invocation
// counters so a future refactor fails loudly.
// Terminal lifecycle and transport recovery tests use a mocked renderer and socket.

import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { act, cleanup, render } from "@testing-library/react";
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { TerminalPane } from "./TerminalPane";

// vi.hoisted runs before the vi.mock factory, so the classes are
Expand All @@ -38,8 +16,8 @@ const { MockTerminal, MockFitAddon } = vi.hoisted(() => {
write = vi.fn();
loadAddon = vi.fn();
dispose = vi.fn();
onData = vi.fn();
onResize = vi.fn();
onData = vi.fn<(callback: (data: string) => void) => void>();
onResize = vi.fn<(callback: (size: { cols: number; rows: number }) => void) => void>();
wasmTerm = { free: vi.fn() };
constructor() {
MockTerminal.instances.push(this);
Expand All @@ -65,6 +43,7 @@ vi.mock("ghostty-web", () => ({

class MockWebSocket {
static instances: MockWebSocket[] = [];
static OPEN = 1;
readyState = 0;
onopen: ((ev: Event) => void) | null = null;
onmessage: ((ev: MessageEvent) => void) | null = null;
Expand All @@ -85,12 +64,13 @@ beforeEach(() => {
MockTerminal.instances = [];
MockFitAddon.instances = [];
MockWebSocket.instances = [];
vi.stubGlobal("WebSocket", MockWebSocket as unknown as typeof WebSocket);
vi.stubGlobal("WebSocket", MockWebSocket);
});

afterEach(() => {
cleanup();
vi.unstubAllGlobals();
vi.useRealTimers();
});

async function flush() {
Expand Down Expand Up @@ -217,3 +197,167 @@ describe("TerminalPane remount cycle", () => {
expect(secondTerm.wasmTerm.free).not.toHaveBeenCalled();
});
});

describe("TerminalPane reconnect", () => {
function closeSocket(code = 1006) {
const ws = MockWebSocket.instances.at(-1)!;
ws.readyState = 3;
act(() => ws.onclose?.(new CloseEvent("close", { code })));
}

async function advance(ms: number) {
await act(async () => {
await vi.advanceTimersByTimeAsync(ms);
});
}

test("retries with bounded backoff and keeps the terminal alive", async () => {
vi.useFakeTimers();
render(<TerminalPane sessionId="s1" />);
await flush();
for (const [index, delay] of [500, 1000, 2000, 4000, 8000].entries()) {
closeSocket();
await advance(delay - 1);
expect(MockWebSocket.instances).toHaveLength(index + 1);
await advance(1);
expect(MockWebSocket.instances).toHaveLength(index + 2);
}
closeSocket();
await advance(60_000);
expect(MockWebSocket.instances).toHaveLength(6);
expect(MockTerminal.instances).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Reconnect" }));
await flush();
expect(MockWebSocket.instances).toHaveLength(7);
expect(MockTerminal.instances).toHaveLength(2);
closeSocket();
await advance(500);
expect(MockWebSocket.instances).toHaveLength(8);
});

test.each([1000, 1008, 4001])(
"does not retry an explicit close or refusal (%s)",
async (code) => {
vi.useFakeTimers();
render(<TerminalPane sessionId="s1" />);
await flush();
closeSocket(code);
await advance(60_000);
expect(MockWebSocket.instances).toHaveLength(1);
},
);

test("cancels pending retries on unmount and ignores late close events", async () => {
vi.useFakeTimers();
const { unmount } = render(<TerminalPane sessionId="s1" />);
await flush();
closeSocket();
unmount();
closeSocket();
await advance(60_000);
expect(MockWebSocket.instances).toHaveLength(1);
expect(vi.getTimerCount()).toBe(0);
});

test("sends input and resize to the replacement socket", async () => {
vi.useFakeTimers();
render(<TerminalPane sessionId="s1" />);
await flush();
const first = MockWebSocket.instances[0]!;
closeSocket();
await advance(500);
const second = MockWebSocket.instances[1]!;
second.readyState = MockWebSocket.OPEN;
act(() => second.onopen?.(new Event("open")));
const term = MockTerminal.instances[0]!;
term.onData.mock.calls[0]![0]("hello");
term.onResize.mock.calls[0]![0]({ cols: 100, rows: 40 });
expect(second.send).toHaveBeenCalledWith("0hello");
expect(second.send).toHaveBeenCalledWith('1{"columns":100,"rows":40}');
expect(first.send).not.toHaveBeenCalled();
expect(second.send).toHaveBeenCalledWith('{"AuthToken":"","columns":80,"rows":24}');
});

test("a drop while hidden waits, then reconnects when the pane is shown", async () => {
vi.useFakeTimers();
const view = render(<TerminalPane sessionId="s1" visible={false} />);
await flush();
closeSocket();
await advance(60_000);
expect(MockWebSocket.instances).toHaveLength(1);
view.rerender(<TerminalPane sessionId="s1" visible />);
expect(MockWebSocket.instances).toHaveLength(2);
view.rerender(<TerminalPane sessionId="s1" visible={false} />);
view.rerender(<TerminalPane sessionId="s1" visible />);
expect(MockWebSocket.instances).toHaveLength(2);
});

test("a pending retry does not connect if the pane is hidden first", async () => {
vi.useFakeTimers();
const view = render(<TerminalPane sessionId="s1" visible />);
await flush();
closeSocket();
view.rerender(<TerminalPane sessionId="s1" visible={false} />);
await advance(60_000);
expect(MockWebSocket.instances).toHaveLength(1);
view.rerender(<TerminalPane sessionId="s1" visible />);
expect(MockWebSocket.instances).toHaveLength(2);
});

test("a drop while visible reconnects after the backoff", async () => {
vi.useFakeTimers();
render(<TerminalPane sessionId="s1" visible />);
await flush();
closeSocket();
await advance(499);
expect(MockWebSocket.instances).toHaveLength(1);
await advance(1);
expect(MockWebSocket.instances).toHaveLength(2);
});

test("marks where the new shell starts after an automatic reconnect", async () => {
vi.useFakeTimers();
render(<TerminalPane sessionId="s1" />);
await flush();
const term = MockTerminal.instances[0]!;
act(() => MockWebSocket.instances[0]!.onopen?.(new Event("open")));
const marker = expect.stringContaining("new shell");
expect(term.write).not.toHaveBeenCalledWith(marker);
closeSocket();
await advance(500);
act(() => MockWebSocket.instances[1]!.onopen?.(new Event("open")));
expect(term.write).toHaveBeenCalledWith(marker);
});

test("resets the retry budget only after a stable connection", async () => {
vi.useFakeTimers();
render(<TerminalPane sessionId="s1" />);
await flush();
closeSocket();
await advance(500);
act(() => MockWebSocket.instances.at(-1)!.onopen?.(new Event("open")));
closeSocket();
await advance(500);
expect(MockWebSocket.instances).toHaveLength(2);
await advance(500);
expect(MockWebSocket.instances).toHaveLength(3);
act(() => MockWebSocket.instances.at(-1)!.onopen?.(new Event("open")));
await advance(30_000);
closeSocket();
await advance(500);
expect(MockWebSocket.instances).toHaveLength(4);
});

test("changing sessions cancels the old retry and creates a fresh terminal", async () => {
vi.useFakeTimers();
const view = render(<TerminalPane sessionId="s1" />);
await flush();
closeSocket();
view.rerender(<TerminalPane sessionId="s2" />);
await flush();
await advance(60_000);
expect(MockWebSocket.instances).toHaveLength(2);
expect(MockWebSocket.instances[1]!.url).toContain("/sessions/s2/shell");
expect(MockTerminal.instances[0]!.dispose).toHaveBeenCalledTimes(1);
});
});
Loading
Loading