fix(web): address review feedback on mobile pickers + multi-terminal

Bots flagged a real first-mount bug and a handful of smaller items;
addressed each:

- mobile-terminal-pane: track xterm in state instead of a ref so the
  active-sender registration effect re-runs once xterm is ready. With
  the ref, the effect ran once on mount, found xtermRef.current === null
  while PassthroughTerminal was still initializing (notably under the
  ResizeObserver fallback path when the container starts at 0×0), and
  silently never registered — leaving the key-bar wired to the default
  shell instead of the visible terminal.
- send-shell-input: wrap the activeSender call in try/catch so a stale
  registry entry (xterm GC'd mid-frame) falls back to the WS path
  instead of dropping the keystroke and silently consuming modifiers.
  Added tests for the activeSender routing branch (success, modifier
  consumption, fallback on throw).
- mobile-sessions-section: remove the dead `showCloseConfirm ? "Delete" : "Delete"`
  ternary and the unused prop on SessionActionsMenu.
- use-mobile-terminals: clear the auto-create guard when addTerminal()
  rejects so the user gets a retry instead of an empty terminal list.
- mobile-repo-pill: sort taskRepos by position before falling back to
  the first repo, so the pill label matches the picker's ordering when
  no session is active yet.
- session-task-switcher-sheet-hooks: catch loadTaskSessionsForTask
  rejection in handleSelectTask (was an unhandled rejection that left
  the sheet open on backend errors), and stabilize useCallback deps in
  handleWorkspaceChange by spreading the SheetNavOptions fields so a
  fresh literal each render doesn't defeat memoization. Extracted
  selectTaskWithoutPrimarySession to keep useSheetActions under the
  function-size lint cap.
This commit is contained in:
José Almeida
2026-05-06 01:56:17 +01:00
parent 2e52e96aaf
commit 9dc7f8a43b
7 changed files with 136 additions and 41 deletions
@@ -37,8 +37,11 @@ function useTaskActiveRepoName(taskId: string | null, workspaceId: string | null
});
return useMemo(() => {
if (!activeRepoId) {
// Fallback to the first task repo when no session is active yet.
const fallback = taskRepos?.[0]?.repository_id;
// Fallback to the position-primary task repo when no session is active
// yet. Match the picker's ordering (mobile-repos-section sorts by
// position) so the pill label and the first sheet row agree.
const sorted = taskRepos ? [...taskRepos].sort((a, b) => a.position - b.position) : [];
const fallback = sorted[0]?.repository_id;
if (!fallback) return null;
const repo = workspaceRepos.find((r) => r.id === fallback);
return repo?.name ?? repo?.local_path ?? null;
@@ -89,7 +89,6 @@ function StateBadge({ state }: { state: TaskSessionState | null }) {
function SessionActionsMenu({
state,
isPrimary,
showCloseConfirm,
onSetPrimary,
onStop,
onResume,
@@ -97,7 +96,6 @@ function SessionActionsMenu({
}: {
state: TaskSessionState | null;
isPrimary: boolean;
showCloseConfirm: boolean;
onSetPrimary: () => void;
onStop: () => void;
onResume: () => void;
@@ -140,7 +138,7 @@ function SessionActionsMenu({
className="cursor-pointer text-destructive focus:text-destructive"
onSelect={onAskDelete}
>
{showCloseConfirm ? "Delete" : "Delete"}
Delete
</DropdownMenuItem>
)}
</DropdownMenuContent>
@@ -246,7 +244,6 @@ function SessionRowItem({
<SessionActionsMenu
state={row.state}
isPrimary={row.isPrimary}
showCloseConfirm
onSetPrimary={() => void actions.setPrimary()}
onStop={() => void actions.stop()}
onResume={() => void actions.resume()}
@@ -1,6 +1,6 @@
"use client";
import { memo, useEffect, useRef } from "react";
import { memo, useEffect, useState } from "react";
import { PassthroughTerminal } from "../passthrough-terminal";
import { useMobileTerminals } from "@/hooks/domains/session/use-mobile-terminals";
import { setActiveTerminalSender } from "@/lib/terminal/mobile-active-terminal";
@@ -17,18 +17,20 @@ function TerminalSlot({
environmentId: string | null;
isActive: boolean;
}) {
const xtermRef = useRef<XtermTerminal | null>(null);
// Track xterm in state so the registration effect re-runs when the instance
// becomes available. PassthroughTerminal initialises xterm asynchronously
// when the container starts at 0×0 (ResizeObserver fallback), so a ref-based
// dependency would silently miss that path on first mount.
const [xterm, setXterm] = useState<XtermTerminal | null>(null);
// Register the active terminal sender so the mobile key-bar can target this
// xterm via paste(), which routes through xterm.onData → AttachAddon → WS.
useEffect(() => {
if (!isActive) return;
const xterm = xtermRef.current;
if (!xterm) return;
if (!isActive || !xterm) return;
const sender = (data: string) => xterm.paste(data);
setActiveTerminalSender(sender);
return () => setActiveTerminalSender(null);
}, [isActive, terminal.id]);
}, [isActive, xterm]);
return (
<div className={`absolute inset-0 ${isActive ? "block" : "hidden"}`}>
@@ -39,9 +41,7 @@ function TerminalSlot({
label={terminal.label}
autoFocus={isActive}
disableWebgl
onXtermReady={(x) => {
xtermRef.current = x;
}}
onXtermReady={setXterm}
/>
</div>
);
@@ -209,14 +209,30 @@ async function switchWorkspace(newWorkspaceId: string, opts: SheetNavOptions) {
}
function useWorkspaceAndTaskCreatedActions(opts: SheetNavOptions) {
const { workspaceId, store, setActiveSession, setActiveTask, onOpenChange } = opts;
const {
workspaceId,
store,
loadTaskSessionsForTask,
setActiveSession,
setActiveTask,
onOpenChange,
} = opts;
const handleWorkspaceChange = useCallback(
async (newWorkspaceId: string) => {
if (newWorkspaceId === workspaceId) return;
await switchWorkspace(newWorkspaceId, opts);
await switchWorkspace(newWorkspaceId, {
workspaceId,
store,
loadTaskSessionsForTask,
setActiveSession,
setActiveTask,
onOpenChange,
});
},
[workspaceId, opts],
// Spread the individual fields rather than the `opts` object so callers
// re-passing a fresh literal each render don't defeat memoization.
[workspaceId, store, loadTaskSessionsForTask, setActiveSession, setActiveTask, onOpenChange],
);
const handleTaskCreated = useCallback(
@@ -264,6 +280,42 @@ function useWorkspaceAndTaskCreatedActions(opts: SheetNavOptions) {
return { handleWorkspaceChange, handleTaskCreated };
}
type SelectTaskOptions = {
setActiveTask: (taskId: string) => void;
setActiveSession: (taskId: string, sessionId: string) => void;
loadTaskSessionsForTask: SheetNavOptions["loadTaskSessionsForTask"];
onOpenChange: (open: boolean) => void;
};
async function selectTaskWithoutPrimarySession(taskId: string, opts: SelectTaskOptions) {
const { setActiveTask, setActiveSession, loadTaskSessionsForTask, onOpenChange } = opts;
try {
const sessions = await loadTaskSessionsForTask(taskId);
const sessionId = sessions[0]?.id ?? null;
if (sessionId) {
setActiveSession(taskId, sessionId);
replaceTaskUrl(taskId);
onOpenChange(false);
return;
}
// No session — prepare workspace.
const { request } = buildPrepareRequest(taskId);
try {
const resp = await launchSession(request);
if (resp.session_id) setActiveSession(taskId, resp.session_id);
} catch {
// Fall through to default navigation.
}
} catch (error) {
// Loading sessions can reject (network / 5xx). Don't strand the user;
// fall back to plain task navigation so URL + state still align with tap.
console.error("Failed to load sessions for task:", error);
}
setActiveTask(taskId);
replaceTaskUrl(taskId);
onOpenChange(false);
}
export function useSheetActions(workspaceId: string | null, onOpenChange: (open: boolean) => void) {
const setActiveTask = useAppStore((state) => state.setActiveTask);
const setActiveSession = useAppStore((state) => state.setActiveSession);
@@ -284,27 +336,11 @@ export function useSheetActions(workspaceId: string | null, onOpenChange: (open:
onOpenChange(false);
return;
}
loadTaskSessionsForTask(taskId).then(async (sessions) => {
const sessionId = sessions[0]?.id ?? null;
if (sessionId) {
setActiveSession(taskId, sessionId);
replaceTaskUrl(taskId);
onOpenChange(false);
return;
}
// No session — prepare workspace.
const { request } = buildPrepareRequest(taskId);
try {
const resp = await launchSession(request);
if (resp.session_id) {
setActiveSession(taskId, resp.session_id);
}
} catch {
// Fall through to default behavior.
}
setActiveTask(taskId);
replaceTaskUrl(taskId);
onOpenChange(false);
void selectTaskWithoutPrimarySession(taskId, {
setActiveTask,
setActiveSession,
loadTaskSessionsForTask,
onOpenChange,
});
},
[loadTaskSessionsForTask, setActiveSession, setActiveTask, store, onOpenChange],
@@ -33,7 +33,17 @@ export function useMobileTerminals(sessionId: string | null) {
return;
}
autoCreatedRef.current = environmentId;
addTerminalRef.current();
// Reset the guard if creation fails so the user gets a retry on the next
// render cycle (e.g. after the WS reconnects). addTerminal returns void
// but its inner promise can still reject; guard defensively.
const result = addTerminalRef.current() as unknown;
if (result && typeof (result as Promise<unknown>).catch === "function") {
(result as Promise<unknown>).catch(() => {
if (autoCreatedRef.current === environmentId) {
autoCreatedRef.current = null;
}
});
}
}, [environmentId, shellsLoaded, shells.length]);
return { ...result, environmentId };
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { useShellModifiersStore } from "./shell-modifiers";
import { setActiveTerminalSender } from "./mobile-active-terminal";
const sendMock = vi.fn();
let clientFactory: () => { send: typeof sendMock } | null = () => ({ send: sendMock });
@@ -17,6 +18,7 @@ beforeEach(() => {
sendMock.mockReset();
clientFactory = () => ({ send: sendMock });
useShellModifiersStore.getState().reset();
setActiveTerminalSender(null);
});
function lastFrameData(): string | undefined {
@@ -77,4 +79,37 @@ describe("sendShellInput", () => {
expect(sendMock).not.toHaveBeenCalled();
expect(useShellModifiersStore.getState().ctrl).toEqual({ latched: true, sticky: false });
});
describe("with an active mobile terminal sender registered", () => {
it("routes input through the active sender and bypasses WS", () => {
const sender = vi.fn();
setActiveTerminalSender(sender);
sendShellInput(SESSION, "ls");
expect(sender).toHaveBeenCalledWith("ls");
expect(sendMock).not.toHaveBeenCalled();
});
it("applies modifiers and consumes them after a successful sender call", () => {
const sender = vi.fn();
setActiveTerminalSender(sender);
useShellModifiersStore.getState().toggleCtrl();
sendShellInput(SESSION, "c");
expect(sender).toHaveBeenCalledWith("\x03");
expect(useShellModifiersStore.getState().ctrl).toEqual({ latched: false, sticky: false });
});
it("falls back to WS when the sender throws", () => {
const sender = vi.fn(() => {
throw new Error("xterm gone");
});
setActiveTerminalSender(sender);
sendShellInput(SESSION, "ls");
expect(sender).toHaveBeenCalledWith("ls");
expect(sendMock).toHaveBeenCalledWith({
type: "request",
action: "shell.input",
payload: { session_id: SESSION, data: "ls" },
});
});
});
});
+15 -1
View File
@@ -25,7 +25,21 @@ export function sendShellInput(sessionId: string, data: string): void {
const activeSender = getActiveTerminalSender();
if (activeSender) {
activeSender(transformed);
try {
activeSender(transformed);
} catch (err) {
// A stale registry entry (e.g. xterm disposed mid-frame) shouldn't
// silently drop the keystroke nor consume modifiers. Fall through to
// the WS path so the input still has a chance of landing.
console.error("Active terminal sender threw, falling back to shell.input:", err);
const client = getWebSocketClient();
if (!client) return;
client.send({
type: "request",
action: "shell.input",
payload: { session_id: sessionId, data: transformed },
});
}
} else {
const client = getWebSocketClient();
if (!client) return; // keep modifiers armed; user can retry once reconnected