Merge branch 'fix/windows-local-server': a local Windows server, and ConPTY panes

This commit is contained in:
callumalpass committed 2026-11-04 16:45:03 +11:00
commit eccedd9b3b
6 files changed
+101 -9

No files matched your search

+1 -1
View File
@@ -209,7 +209,7 @@ A key after the prefix never reaches the program, and a program can't receive `c
| `r` | list everything again | | `r` | list everything again |
| `esc` | back to the conversation | | `esc` | back to the conversation |
Results take the same keys (`j`/`k`, `enter`, `m`, `y`, `p`). A preview is a tab of its own, titled with the path: code is highlighted by its extension, markdown is rendered, images are drawn, and other binary files show their size. `j`/`k` scroll it, `space`/`pgdn` and `pgup` page, `g`/`G` go to the ends, and `ctrl+\ x` or the tab's ✕ closes it and returns to Files. Files are read through the server, so previews work over SSH too. The Files tab can't be closed; `d` hides the column. Creating, renaming or deleting files is left to the agent or your editor. Results take the same keys (`j`/`k`, `enter`, `m`, `y`, `p`). A preview is a tab of its own, titled with the path: code is highlighted by its extension, markdown is rendered, images are drawn, and other binary files show their size. `j`/`k` scroll it, `space`/`pgdn` and `pgup` page, `g`/`G` go to the ends, and `ctrl+\ x` or the tab's ✕ closes it and returns to Files. Files are read through the server, so previews work over SSH too. The Files tab can't be closed; `d` hides the column. Creating, renaming or deleting files is left to the agent or your editor. On a Windows server, search and the `@` menu need the Microsoft Visual C++ Redistributable; without it they fail with `Failed to search workspace entries`, until it's installed and the server restarted.
## Workspace ## Workspace
+10 -2
View File
@@ -83,15 +83,23 @@ async function writeCredential(credential: StoredCredential): Promise<void> {
await chmod(path, 0o600); await chmod(path, 0o600);
} }
/** The `t3` CLI: the desktop app's copy, or the one on the PATH, or where the Windows installer puts it. A .cmd only runs through cmd. */
export function t3Command(exists: (path: string) => boolean = existsSync, which: (program: string) => string | null = Bun.which): string[] {
const t3 =
process.env.T3TUI_T3_BIN ??
[join(t3Home(), "bin", "t3"), which("t3"), join(homedir(), ".local", "bin", "t3.cmd")].find((path): path is string => path !== null && exists(path)) ??
"t3";
return /\.(?:cmd|bat)$/i.test(t3) ? ["cmd.exe", "/c", "call", t3] : [t3];
}
/** /**
* Issues a scoped bearer session through the local `t3` CLI, which can mint one * Issues a scoped bearer session through the local `t3` CLI, which can mint one
* because it shares the server's data directory. Remote servers need T3TUI_TOKEN. * because it shares the server's data directory. Remote servers need T3TUI_TOKEN.
*/ */
export async function issueLocalCredential(target: ServerTarget): Promise<StoredCredential> { export async function issueLocalCredential(target: ServerTarget): Promise<StoredCredential> {
const t3 = process.env.T3TUI_T3_BIN ?? join(t3Home(), "bin", "t3");
const args = ["auth", "session", "issue", "--label", "t3tui", "--token-only"]; const args = ["auth", "session", "issue", "--label", "t3tui", "--token-only"];
for (const scope of T3TUI_SCOPES) args.push("--scope", scope); for (const scope of T3TUI_SCOPES) args.push("--scope", scope);
const proc = Bun.spawn([t3, ...args], { stdout: "pipe", stderr: "pipe" }); const proc = Bun.spawn([...t3Command(), ...args], { stdout: "pipe", stderr: "pipe" });
const [stdout, stderr, code] = await Promise.all([ const [stdout, stderr, code] = await Promise.all([
new Response(proc.stdout).text(), new Response(proc.stdout).text(),
new Response(proc.stderr).text(), new Response(proc.stderr).text(),
+7 -4
View File
@@ -3,8 +3,9 @@ import { extend } from "@opentui/react";
import { useEffect, useRef, type ReactNode } from "react"; import { useEffect, useRef, type ReactNode } from "react";
import type { T3Session } from "../client/session.ts"; import type { T3Session } from "../client/session.ts";
import { isWindowsAbsolute } from "../model/paths.ts";
import { BAR } from "./edges.ts"; import { BAR } from "./edges.ts";
import type { TerminalTarget } from "./terminalAttach.ts"; import { keepConptyWrap, type TerminalTarget } from "./terminalAttach.ts";
import { colors } from "./theme.ts"; import { colors } from "./theme.ts";
import { useEvent } from "./useEvent.ts"; import { useEvent } from "./useEvent.ts";
@@ -114,6 +115,7 @@ function paint(term: EmbeddedTerminalRenderable): void {
function attachServer(session: T3Session, target: TerminalTarget, term: EmbeddedTerminalRenderable, cols: number, rows: number, close: (message?: string) => void): Link { function attachServer(session: T3Session, target: TerminalTarget, term: EmbeddedTerminalRenderable, cols: number, rows: number, close: (message?: string) => void): Link {
const { threadId, terminalId } = target; const { threadId, terminalId } = target;
const decoder = new TextDecoder(); const decoder = new TextDecoder();
const output = isWindowsAbsolute(target.cwd) ? keepConptyWrap : (data: string) => data;
let stopped = false; let stopped = false;
let detach = () => {}; let detach = () => {};
const end = (message?: string) => { const end = (message?: string) => {
@@ -131,10 +133,10 @@ function attachServer(session: T3Session, target: TerminalTarget, term: Embedded
case "restarted": case "restarted":
term.write("\x1bc"); term.write("\x1bc");
paint(term); paint(term);
term.write(event.snapshot.history); term.write(output(event.snapshot.history));
return; return;
case "output": case "output":
term.write(event.data); term.write(output(event.data));
return; return;
case "cleared": case "cleared":
term.write("\x1b[H\x1b[2J"); term.write("\x1b[H\x1b[2J");
@@ -176,12 +178,13 @@ function withoutInBandResize(data: Uint8Array): Uint8Array {
/** A program run here on its own pty, answering its terminal queries through the emulator. */ /** A program run here on its own pty, answering its terminal queries through the emulator. */
function spawnLocal(program: Extract<PaneProgram, { kind: "local" }>, term: EmbeddedTerminalRenderable, cols: number, rows: number, close: (message?: string) => void): Link { function spawnLocal(program: Extract<PaneProgram, { kind: "local" }>, term: EmbeddedTerminalRenderable, cols: number, rows: number, close: (message?: string) => void): Link {
const output = process.platform === "win32" ? (data: Uint8Array) => Buffer.from(keepConptyWrap(Buffer.from(data).toString("latin1")), "latin1") : (data: Uint8Array) => data;
let stopped = false; let stopped = false;
let child: ReturnType<typeof Bun.spawn>; let child: ReturnType<typeof Bun.spawn>;
try { try {
child = Bun.spawn([...program.command], { child = Bun.spawn([...program.command], {
...(program.cwd ? { cwd: program.cwd } : {}), ...(program.cwd ? { cwd: program.cwd } : {}),
terminal: { cols, rows, data: (_pty, data) => term.write(data) }, terminal: { cols, rows, data: (_pty, data) => term.write(output(data)) },
}); });
} catch (error) { } catch (error) {
// A missing program throws here, inside a resize; let the pane say so rather than the render loop. // A missing program throws here, inside a resize; let the pane say so rather than the render loop.
+15 -2
View File
@@ -2,6 +2,7 @@ import type { CliRenderer } from "@opentui/core";
import type { ThreadId } from "@t3tools/contracts"; import type { ThreadId } from "@t3tools/contracts";
import type { T3Session } from "../client/session.ts"; import type { T3Session } from "../client/session.ts";
import { isWindowsAbsolute } from "../model/paths.ts";
/** Ctrl+J (LF), Ctrl+] and Ctrl+J under the kitty keyboard protocol leave the terminal. */ /** Ctrl+J (LF), Ctrl+] and Ctrl+J under the kitty keyboard protocol leave the terminal. */
const DETACH_KEYS = new Set(["\n", "\x1d", "\x1b[106;5u"]); const DETACH_KEYS = new Set(["\n", "\x1d", "\x1b[106;5u"]);
@@ -17,6 +18,17 @@ export interface TerminalTarget {
readonly label: string; readonly label: string;
} }
/**
* ConPTY's output, for terminals that aren't Windows Terminal. ConPTY fills a row and goes on to
* the next by writing, relying on the wrap staying pending through a `\\x1b[K` in between; other
* terminals drop it there, as xterm does, and the next row's text lands on the last column. It
* only erases and writes on without moving when the row is full, so that erase has nothing to do.
*/
export function keepConptyWrap(data: string): string {
// biome-ignore lint/suspicious/noControlCharactersInRegex: this matches escape sequences
return data.replace(/\x1b\[K(?=(?:\x1b\[\??[\d;]*[mhl])*[^\x00-\x1f\x7f])/g, "");
}
/** /**
* Gives the whole screen to one of T3's terminals: its scrollback, then live output, with * Gives the whole screen to one of T3's terminals: its scrollback, then live output, with
* keystrokes sent to it. Ctrl+J comes back. The terminal keeps running on the server. * keystrokes sent to it. Ctrl+J comes back. The terminal keeps running on the server.
@@ -26,6 +38,7 @@ export async function attachTerminal(renderer: CliRenderer, session: T3Session,
const stdin = process.stdin; const stdin = process.stdin;
const stdout = process.stdout; const stdout = process.stdout;
const size = () => ({ cols: stdout.columns || 80, rows: stdout.rows || 24 }); const size = () => ({ cols: stdout.columns || 80, rows: stdout.rows || 24 });
const output = isWindowsAbsolute(target.cwd) ? keepConptyWrap : (data: string) => data;
let finished = false; let finished = false;
await renderer.suspend(); await renderer.suspend();
@@ -50,10 +63,10 @@ export async function attachTerminal(renderer: CliRenderer, session: T3Session,
case "snapshot": case "snapshot":
case "restarted": case "restarted":
stdout.write("\x1b[H\x1b[2J"); stdout.write("\x1b[H\x1b[2J");
stdout.write(event.snapshot.history); stdout.write(output(event.snapshot.history));
return; return;
case "output": case "output":
stdout.write(event.data); stdout.write(output(event.data));
return; return;
case "cleared": case "cleared":
stdout.write("\x1b[H\x1b[2J"); stdout.write("\x1b[H\x1b[2J");
+46
View File
@@ -0,0 +1,46 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { homedir } from "node:os";
import { join } from "node:path";
import { t3Command } from "../src/client/auth.ts";
const appCopy = join(homedir(), ".t3", "bin", "t3");
const installerCopy = join(homedir(), ".local", "bin", "t3.cmd");
describe("t3Command", () => {
const saved = { bin: process.env.T3TUI_T3_BIN, home: process.env.T3CODE_HOME };
beforeEach(() => {
delete process.env.T3TUI_T3_BIN;
delete process.env.T3CODE_HOME;
});
afterEach(() => {
delete process.env.T3TUI_T3_BIN;
if (saved.bin !== undefined) process.env.T3TUI_T3_BIN = saved.bin;
if (saved.home !== undefined) process.env.T3CODE_HOME = saved.home;
});
test("prefers the desktop app's copy, then the PATH", () => {
expect(t3Command((path) => path === appCopy, () => "/usr/bin/t3")).toEqual([appCopy]);
expect(t3Command((path) => path === "/usr/bin/t3", () => "/usr/bin/t3")).toEqual(["/usr/bin/t3"]);
});
test("runs where the Windows installer puts it, which needs cmd", () => {
expect(t3Command((path) => path === installerCopy, () => null)).toEqual(["cmd.exe", "/c", "call", installerCopy]);
});
test("runs a .cmd on the PATH through cmd too", () => {
const shim = "C:\\npm\\t3.CMD";
expect(t3Command((path) => path === shim, () => shim)).toEqual(["cmd.exe", "/c", "call", shim]);
});
test("falls back to the bare name so the error names it", () => {
expect(t3Command(() => false, () => null)).toEqual(["t3"]);
});
test("T3TUI_T3_BIN wins", () => {
process.env.T3TUI_T3_BIN = "/opt/t3";
expect(t3Command(() => true, () => "/usr/bin/t3")).toEqual(["/opt/t3"]);
});
});
+22
View File
@@ -0,0 +1,22 @@
import { describe, expect, test } from "bun:test";
import { keepConptyWrap } from "../src/ui/terminalAttach.ts";
describe("keepConptyWrap", () => {
test("drops the erase between a full row and the next one's text", () => {
expect(keepConptyWrap("~ \x1b[K~ \x1b[K~")).toBe("~ ~ ~");
});
test("sees past styling and cursor visibility", () => {
expect(keepConptyWrap("~ \x1b[K\x1b[m\x1b[1m\x1b[7mstatus")).toBe("~ \x1b[m\x1b[1m\x1b[7mstatus");
expect(keepConptyWrap("~ \x1b[K\x1b[?25l~")).toBe("~ \x1b[?25l~");
});
test("keeps an erase that ends a row", () => {
for (const data of ["short\x1b[K", "short\x1b[K\r\nnext", "short\x1b[K\x1b[3;1Hnext", "short\x1b[K\x1b[?25l\x1b[14C"]) expect(keepConptyWrap(data)).toBe(data);
});
test("leaves other erases alone", () => {
expect(keepConptyWrap("a\x1b[2Kb\x1b[1Kc")).toBe("a\x1b[2Kb\x1b[1Kc");
});
});