Merge remote-tracking branch 'origin/main' into haiky
# Conflicts: # crates/maestro-daemon/src/session.rs # crates/maestro-protocol/src/lib.rs # crates/maestro-protocol/src/routes.rs
This commit is contained in:
@@ -91,6 +91,22 @@ export async function killSession(id: Uuid, force = false): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
/** Report whether this client's pane is the one currently showing `id` — not
|
||||
* merely highlighted in a sidebar. The daemon uses this to clear an
|
||||
* `AwaitingInput` glow once the pane has been looked at long enough
|
||||
* (docs/SIDEBAR.md). Best-effort: a failure here only delays the glow
|
||||
* clearing, so callers don't need to surface it. */
|
||||
export async function setSessionFocus(id: Uuid, focused: boolean): Promise<void> {
|
||||
await jsonOrError(
|
||||
await fetch(routes.sessionFocus(id), {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ focused }),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** List one directory's immediate subdirectories (NAP-329). `path` may be empty,
|
||||
* `~`, relative, or absolute — the daemon resolves it against its home dir. */
|
||||
export async function listDir(path: string): Promise<DirListing> {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Terminal } from "@xterm/xterm";
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
|
||||
import { attachWsUrl } from "./routes.js";
|
||||
import { FOCUS_SIDEBAR_EVENT } from "./catalog.js";
|
||||
import { escapeHtml } from "./html.js";
|
||||
import { INITIAL_RECONNECT_MS, MAX_RECONNECT_MS } from "./reconnect.js";
|
||||
import { applyModsToChar, cursorSeq, tildeSeq } from "./keys.js";
|
||||
@@ -134,6 +135,15 @@ export function createAttachConnection(
|
||||
term.loadAddon(fit);
|
||||
term.open(body);
|
||||
|
||||
// Plain Escape hands the keyboard back to the session list instead of the
|
||||
// shell/app. `false` tells xterm to skip its own handling of this event.
|
||||
term.attachCustomKeyEventHandler((e) => {
|
||||
if (e.type !== "keydown" || e.key !== "Escape") return true;
|
||||
if (e.ctrlKey || e.altKey || e.metaKey || e.shiftKey) return true;
|
||||
document.dispatchEvent(new CustomEvent(FOCUS_SIDEBAR_EVENT));
|
||||
return false;
|
||||
});
|
||||
|
||||
// Touch scrolling: xterm's built-in touch handling is jittery (drags crawl a
|
||||
// line at a time and stall), so map finger drags ourselves. Two routes:
|
||||
// • normal buffer → term.scrollLines walks the scrollback.
|
||||
|
||||
+17
-2
@@ -37,14 +37,26 @@ export function requestOpenSpawn(): void {
|
||||
}
|
||||
|
||||
/** Ask the shell to hand the keyboard back to the focused pane's terminal —
|
||||
* what Escape in the sidebar list does. Handled in main.ts, which owns the
|
||||
* what Tab in the sidebar list does. Handled in main.ts, which owns the
|
||||
* connection pool. */
|
||||
export const FOCUS_PANE_EVENT = "catalog-focus-pane";
|
||||
|
||||
/** Ask the shell to hand the keyboard back to the session list — what Escape
|
||||
* does when the pane's terminal is focused. Handled in main.ts. */
|
||||
export const FOCUS_SIDEBAR_EVENT = "catalog-focus-sidebar";
|
||||
|
||||
/** Ask the shell to open the spawn modal seeded from an existing session
|
||||
* ("Spawn similar"). Detail is the session being cloned. */
|
||||
export const SPAWN_SIMILAR_EVENT = "catalog-spawn-similar";
|
||||
|
||||
/** A session row was clicked (issue #133). The row's `href` drives normal
|
||||
* hash navigation, but a split/drag can move focus without ever touching
|
||||
* `location.hash` — so a click back onto a session whose hash still
|
||||
* matches fires no `hashchange` and the app never hears about it. This
|
||||
* event is the click-driven path that doesn't depend on the hash actually
|
||||
* changing. */
|
||||
export const SESSION_SELECT_EVENT = "catalog-session-select";
|
||||
|
||||
/** The rows a keyboard walk stops on, in visual (document) order. Expanded
|
||||
* folder headers are skipped: a directory is not something to focus, and the
|
||||
* cards under it are one row away anyway. A *collapsed* folder still counts —
|
||||
@@ -193,6 +205,9 @@ function renderNode(node: TreeNode, depth: number): HTMLElement {
|
||||
ev.stopPropagation();
|
||||
void requestKill(s, name);
|
||||
});
|
||||
row.addEventListener("click", () => {
|
||||
document.dispatchEvent(new CustomEvent(SESSION_SELECT_EVENT, { detail: s.id }));
|
||||
});
|
||||
row.addEventListener("contextmenu", (ev) => {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
@@ -558,7 +573,7 @@ export function renderSidebar(store: CatalogStore, opts: SidebarOptions = {}): S
|
||||
if (e.key === "j" || e.key === "ArrowDown") moveNav(1);
|
||||
else if (e.key === "k" || e.key === "ArrowUp") moveNav(-1);
|
||||
else if (e.key === "Enter") activateNav();
|
||||
else if (e.key === "Escape") document.dispatchEvent(new CustomEvent(FOCUS_PANE_EVENT));
|
||||
else if (e.key === "Tab") document.dispatchEvent(new CustomEvent(FOCUS_PANE_EVENT));
|
||||
else return;
|
||||
e.preventDefault();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ConnectionPool } from "./connections.js";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
const A = "aaaaaaaa-0000-0000-0000-0000000000ff";
|
||||
const B = "bbbbbbbb-0000-0000-0000-0000000000ff";
|
||||
|
||||
function mockFetch() {
|
||||
const fetchMock = vi.fn(() => Promise.resolve(new Response(null, { status: 204 })));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
return fetchMock;
|
||||
}
|
||||
|
||||
describe("ConnectionPool.setFocus", () => {
|
||||
it("reports the new session focused, none unfocused, the first time", () => {
|
||||
const fetchMock = mockFetch();
|
||||
const pool = new ConnectionPool();
|
||||
|
||||
pool.setFocus(A);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect(url).toBe(`/api/sessions/${A}/focus`);
|
||||
expect(init.method).toBe("POST");
|
||||
expect(JSON.parse(init.body as string)).toEqual({ focused: true });
|
||||
});
|
||||
|
||||
it("unfocuses the previous session and focuses the new one on a switch", () => {
|
||||
const fetchMock = mockFetch();
|
||||
const pool = new ConnectionPool();
|
||||
pool.setFocus(A);
|
||||
fetchMock.mockClear();
|
||||
|
||||
pool.setFocus(B);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
const bodies = fetchMock.mock.calls.map(([url, init]: unknown[]) => [
|
||||
url,
|
||||
JSON.parse((init as RequestInit).body as string),
|
||||
]);
|
||||
expect(bodies).toContainEqual([`/api/sessions/${A}/focus`, { focused: false }]);
|
||||
expect(bodies).toContainEqual([`/api/sessions/${B}/focus`, { focused: true }]);
|
||||
});
|
||||
|
||||
it("reports unfocused when focus clears to null", () => {
|
||||
const fetchMock = mockFetch();
|
||||
const pool = new ConnectionPool();
|
||||
pool.setFocus(A);
|
||||
fetchMock.mockClear();
|
||||
|
||||
pool.setFocus(null);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect(url).toBe(`/api/sessions/${A}/focus`);
|
||||
expect(JSON.parse(init.body as string)).toEqual({ focused: false });
|
||||
});
|
||||
|
||||
it("is a no-op when the focused session doesn't change", () => {
|
||||
const fetchMock = mockFetch();
|
||||
const pool = new ConnectionPool();
|
||||
pool.setFocus(A);
|
||||
fetchMock.mockClear();
|
||||
|
||||
pool.setFocus(A);
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not let a fetch rejection break the pool", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(() => Promise.reject(new Error("offline"))),
|
||||
);
|
||||
const pool = new ConnectionPool();
|
||||
|
||||
expect(() => pool.setFocus(A)).not.toThrow();
|
||||
// Let the rejected promise's `.catch` settle before the test ends.
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
type AttachConnection,
|
||||
type AttachInfo,
|
||||
} from "./attach.js";
|
||||
import { setSessionFocus } from "./api.js";
|
||||
import type { Uuid } from "./types.js";
|
||||
|
||||
/**
|
||||
@@ -122,9 +123,16 @@ export class ConnectionPool {
|
||||
for (const e of entries) this.mount(e.id, e.pane, e.info);
|
||||
}
|
||||
|
||||
/** Also tells the daemon which pane is focused (docs/SIDEBAR.md's
|
||||
* `AwaitingInput` auto-clear) — the sidebar highlight never calls this,
|
||||
* only a pane actually becoming the visible view. Best-effort: a failed
|
||||
* report only delays the glow clearing. */
|
||||
setFocus(id: Uuid | null): void {
|
||||
if (id === this.focusedId) return;
|
||||
const previous = this.focusedId;
|
||||
this.focusedId = id;
|
||||
if (previous !== null) void setSessionFocus(previous, false).catch(() => {});
|
||||
if (id !== null) void setSessionFocus(id, true).catch(() => {});
|
||||
this.opts.onFocusChange?.(id);
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,30 @@ describe("resolveFastForward (#67)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the focused session's project over the freshest one", () => {
|
||||
const projects = [
|
||||
project({ path: "/repos/fresh", name: "fresh", last_command: "claude" }),
|
||||
project({
|
||||
path: "/repos/current",
|
||||
name: "current",
|
||||
last_activity: "2020-01-01T00:00:00Z",
|
||||
last_command: "zsh",
|
||||
}),
|
||||
];
|
||||
const res = resolveFastForward(projects, presets, "n", "/repos/current");
|
||||
expect(res.project?.path).toBe("/repos/current");
|
||||
expect(res.command).toBe("zsh");
|
||||
});
|
||||
|
||||
it("falls back to the freshest project when the focused cwd is unknown", () => {
|
||||
const projects = [
|
||||
project({ path: "/repos/old", name: "old", last_activity: "2020-01-01T00:00:00Z" }),
|
||||
project({ path: "/repos/fresh", name: "fresh" }),
|
||||
];
|
||||
const res = resolveFastForward(projects, presets, "n", "/repos/gone");
|
||||
expect(res.project?.path).toBe("/repos/fresh");
|
||||
});
|
||||
|
||||
it("falls back to the first non-custom preset when there is no last command", () => {
|
||||
const res = resolveFastForward([project({ last_command: undefined })], presets, "n");
|
||||
expect(res.command).toBe("claude");
|
||||
|
||||
@@ -13,15 +13,20 @@ export interface FastForwardResolution {
|
||||
name?: string;
|
||||
}
|
||||
|
||||
/** The defaults: most recent project (fresh-first, same ordering the picker
|
||||
* shows), its last command falling back to the first non-custom preset, and
|
||||
* a freshly generated name when the daemon supplied one. */
|
||||
/** The defaults: the currently focused session's project when it's still a
|
||||
* known project, else the most recent one (fresh-first, same ordering the
|
||||
* picker shows) — so `N` lands where the operator currently is, matching
|
||||
* what plain `n` seeds from `spawnSimilarProjectSeed`. Its last command
|
||||
* falls back to the first non-custom preset, and the name is freshly
|
||||
* generated when the daemon supplied one. */
|
||||
export function resolveFastForward(
|
||||
projects: Project[],
|
||||
presets: SpawnPreset[],
|
||||
name?: string,
|
||||
focusedCwd?: string,
|
||||
): FastForwardResolution {
|
||||
const project = sortProjects(projects, new Date())[0];
|
||||
const project =
|
||||
projects.find((p) => p.path === focusedCwd) ?? sortProjects(projects, new Date())[0];
|
||||
const lastCommand = project?.last_command?.trim();
|
||||
const command =
|
||||
lastCommand || presets.find((p) => p.command !== "")?.command || undefined;
|
||||
|
||||
+2
-1
@@ -31,7 +31,8 @@ export const SHORTCUTS: ShortcutGroup[] = [
|
||||
{ keys: ["j"], description: "Highlight the next session" },
|
||||
{ keys: ["k"], description: "Highlight the previous session" },
|
||||
{ keys: ["Enter"], description: "Open the highlighted session, or expand a folder" },
|
||||
{ keys: ["Esc"], description: "Hand the keyboard back to the pane" },
|
||||
{ keys: ["Tab"], description: "Send the keyboard to the pane" },
|
||||
{ keys: ["Esc"], description: "Hand the keyboard back to the session list, from the pane" },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
+46
-8
@@ -29,7 +29,13 @@ import { mountHud, type Hud } from "./hud.js";
|
||||
import { emptyLayout, type Layout, openSessions } from "./layout.js";
|
||||
import { createMultiView, type MultiView } from "./multiview.js";
|
||||
import { loadLayout, saveLayout } from "./persistence.js";
|
||||
import { FOCUS_PANE_EVENT, OPEN_SPAWN_EVENT, SPAWN_SIMILAR_EVENT } from "./catalog.js";
|
||||
import {
|
||||
FOCUS_PANE_EVENT,
|
||||
FOCUS_SIDEBAR_EVENT,
|
||||
OPEN_SPAWN_EVENT,
|
||||
SESSION_SELECT_EVENT,
|
||||
SPAWN_SIMILAR_EVENT,
|
||||
} from "./catalog.js";
|
||||
import { initTheme } from "./theme.js";
|
||||
import { sessionName, type Project, type Session, type SpawnPreset } from "./types.js";
|
||||
import { installViewportSizing } from "./viewport.js";
|
||||
@@ -257,13 +263,28 @@ function requestOpenSpawn(): void {
|
||||
// beside it is the point.
|
||||
// The session you were last on preselects its project: `n` then Enter spawns
|
||||
// another session there without touching the picker.
|
||||
const focused = mv?.focusedSessionId() ?? null;
|
||||
const current = focused ? store.snapshot().sessions.get(focused) : undefined;
|
||||
const current = focusedSession();
|
||||
openSpawnModal({
|
||||
seed: current ? spawnSimilarProjectSeed(current) : undefined,
|
||||
onSuccess: (session) => mountSpawned(session, { newTab: true }),
|
||||
});
|
||||
}
|
||||
|
||||
/** The session the operator was last on, if any. Shared by the plain spawn
|
||||
* modal seed and fast-forward's project pick: both should land on "where I
|
||||
* currently am". */
|
||||
function focusedSession(): Session | undefined {
|
||||
const focused = mv?.focusedSessionId() ?? null;
|
||||
return focused ? store.snapshot().sessions.get(focused) : undefined;
|
||||
}
|
||||
|
||||
/** The focused session's project — its base repo for a worktree session, its
|
||||
* cwd otherwise (same rule as spawnSimilarProjectSeed). */
|
||||
function focusedProjectCwd(): string | undefined {
|
||||
const s = focusedSession();
|
||||
if (!s) return undefined;
|
||||
return s.worktree ? s.worktree.base_repo : s.cwd;
|
||||
}
|
||||
document.addEventListener(OPEN_SPAWN_EVENT, () => requestOpenSpawn());
|
||||
document.addEventListener(SPAWN_SIMILAR_EVENT, (ev) => {
|
||||
const s = (ev as CustomEvent<Session>).detail;
|
||||
@@ -298,7 +319,7 @@ async function requestFastForward(): Promise<void> {
|
||||
} catch {
|
||||
/* keep fallbacks */
|
||||
}
|
||||
const resolved = resolveFastForward(discovered, presets, name);
|
||||
const resolved = resolveFastForward(discovered, presets, name, focusedProjectCwd());
|
||||
const req = buildFastForwardRequest(resolved);
|
||||
if (req) {
|
||||
try {
|
||||
@@ -352,8 +373,27 @@ window.addEventListener("keydown", (e) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Escape in the session list hands the keyboard back to the pane.
|
||||
// Tab in the session list hands the keyboard to the pane; Escape in the pane
|
||||
// hands it back — the pair the TUI gets from `tab` and `esc`.
|
||||
document.addEventListener(FOCUS_PANE_EVENT, () => pool.focusTerminal());
|
||||
document.addEventListener(FOCUS_SIDEBAR_EVENT, () => {
|
||||
drawer.open(); // no-op on desktop; on mobile the list is off-canvas
|
||||
sidebar.focusList();
|
||||
});
|
||||
|
||||
/** Open/focus a session and reflect it in the shell chrome. Shared by the
|
||||
* hash router and the sidebar's click-driven path (#133), which can't rely
|
||||
* on `hashchange` alone — a split or drag can move focus without the hash
|
||||
* changing, leaving a click back onto that session's row silently ignored. */
|
||||
function focusSession(sessionId: string): void {
|
||||
showMultiView();
|
||||
mv.openSession(sessionId);
|
||||
updateShellRoute();
|
||||
}
|
||||
|
||||
document.addEventListener(SESSION_SELECT_EVENT, (e) => {
|
||||
focusSession((e as CustomEvent<string>).detail);
|
||||
});
|
||||
|
||||
type Route =
|
||||
| { kind: "catalog" }
|
||||
@@ -373,9 +413,7 @@ function dispatch(): void {
|
||||
switch (route.kind) {
|
||||
case "attach":
|
||||
// Deep-link: open/focus the session, then show the layout.
|
||||
showMultiView();
|
||||
mv.openSession(route.sessionId);
|
||||
updateShellRoute();
|
||||
focusSession(route.sessionId);
|
||||
return;
|
||||
case "not-found":
|
||||
shellEl.dataset.route = "notfound";
|
||||
|
||||
@@ -33,6 +33,10 @@ export function attach(id: Uuid): string {
|
||||
return `${API_PREFIX}/attach/${encodeURIComponent(id)}`;
|
||||
}
|
||||
|
||||
export function sessionFocus(id: Uuid): string {
|
||||
return `${session(id)}/focus`;
|
||||
}
|
||||
|
||||
/** Append the `path` query parameter `DIRS` and `GITROOT` accept. */
|
||||
export function withPathQuery(route: string, value: string): string {
|
||||
return `${route}?${PATH_QUERY}=${encodeURIComponent(value)}`;
|
||||
|
||||
@@ -109,11 +109,11 @@ describe("sidebar keyboard navigation", () => {
|
||||
expect(handle.hasListFocus()).toBe(true);
|
||||
});
|
||||
|
||||
it("Escape asks the shell for the pane back", () => {
|
||||
it("Tab asks the shell for the pane back", () => {
|
||||
const { el } = twoFolders();
|
||||
let asked = 0;
|
||||
document.addEventListener(FOCUS_PANE_EVENT, () => (asked += 1));
|
||||
press(tree(el), "Escape");
|
||||
press(tree(el), "Tab");
|
||||
expect(asked).toBe(1);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user