Remember the thread list's dragged width across runs

Kept in layout.json next to the config, as the web keeps its sidebar
width in browser storage. Tests now write to a scratch config folder.
This commit is contained in:
Callum Alpass committed 2026-11-02 23:15:33 +11:00
1 parent 320dbf492d
commit 81a1ee942c
5 files changed
+81 -8

No files matched your search

+3 -1
View File
@@ -141,9 +141,11 @@ async function runUi(attachNeedle?: string) {
const { App } = await import("./ui/App.tsx");
const { loadConfig } = await import("./config.ts");
const config = await loadConfig();
const { loadLayout } = await import("./layout.ts");
const layout = await loadLayout();
// The kitty keyboard protocol lets terminals that support it send shift+enter, for newlines.
const renderer = await createCliRenderer({ exitOnCtrlC: false, useMouse: true, useKittyKeyboard: {} });
createRoot(renderer).render(createElement(App, { session, config, ...(attachThreadId ? { attachThreadId } : {}) }));
createRoot(renderer).render(createElement(App, { session, config, layout, ...(attachThreadId ? { attachThreadId } : {}) }));
}
function fail(message: string): never {
+37
View File
@@ -0,0 +1,37 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { configDir } from "./client/auth.ts";
/**
* Where you left the layout, kept across runs as the web keeps its sidebar width in the
* browser's storage. Separate from the config: nobody edits this by hand.
*/
export interface Layout {
/** The thread list's width once its border is dragged; null follows the window. */
readonly listWidth: number | null;
}
export const DEFAULT_LAYOUT: Layout = { listWidth: null };
const layoutPath = () => join(configDir(), "layout.json");
export async function loadLayout(): Promise<Layout> {
try {
return parseLayout(JSON.parse(await readFile(layoutPath(), "utf8")));
} catch {
// None saved yet, or unreadable: start from the defaults.
return DEFAULT_LAYOUT;
}
}
export function parseLayout(raw: unknown): Layout {
const record = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
const width = record.listWidth;
return { listWidth: typeof width === "number" && Number.isInteger(width) && width > 0 ? width : null };
}
export async function saveLayout(layout: Layout): Promise<void> {
await mkdir(configDir(), { recursive: true });
await writeFile(layoutPath(), `${JSON.stringify(layout, null, 2)}\n`);
}
+19 -5
View File
@@ -11,6 +11,7 @@ import type { ServerConfigState, ShellState, T3Session, ThreadState } from "../c
import { createAlerts, type Alert } from "../model/alerts.ts";
import { modelSummary } from "../model/models.ts";
import { configPath, cycleConfig, saveConfig, type Tui3Config } from "../config.ts";
import { saveLayout, type Layout } from "../layout.ts";
import { RUNTIME_MODE_LABELS } from "../model/details.ts";
import { paletteEntries, paletteGroups, pickerGroups, type Picker, type PickerItem } from "../model/palette.ts";
import { pullRequestRepository } from "../model/pullRequests.ts";
@@ -93,7 +94,7 @@ const COMPOSER_KEYS = {
/** The composer's key while a new thread is being drafted. */
const DRAFT_KEY = "draft";
export function App(props: { readonly session: T3Session; readonly config: Tui3Config; readonly attachThreadId?: ThreadId }) {
export function App(props: { readonly session: T3Session; readonly config: Tui3Config; readonly layout?: Layout; readonly attachThreadId?: ThreadId }) {
const { session, attachThreadId } = props;
const attached = attachThreadId !== undefined;
const renderer = useRenderer();
@@ -108,7 +109,11 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
/** Folds opened one at a time by a click, for the open thread. */
const [expandedIds, setExpandedIds] = useState<ReadonlySet<string>>(() => new Set());
/** The thread list's width once its border is dragged; null follows the window. */
const [listWidthPref, setListWidthPref] = useState<number | null>(null);
const [listWidthPref, setListWidthPref] = useState<number | null>(props.layout?.listWidth ?? null);
const listWidthNow = useRef(listWidthPref);
listWidthNow.current = listWidthPref;
/** Kept for the next run; a failed save only costs that. */
const saveListWidth = (listWidth: number | null) => void saveLayout({ listWidth }).catch(() => {});
const [resizing, setResizing] = useState(false);
const [diff, setDiff] = useState<DiffState | null>(null);
const [config, setConfig] = useState(props.config);
@@ -1003,8 +1008,14 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
{...(resizing
? {
onMouseDrag: (event: MouseEvent) => setListWidthPref(clampListWidth(event.x, width)),
onMouseUp: () => setResizing(false),
onMouseDragEnd: () => setResizing(false),
onMouseUp: () => {
setResizing(false);
saveListWidth(listWidthNow.current);
},
onMouseDragEnd: () => {
setResizing(false);
saveListWidth(listWidthNow.current);
},
}
: {})}
>
@@ -1045,7 +1056,10 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
shelfStatus={library.error ?? (library.loading ? "Loading…" : library.archived ? "Archived threads · A to go back" : null)}
/>
)}
{attached ? null : <ResizeHandle active={resizing} onStart={() => setResizing(true)} onReset={() => setListWidthPref(null)} />}
{attached ? null : <ResizeHandle active={resizing} onStart={() => setResizing(true)} onReset={() => {
setListWidthPref(null);
saveListWidth(null);
}} />}
<box flexDirection="column" flexGrow={1} minHeight={0}>
<box flexDirection="column" flexGrow={1} minHeight={0} onMouseDown={focusConversation}>
{settingsIndex !== null ? (
+13
View File
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, test } from "bun:test";
import { withApproval, withQuestion } from "./fixtures.ts";
import { loadLayout } from "../../src/layout.ts";
import { fakeSession, renderApp, v2ThreadId } from "./harness.tsx";
let app: Awaited<ReturnType<typeof renderApp>> | null = null;
@@ -283,4 +284,16 @@ describe("mouse", () => {
await app.click(before + 10, 10, 2);
expect(app.find("│").x).toBe(before);
});
test("the list keeps its dragged width for the next run", async () => {
const first = await open();
const before = first.find("│").x;
await first.mockMouse.drag(before, 10, before + 7, 10);
await first.settle(100);
first.destroy();
const layout = await loadLayout();
expect(layout.listWidth).toBe(before + 7);
const next = await open({ layout });
expect(next.find("│").x).toBe(before + 7);
});
});
+9 -2
View File
@@ -1,14 +1,21 @@
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { testRender } from "@opentui/react/test-utils";
import { createMockKeys, type KeyInput } from "@opentui/core/testing";
import type { OrchestrationV2ShellSnapshot, OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contracts";
import type { ConnectionStatus, T3Session } from "../../src/client/session.ts";
import { DEFAULT_CONFIG, type Tui3Config } from "../../src/config.ts";
import type { Layout } from "../../src/layout.ts";
import { App } from "../../src/ui/App.tsx";
import { v2Projection, v2ShellSnapshot, v2ThreadId } from "../../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts";
export { v2Projection, v2ShellSnapshot, v2ThreadId };
// Settings and layout saves go to a scratch folder, never the real config.
process.env.XDG_CONFIG_HOME = mkdtempSync(join(tmpdir(), "tui3-test-"));
// Updates from the app's own timers land outside act(); the warnings say nothing useful here.
const consoleError = console.error;
console.error = (...args: unknown[]) => {
@@ -69,10 +76,10 @@ export function fakeSession(
}
/** Renders the whole app against a fake session, with helpers to drive it by key and mouse. */
export async function renderApp(options: { readonly session?: ReturnType<typeof fakeSession>; readonly config?: Partial<Tui3Config>; readonly width?: number; readonly height?: number } = {}) {
export async function renderApp(options: { readonly session?: ReturnType<typeof fakeSession>; readonly config?: Partial<Tui3Config>; readonly layout?: Layout; readonly width?: number; readonly height?: number } = {}) {
const fake = options.session ?? fakeSession();
const config = { ...DEFAULT_CONFIG, ...options.config };
const rig = await testRender(<App session={fake.session} config={config} />, { width: options.width ?? 140, height: options.height ?? 40 });
const rig = await testRender(<App session={fake.session} config={config} {...(options.layout ? { layout: options.layout } : {})} />, { width: options.width ?? 140, height: options.height ?? 40 });
// The app runs on timers and subscriptions, as it does live: tests wait for frames rather than wrap each update in act().
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = false;
const keys = createMockKeys(rig.renderer);