diff --git a/apps/web/components/task/mobile/mobile-repo-pill.tsx b/apps/web/components/task/mobile/mobile-repo-pill.tsx index d0f5af0afa..e20552fc79 100644 --- a/apps/web/components/task/mobile/mobile-repo-pill.tsx +++ b/apps/web/components/task/mobile/mobile-repo-pill.tsx @@ -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; diff --git a/apps/web/components/task/mobile/mobile-sessions-section.tsx b/apps/web/components/task/mobile/mobile-sessions-section.tsx index e74a6b1a4b..d0b98052b0 100644 --- a/apps/web/components/task/mobile/mobile-sessions-section.tsx +++ b/apps/web/components/task/mobile/mobile-sessions-section.tsx @@ -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 )} @@ -246,7 +244,6 @@ function SessionRowItem({ void actions.setPrimary()} onStop={() => void actions.stop()} onResume={() => void actions.resume()} diff --git a/apps/web/components/task/mobile/mobile-terminal-pane.tsx b/apps/web/components/task/mobile/mobile-terminal-pane.tsx index ece48382b4..bd52354337 100644 --- a/apps/web/components/task/mobile/mobile-terminal-pane.tsx +++ b/apps/web/components/task/mobile/mobile-terminal-pane.tsx @@ -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(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(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 (
@@ -39,9 +41,7 @@ function TerminalSlot({ label={terminal.label} autoFocus={isActive} disableWebgl - onXtermReady={(x) => { - xtermRef.current = x; - }} + onXtermReady={setXterm} />
); diff --git a/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts b/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts index 5156f987b6..2d036b3947 100644 --- a/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts +++ b/apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts @@ -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], diff --git a/apps/web/hooks/domains/session/use-mobile-terminals.ts b/apps/web/hooks/domains/session/use-mobile-terminals.ts index e3b2896166..7cb9eb6114 100644 --- a/apps/web/hooks/domains/session/use-mobile-terminals.ts +++ b/apps/web/hooks/domains/session/use-mobile-terminals.ts @@ -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).catch === "function") { + (result as Promise).catch(() => { + if (autoCreatedRef.current === environmentId) { + autoCreatedRef.current = null; + } + }); + } }, [environmentId, shellsLoaded, shells.length]); return { ...result, environmentId }; diff --git a/apps/web/lib/terminal/send-shell-input.test.ts b/apps/web/lib/terminal/send-shell-input.test.ts index 8009ee8eea..02f921fbdc 100644 --- a/apps/web/lib/terminal/send-shell-input.test.ts +++ b/apps/web/lib/terminal/send-shell-input.test.ts @@ -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" }, + }); + }); + }); }); diff --git a/apps/web/lib/terminal/send-shell-input.ts b/apps/web/lib/terminal/send-shell-input.ts index 5e7f040237..9e6c75c36f 100644 --- a/apps/web/lib/terminal/send-shell-input.ts +++ b/apps/web/lib/terminal/send-shell-input.ts @@ -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