8000 feat(deck): pane navigation keys (#25) by simon-inkie · Pull Request #47 · simon-inkie/inkie-deck · GitHub
[go: up one dir, main page]

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
44 changes: 41 additions & 3 deletions packages/deck/app/components/TmuxPane.tsx
10000
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,30 @@ import { useFetcher } from "react-router";
import { EmptyState } from "./EmptyState";
import { TerminalSquare, CornerDownLeft } from "lucide-react";

const NAVIGATION_KEYS = [
"Up",
"Down",
"Enter",
"Escape",
"Tab",
"BTab",
] as const;

type SendData =
| { ok: true }
| { ok: false; unverified?: boolean; error: string };

/**
* The write affordance. A small textarea + Send that posts to the one send
* seam. Enter submits, Shift+Enter is a newline. Clears only after a send
* SETTLES ok, so a failed send keeps the typed text for a retry.
* SETTLES ok, so a failed send keeps the typed text for a retry. Navigation
* keys use the same seam and never clear a draft.
*/
function TmuxCompose({ sendTarget }: { sendTarget: string }) {
const fetcher = useFetcher<SendData>();
const [text, setText] = useState("");
const prevState = useRef(fetcher.state);
const sentText = useRef(false);
const busy = fetcher.state !== "idle";
const data = fetcher.data;
const error =
Expand All @@ -44,24 +55,51 @@ function TmuxCompose({ sendTarget }: { sendTarget: string }) {
: data.error
: undefined;

// Clear the box only when a submission transitions back to idle with ok.
// Clear the box only when a text submission settles successfully.
useEffect(() => {
if (prevState.current !== "idle" && fetcher.state === "idle") {
if (fetcher.data?.ok) setText("");
if (fetcher.data?.ok && sentText.current) setText("");
}
prevState.current = fetcher.state;
}, [fetcher.state, fetcher.data]);

function send() {
if (text.trim() === "" || busy) return;
sentText.current = true;
fetcher.submit(
{ window: sendTarget, text },
{ method: "post", action: "/api/tmux-send" }
);
}

function sendKey(key: (typeof NAVIGATION_KEYS)[number]) {
if (busy) return;
sentText.current = false;
fetcher.submit(
{ window: sendTarget, key },
{ method: "post", action: "/api/tmux-send" }
);
}

return (
<div className="mt-2 shrink-0">
<div
className="mb-2 flex flex-wrap gap-2"
role="group"
aria-label="Pane navigation"
>
{NAVIGATION_KEYS.map((key) => (
<button
key={key}
type="button"
disabled={busy}
=> sendKey(key)}
className="min-h-11 rounded-lg border border-border px-3 font-mono text-xs text-foreground hover:bg-primary/10 disabled:opacity-40"
>
{key === "BTab" ? "Shift+Tab" : key}
</button>
))}
</div>
{error !== undefined ? (
<p
data-testid="tmux-compose-error"
Expand Down
73 changes: 73 additions & 0 deletions packages/deck/app/lib/tmux.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,30 @@ export function buildSendKeysTextArgs(
return ["send-keys", "-t", `=${session}:=${window}`, "-l", "--", text];
}

/** Fixed navigation keys accepted by the pane send seam. */
export const SEND_KEYS_ALLOWED_KEYS = [
"Up",
"Down",
"Enter",
"Escape",
"Tab",
"BTab",
] as const;
export type PaneKey = (typeof SEND_KEYS_ALLOWED_KEYS)[number];

export function isValidPaneKey(key: string): key is PaneKey {
return SEND_KEYS_ALLOWED_KEYS.some((allowed) => allowed === key);
}

/** Named keys are single keystrokes, without literal mode or an extra Enter. */
export function buildSendKeysNamedArgs(
session: string,
window: string,
key: PaneKey
): string[] {
return ["send-keys", "-t", `=${session}:=${window}`, key];
}

/**
* argv for pressing Enter in a window. Pure - unit-pinned. No "-l": "Enter" is
* a key NAME here, not literal text - this is the keystroke that submits.
Expand Down Expand Up @@ -224,6 +248,41 @@ function runTmuxVoid(args: string[]): boolean {

export type SendKeysResult = { ok: true } | { ok: false; error: string };

/** Send one allowlisted navigation key to a live, exactly matched window. */
export function sendNamedKeyToWindow(
env: NodeJS.ProcessEnv,
window: string,
key: string
): SendKeysResult {
if (!isValidWindowName(window)) {
return { ok: false, error: "Unknown or invalid window." };
}
if (!isValidPaneKey(key)) {
return { ok: false, error: "Invalid navigation key." };
}
if (!listTmuxWindows(env).includes(window)) {
return { ok: false, error: "Window is not live in the session." };
}
return runTmuxVoid(buildSendKeysNamedArgs(resolveTmuxSession(env), window, key))
? { ok: true }
: { ok: false, error: "Could not send key to the window." };
}

/** Refuse text when the current viewport cannot be checked or shows a shell. */
function textSendRefusal(
session: string,
window: string
): string | undefined {
const viewport = runTmux(buildCaptureViewportArgs(session, window));
if (viewport === undefined) {
return "Could not check the pane before sending text.";
}
if (viewport.split("\n").some((line) => SHELL_PROMPT_RE.test(line))) {
return "The pane is at a shell prompt. Text was not submitted.";
}
return undefined;
}

/**
* tmux side effects the verified-send state machine needs, as a seam so the
* policy module stays testable without a live server.
Expand All @@ -250,7 +309,12 @@ const LIVE_SEND_KEYS_DRIVER: SendKeysDriver = {
),
sendText: (session, window, text) =>
runTmuxVoid(buildSendKeysTextArgs(session, window, text)),
// Recheck immediately before every Enter. The verified state machine proves
// the composer safe before typing and verifies the result afterwards; this
// closes the remaining delay race where the agent could exit to a shell
// after the text send but before Enter.
pressEnter: (session, window) =>
textSendRefusal(session, window) === undefined &&
runTmuxVoid(buildSendKeysEnterArgs(session, window)),
wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
};
Expand Down Expand Up @@ -684,6 +748,15 @@ export function classifyPaneSnapshot(
rawViewport?: string
): PaneSnapshot {
const lines = viewport.split("\n");
// A shell frame anywhere in the live viewport is ambiguous and therefore
// unsafe. This preserves the original text-send guard while the positive
// composer classification below supplies the stronger verified-send gate.
if (lines.some((line) => SHELL_PROMPT_RE.test(line))) {
return {
activity: paneTextIsActive(viewport) ? "active" : "idle",
composer: "unknown",
};
}
const promptIndex = findComposerOpenIndex(lines);
if (promptIndex === -1) {
return {
Expand Down
80 changes: 68 additions & 12 deletions packages/deck/app/routes/api.tmux-send.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/**
* api.tmux-send.tsx - the ONE send seam for the read/write tmux view (v2).
*
* POST { window, text } (form-encoded). Runs send-keys against the agent's
* POST { window, text } or { window, key } (form-encoded). Runs send-keys against the agent's
* window: literal text, ~1s delay, then Enter as a separate keystroke (the
* Claude TUI races a combined text+Enter). Both tmux homes (the /tmux Team tab
* Claude TUI races a combined text+Enter). Named keys send once without an
* automatic Enter. Both tmux homes (the /tmux Team tab
* and the per-thread ?view=tmux pane) POST here via useFetcher, so the send
* logic lives in exactly one place - mirrors the api.review resource-route
* precedent.
Expand All @@ -17,37 +18,92 @@
* ASCII only - no em-dashes (FND-05).
*/
import { z } from "zod";
import { data } from "react-router";
import type { Route } from "./+types/api.tmux-send";
import { sendKeysToWindow, SEND_KEYS_MAX_LEN } from "~/lib/tmux.server";
import {
sendKeysToWindow,
sendNamedKeyToWindow,
SEND_KEYS_ALLOWED_KEYS,
SEND_KEYS_MAX_LEN,
} from "~/lib/tmux.server";
import { tmuxEnabled } from "~/lib/instance.server";

const sendSchema = z.object({
window: z.string().min(1),
text: z.string().min(1).max(SEND_KEYS_MAX_LEN),
});
const windowSchema = z.string().regex(/^[a-z0-9][a-z0-9-]*$/);
const sendSchema = z.union([
z
.object({
window: windowSchema,
text: z
.string()
.min(1)
.max(SEND_KEYS_MAX_LEN)
.refine((text) => text.trim() !== ""),
})
.strict(),
z.object({ window: windowSchema, key: z.enum(SEND_KEYS_ALLOWED_KEYS) }).strict(),
]);

export async function action({ request }: Route.ActionArgs) {
// TASK-462: server-side gate, not just hidden UI - a tmux-disabled instance
// (Robin's) refuses sends even if the endpoint is POSTed directly.
if (!tmuxEnabled(process.env)) {
return { ok: false as const, error: "The terminal is not available on this instance." };
return {
ok: false as const,
error: "The terminal is not available on this instance.",
};
}
let formData: FormData;
try {
formData = await request.formData();
} catch {
return data(
{ ok: false as const, error: "Invalid send payload." },
{ status: 400 }
);
}
if (
["window", "text", "key"].some(
(field) => formData.getAll(field).length > 1
)
) {
return data(
{ ok: false as const, error: "Invalid send payload." },
{ status: 400 }
);
}
const formData = await request.formData();
const parsed = sendSchema.safeParse(Object.fromEntries(formData));
if (!parsed.success) {
return { ok: false as const, error: "Invalid send payload." };
return data(
{ ok: false as const, error: "Invalid send payload." },
{ status: 400 }
);
}
if ("key" in parsed.data) {
return sendNamedKeyToWindow(
process.env,
parsed.data.window,
parsed.data.key
);
}
// sendKeysToWindow carries the ROSTER + live-allowlist gate, verifies the
// submit, and degrades to { ok: false } on any failure - it never throws.
const result = await sendKeysToWindow(process.env, parsed.data.window, parsed.data.text);
const result = await sendKeysToWindow(
process.env,
parsed.data.window,
parsed.data.text
);
if (result.status === "submitted") {
return { ok: true as const };
}
// "unverified" means text AND Enter were sent but delivery could not be
// proven. Surface it distinctly so the operator is told "sent, could not
// confirm" rather than "failed", which would invite a duplicate resend.
if (result.status === "unverified") {
return { ok: false as const, unverified: true as const, error: result.error };
return {
ok: false as const,
unverified: true as const,
error: result.error,
};
}
return { ok: false as const, error: result.error };
}
89 changes: 89 additions & 0 deletions packages/deck/test/tmux-pane-navigation.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";

vi.mock("react-router", () => ({ useFetcher: vi.fn() }));
import { useFetcher } from "react-router";
import { TmuxPane } from "~/components/TmuxPane";

(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
let container: HTMLDivElement;
let root: Root;
const submit = vi.fn();
let fetcher: { state: string; data: { ok: boolean; error?: string } | undefined; submit: typeof submit };

beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
submit.mockReset();
fetcher = { state: "idle", data: undefined, submit };
vi.mocked(useFetcher).mockImplementation(() => fetcher as unknown as ReturnType<typeof useFetcher>);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
function render(sendTarget: string | undefined = "agent", pane: string | undefined = "Trust directory?") {
act(() => root.render(<TmuxPane pane={pane} windowName="agent" sendTarget={sendTarget} />));
}
function button(label: string) {
return Array.from(container.querySelectorAll("button")).find((b) => b.textContent === label)!;
}
function draft(text: string) {
const input = container.querySelector("textarea")!;
act(() => {
Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(input, text);
input.dispatchEvent(new Event("input", { bubbles: true }));
});
}
function settle(ok: boolean) {
fetcher.state = "submitting";
render();
fetcher.state = "idle";
fetcher.data = ok ? { ok: true } : { ok: false, error: "Unavailable" };
render();
}

describe("shared pane navigation", () => {
it.each(["Up", "Down", "Enter", "Escape", "Tab", "Shift+Tab"])("posts %s as one key and retains the draft", (label) => {
render();
draft("draft message");
act(() => button(label).click());
expect(submit).toHaveBeenCalledExactlyOnceWith(
{ window: "agent", key: label === "Shift+Tab" ? "BTab" : label },
{ method: "post", action: "/api/tmux-send" }
);
settle(true);
expect(container.querySelector("textarea")!.value).toBe("draft message");
});

it("clears a successful text send and retains a failed one", () => {
render();
draft("draft message");
act(() => button("Send").click());
settle(false);
expect(container.querySelector("textarea")!.value).toBe("draft message");
act(() => button("Send").click());
settle(true);
expect(container.querySelector("textarea")!.value).toBe("");
});

it("disables all send controls while a submission is pending", () => {
fetcher.state = "submitting";
render();
expect(Array.from(container.querySelectorAll("button")).every((b) => b.disabled)).toBe(true);
});

it("keeps navigation available for a transiently unavailable pane", () => {
render("agent", undefined);
expect(button("Up")).toBeDefined();
});

it("renders no send controls for a read-only pane", () => {
act(() => root.render(<TmuxPane pane="Trust directory?" windowName="agent" />));
expect(container.querySelector("button")).toBeNull();
expect(container.querySelector("textarea")).toBeNull();
});
});
Loading
Loading
0