diff --git a/apps/backend/internal/agent/handlers/shell_handlers.go b/apps/backend/internal/agent/handlers/shell_handlers.go index 2667d82cbb..4cc83b7a3b 100644 --- a/apps/backend/internal/agent/handlers/shell_handlers.go +++ b/apps/backend/internal/agent/handlers/shell_handlers.go @@ -224,82 +224,94 @@ func (h *ShellHandlers) wsUserShellList(ctx context.Context, msg *ws.Message) (* }) } -// UserShellCreateRequest for user_shell.create action +// UserShellCreateRequest for user_shell.create action. +// Exactly one of (ScriptID) or (Command) may be set; if both are empty the +// handler creates a plain shell. When Command is set, Label is used as the +// terminal label (defaults to "Script" when omitted). type UserShellCreateRequest struct { SessionID string `json:"session_id"` - ScriptID string `json:"script_id,omitempty"` // Optional: create a script terminal instead of plain shell + ScriptID string `json:"script_id,omitempty"` + Command string `json:"command,omitempty"` + Label string `json:"label,omitempty"` } -// wsUserShellCreate creates a new user shell terminal and returns the assigned ID and label +// wsUserShellCreate creates a new user shell terminal and returns the assigned ID and label. func (h *ShellHandlers) wsUserShellCreate(ctx context.Context, msg *ws.Message) (*ws.Message, error) { var req UserShellCreateRequest if err := msg.ParsePayload(&req); err != nil { return nil, fmt.Errorf("invalid payload: %w", err) } - if req.SessionID == "" { return nil, fmt.Errorf("session_id is required") } - // Get the interactive runner interactiveRunner := h.lifecycleMgr.GetInteractiveRunner() if interactiveRunner == nil { return nil, fmt.Errorf("interactive runner not available") } - var terminalID, label, initialCommand string - var closable bool - - if req.ScriptID != "" { - // Creating a script terminal - look up the script - if h.scriptService == nil { - return nil, fmt.Errorf("script service not available") - } - - script, err := h.scriptService.GetRepositoryScript(ctx, req.ScriptID) - if err != nil { - h.logger.Error("failed to get repository script", - zap.String("script_id", req.ScriptID), - zap.Error(err)) - return nil, fmt.Errorf("invalid script ID: %w", err) - } - - terminalID = "script-" + uuid.New().String() - label = script.Name - initialCommand = script.Command - closable = true // Script terminals are always closable - - // Register the script terminal with the interactive runner - interactiveRunner.RegisterScriptShell(req.SessionID, terminalID, label, initialCommand) + label, command, err := h.resolveShellScript(ctx, &req) + if err != nil { + return nil, err + } + if command != "" { + terminalID := "script-" + uuid.New().String() + interactiveRunner.RegisterScriptShell(req.SessionID, terminalID, label, command) h.logger.Info("created script terminal", zap.String("session_id", req.SessionID), zap.String("terminal_id", terminalID), zap.String("label", label), - zap.String("script_id", req.ScriptID), - zap.String("initial_command", initialCommand)) - } else { - // Creating a plain shell terminal - result := interactiveRunner.CreateUserShell(req.SessionID) - terminalID = result.TerminalID - label = result.Label - closable = result.Closable - - h.logger.Info("created user shell", - zap.String("session_id", req.SessionID), - zap.String("terminal_id", terminalID), - zap.String("label", label), - zap.Bool("closable", closable)) + zap.String("initial_command", command)) + return ws.NewResponse(msg.ID, msg.Action, map[string]any{ + "terminal_id": terminalID, + "label": label, + "closable": true, + "initial_command": command, + }) } + result := interactiveRunner.CreateUserShell(req.SessionID) + h.logger.Info("created user shell", + zap.String("session_id", req.SessionID), + zap.String("terminal_id", result.TerminalID), + zap.String("label", result.Label), + zap.Bool("closable", result.Closable)) return ws.NewResponse(msg.ID, msg.Action, map[string]any{ - "terminal_id": terminalID, - "label": label, - "closable": closable, - "initial_command": initialCommand, + "terminal_id": result.TerminalID, + "label": result.Label, + "closable": result.Closable, + "initial_command": "", }) } +// resolveShellScript returns the (label, command) pair for a script terminal, +// or ("", "") when the request is for a plain shell. +func (h *ShellHandlers) resolveShellScript( + ctx context.Context, req *UserShellCreateRequest, +) (string, string, error) { + if req.ScriptID != "" { + if h.scriptService == nil { + return "", "", fmt.Errorf("script service not available") + } + script, err := h.scriptService.GetRepositoryScript(ctx, req.ScriptID) + if err != nil { + h.logger.Error("failed to get repository script", + zap.String("script_id", req.ScriptID), zap.Error(err)) + return "", "", fmt.Errorf("invalid script ID: %w", err) + } + return script.Name, script.Command, nil + } + if req.Command != "" { + label := req.Label + if label == "" { + label = "Script" + } + return label, req.Command, nil + } + return "", "", nil +} + // UserShellStopRequest for user_shell.stop action type UserShellStopRequest struct { SessionID string `json:"session_id"` diff --git a/apps/backend/internal/agent/handlers/shell_handlers_test.go b/apps/backend/internal/agent/handlers/shell_handlers_test.go index 79b6a28176..2c2773ede4 100644 --- a/apps/backend/internal/agent/handlers/shell_handlers_test.go +++ b/apps/backend/internal/agent/handlers/shell_handlers_test.go @@ -441,6 +441,65 @@ func TestWsUserShellCreate_ScriptID_NoScriptService(t *testing.T) { } } +func TestResolveShellScript(t *testing.T) { + log := newTestLogger() + h := NewShellHandlers(nil, nil, log) + ctx := context.Background() + + t.Run("plain shell when no script_id and no command", func(t *testing.T) { + label, cmd, err := h.resolveShellScript(ctx, &UserShellCreateRequest{SessionID: "s1"}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if label != "" || cmd != "" { + t.Errorf("expected empty label/command, got label=%q command=%q", label, cmd) + } + }) + + t.Run("inline command with explicit label", func(t *testing.T) { + label, cmd, err := h.resolveShellScript(ctx, &UserShellCreateRequest{ + SessionID: "s1", + Command: "echo hi", + Label: "Dev Server", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if label != "Dev Server" { + t.Errorf("label = %q, want %q", label, "Dev Server") + } + if cmd != "echo hi" { + t.Errorf("command = %q, want %q", cmd, "echo hi") + } + }) + + t.Run("inline command defaults label to Script", func(t *testing.T) { + label, cmd, err := h.resolveShellScript(ctx, &UserShellCreateRequest{ + SessionID: "s1", + Command: "ls", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if label != "Script" { + t.Errorf("label = %q, want %q", label, "Script") + } + if cmd != "ls" { + t.Errorf("command = %q, want %q", cmd, "ls") + } + }) + + t.Run("script_id without script service errors", func(t *testing.T) { + _, _, err := h.resolveShellScript(ctx, &UserShellCreateRequest{ + SessionID: "s1", + ScriptID: "abc", + }) + if err == nil { + t.Fatal("expected error when script service is nil") + } + }) +} + func TestWsUserShellStop_InvalidPayload(t *testing.T) { log := newTestLogger() handlers := NewShellHandlers(nil, nil, log) diff --git a/apps/backend/internal/agentctl/server/process/interactive_io.go b/apps/backend/internal/agentctl/server/process/interactive_io.go index 3de5fffe6f..b96f02fd92 100644 --- a/apps/backend/internal/agentctl/server/process/interactive_io.go +++ b/apps/backend/internal/agentctl/server/process/interactive_io.go @@ -39,6 +39,7 @@ func (r *InteractiveRunner) readOutput(proc *interactiveProcess) { firstRead = false } if n > 0 { + proc.firstOutputOnce.Do(func() { close(proc.firstOutputCh) }) recentOutput = r.processOutputData(proc, ptyInstance, buf[:n], recentOutput) } if err != nil { diff --git a/apps/backend/internal/agentctl/server/process/interactive_lifecycle.go b/apps/backend/internal/agentctl/server/process/interactive_lifecycle.go index 6a35cc1a0d..dfeb87e96a 100644 --- a/apps/backend/internal/agentctl/server/process/interactive_lifecycle.go +++ b/apps/backend/internal/agentctl/server/process/interactive_lifecycle.go @@ -55,6 +55,13 @@ type interactiveProcess struct { stopSignal chan struct{} waitDone chan struct{} // closed when wait() returns (cmd.Wait completed) mu sync.Mutex + + // firstOutputCh is closed by readOutput once any bytes arrive from the PTY — + // a reliable proxy for "shell has rendered its prompt and is ready for input". + // InitialCommand writes wait on this so heavy zsh/bash startup scripts don't + // race with stdin echo (which would otherwise duplicate the command in output). + firstOutputOnce sync.Once + firstOutputCh chan struct{} } // Start creates an interactive process entry and defers PTY creation until first resize. @@ -116,6 +123,7 @@ func (r *InteractiveRunner) Start(ctx context.Context, req InteractiveStartReque isUserShell: req.IsUserShell, stopSignal: make(chan struct{}), waitDone: make(chan struct{}), + firstOutputCh: make(chan struct{}), // Store start parameters for deferred initialization started: false, startCmd: req.Command, @@ -267,11 +275,21 @@ func (r *InteractiveRunner) startProcess(proc *interactiveProcess, cols, rows in go r.readOutput(proc) go r.wait(proc) - // If an initial command was provided, write it to the PTY after a short delay - // to allow the shell to initialize and display its prompt + // Wait for the shell to print its prompt before writing the initial command. + // readOutput closes firstOutputCh on the first PTY read; without that gate a + // heavy zsh/bash startup races the write and zsh ends up rendering the + // command twice — once from PTY echo, once when it repaints with the + // pending input. We still cap the wait so silent shells don't hang. if req.InitialCommand != "" { go func() { - time.Sleep(100 * time.Millisecond) + select { + case <-proc.firstOutputCh: + case <-time.After(2 * time.Second): + r.logger.Warn("initial command write timed out waiting for shell prompt", + zap.String("process_id", proc.info.ID)) + } + // Brief settle so the prompt is fully painted before we type into it. + time.Sleep(50 * time.Millisecond) proc.mu.Lock() pty := proc.ptmx proc.mu.Unlock() diff --git a/apps/backend/internal/agentctl/server/process/interactive_shells.go b/apps/backend/internal/agentctl/server/process/interactive_shells.go index 1c56d4ecaf..b4891f6d84 100644 --- a/apps/backend/internal/agentctl/server/process/interactive_shells.go +++ b/apps/backend/internal/agentctl/server/process/interactive_shells.go @@ -104,6 +104,20 @@ func (r *InteractiveRunner) RegisterScriptShell(sessionID, terminalID, label, in } } +// LookupShellInitialCommand returns the InitialCommand stored for a pre-registered +// shell entry, or "" when no entry exists. Used by remote-shell handlers to recover +// the script command across the WS-handshake boundary, since the per-terminal WS URL +// only carries terminalId — not script_id or command. +func (r *InteractiveRunner) LookupShellInitialCommand(sessionID, terminalID string) string { + key := sessionID + ":" + terminalID + r.userShellsMu.RLock() + defer r.userShellsMu.RUnlock() + if entry, ok := r.userShells[key]; ok { + return entry.InitialCommand + } + return "" +} + // StartUserShell starts or returns an existing user shell for a terminal tab. // Each terminal tab gets its own independent shell process. // If opts.InitialCommand is provided, it will be written to stdin after the shell starts. diff --git a/apps/backend/internal/gateway/websocket/terminal_handler.go b/apps/backend/internal/gateway/websocket/terminal_handler.go index 2828d6ce64..5e2118a70f 100644 --- a/apps/backend/internal/gateway/websocket/terminal_handler.go +++ b/apps/backend/internal/gateway/websocket/terminal_handler.go @@ -277,6 +277,15 @@ func (h *TerminalHandler) handleRemoteUserShellWS(c *gin.Context, sessionID, ter c.JSON(http.StatusBadRequest, gin.H{"error": httpErr}) return } + // The per-terminal WS URL only carries terminalId, so fall back to the + // command pre-registered by wsUserShellCreate when the URL didn't include + // scriptId or label-derived command. Without this, script terminals (custom + // scripts and dev_script) would open empty in containerized sessions. + if initialCommand == "" { + if runner := h.lifecycleMgr.GetInteractiveRunner(); runner != nil { + initialCommand = runner.LookupShellInitialCommand(sessionID, terminalID) + } + } // Create a per-terminal shell on agentctl (idempotent if already exists) if err := client.StartShellTerminal(c.Request.Context(), terminalID, 80, 24); err != nil { diff --git a/apps/web/components/task/dockview-header-actions.tsx b/apps/web/components/task/dockview-header-actions.tsx index e2e0032c91..82ccafc1b3 100644 --- a/apps/web/components/task/dockview-header-actions.tsx +++ b/apps/web/components/task/dockview-header-actions.tsx @@ -41,6 +41,7 @@ import type { Task, ProcessInfo } from "@/lib/types/http"; import type { ProcessStatusEntry } from "@/lib/state/slices"; import { NewSessionDialog } from "./new-session-dialog"; import { NewTaskDropdown } from "./new-task-dropdown"; +import { RepositoryScriptsMenuItems, useActiveSessionDevScript } from "./repository-scripts-menu"; import { SessionReopenMenuItems } from "./session-reopen-menu"; /** Map a ProcessInfo response to a ProcessStatusEntry for the store. */ @@ -93,11 +94,15 @@ function AddPanelMenuItems({ state, onNewSession, onAddTerminal, + onRunScript, + onRunDevScript, }: { groupId: string; state: ReturnType; onNewSession: () => void; onAddTerminal: () => void; + onRunScript: (scriptId: string) => void; + onRunDevScript: () => void; }) { const addBrowserPanel = useDockviewStore((s) => s.addBrowserPanel); const addVscodePanel = useDockviewStore((s) => s.addVscodePanel); @@ -167,6 +172,7 @@ function AddPanelMenuItems({ {prPanelLabel(state.pr.pr_number)} )} + ); } @@ -175,6 +181,7 @@ export function LeftHeaderActions(props: IDockviewHeaderActionsProps) { const { group, containerApi } = props; const state = useLeftHeaderState(group.id, containerApi); const addTerminalPanel = useDockviewStore((s) => s.addTerminalPanel); + const devScript = useActiveSessionDevScript(); const [showNewSessionDialog, setShowNewSessionDialog] = useState(false); const handleAddTerminal = useCallback(async () => { @@ -187,6 +194,32 @@ export function LeftHeaderActions(props: IDockviewHeaderActionsProps) { } }, [state.activeSessionId, addTerminalPanel, group.id]); + const handleRunScript = useCallback( + async (scriptId: string) => { + if (!state.activeSessionId) return; + try { + const result = await createUserShell(state.activeSessionId, { scriptId }); + addTerminalPanel(result.terminalId, group.id); + } catch (error) { + console.error("Failed to run script:", error); + } + }, + [state.activeSessionId, addTerminalPanel, group.id], + ); + + const handleRunDevScript = useCallback(async () => { + if (!state.activeSessionId || !devScript) return; + try { + const result = await createUserShell(state.activeSessionId, { + command: devScript, + label: "Dev Server", + }); + addTerminalPanel(result.terminalId, group.id); + } catch (error) { + console.error("Failed to start dev script:", error); + } + }, [state.activeSessionId, devScript, addTerminalPanel, group.id]); + if (state.isSidebarGroup) return null; return ( @@ -208,6 +241,8 @@ export function LeftHeaderActions(props: IDockviewHeaderActionsProps) { state={state} onNewSession={() => setShowNewSessionDialog(true)} onAddTerminal={handleAddTerminal} + onRunScript={handleRunScript} + onRunDevScript={handleRunDevScript} /> @@ -472,18 +507,6 @@ function CenterRightActions() { ); } -function useHasActiveSessionDevScript() { - return useAppStore((state) => { - const sessionId = state.tasks.activeSessionId; - if (!sessionId) return false; - const repoId = state.taskSessions.items[sessionId]?.repository_id; - if (!repoId) return false; - const allRepos = Object.values(state.repositories.itemsByWorkspaceId).flat(); - const repo = allRepos.find((r) => r.id === repoId); - return Boolean(repo?.dev_script?.trim()); - }); -} - function TerminalGroupRightActions() { const activeSessionId = useAppStore((state) => state.tasks.activeSessionId); const repositoryId = useAppStore((state) => { @@ -491,7 +514,7 @@ function TerminalGroupRightActions() { if (!sessionId) return null; return state.taskSessions.items[sessionId]?.repository_id ?? null; }); - const hasDevScript = useHasActiveSessionDevScript(); + const hasDevScript = Boolean(useActiveSessionDevScript()); const { scripts } = useRepositoryScripts(repositoryId); const addTerminalPanel = useDockviewStore((s) => s.addTerminalPanel); @@ -504,7 +527,7 @@ function TerminalGroupRightActions() { async (scriptId: string) => { if (!activeSessionId) return; try { - const result = await createUserShell(activeSessionId, scriptId); + const result = await createUserShell(activeSessionId, { scriptId }); addTerminalPanel(result.terminalId, rightBottomGroupId); } catch (error) { console.error("Failed to run script:", error); diff --git a/apps/web/components/task/repository-scripts-menu.tsx b/apps/web/components/task/repository-scripts-menu.tsx new file mode 100644 index 0000000000..4b60acbdb3 --- /dev/null +++ b/apps/web/components/task/repository-scripts-menu.tsx @@ -0,0 +1,78 @@ +"use client"; + +import { IconDeviceDesktop, IconPlayerPlay } from "@tabler/icons-react"; +import { + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, +} from "@kandev/ui/dropdown-menu"; +import { useAppStore } from "@/components/state-provider"; +import { useRepositoryScripts } from "@/hooks/domains/workspace/use-repository-scripts"; + +/** + * Returns the trimmed dev_script command of the active session's repository, + * or an empty string when none is configured. Boolean usage stays valid via + * truthiness; callers that need the command itself can use it directly. + */ +export function useActiveSessionDevScript(): string { + return useAppStore((state) => { + const sessionId = state.tasks.activeSessionId; + if (!sessionId) return ""; + const repoId = state.taskSessions.items[sessionId]?.repository_id; + if (!repoId) return ""; + const allRepos = Object.values(state.repositories.itemsByWorkspaceId).flat(); + const repo = allRepos.find((r) => r.id === repoId); + return repo?.dev_script?.trim() ?? ""; + }); +} + +/** + * Renders custom repository scripts (and the dev script if configured) as + * dropdown items inside the dockview "+" menu. Returns null when neither is + * available so the caller doesn't render an empty section. + */ +export function RepositoryScriptsMenuItems({ + onRunScript, + onRunDevScript, +}: { + onRunScript: (scriptId: string) => void; + onRunDevScript: () => void; +}) { + const repositoryId = useAppStore((s) => { + const sessionId = s.tasks.activeSessionId; + if (!sessionId) return null; + return s.taskSessions.items[sessionId]?.repository_id ?? null; + }); + const { scripts } = useRepositoryScripts(repositoryId); + const devScript = useActiveSessionDevScript(); + + if (scripts.length === 0 && !devScript) return null; + + return ( + <> + + Scripts + {devScript && ( + + + Dev Server + + )} + {scripts.map((script) => ( + onRunScript(script.id)} + className="cursor-pointer text-xs" + data-testid={`run-script-${script.id}`} + > + + {script.name} + + ))} + + ); +} diff --git a/apps/web/e2e/helpers/api-client.ts b/apps/web/e2e/helpers/api-client.ts index 81b84e24e5..9b3c9a35a5 100644 --- a/apps/web/e2e/helpers/api-client.ts +++ b/apps/web/e2e/helpers/api-client.ts @@ -370,6 +370,32 @@ export class ApiClient { }); } + async updateRepository( + repositoryId: string, + updates: { dev_script?: string; setup_script?: string; cleanup_script?: string }, + ): Promise { + await this.request("PATCH", `/api/v1/repositories/${repositoryId}`, updates); + } + + async createRepositoryScript( + repositoryId: string, + name: string, + command: string, + position = 0, + ): Promise<{ + id: string; + repository_id: string; + name: string; + command: string; + position: number; + }> { + return this.request("POST", `/api/v1/repositories/${repositoryId}/scripts`, { + name, + command, + position, + }); + } + async createExecutor( name: string, type: string, diff --git a/apps/web/e2e/tests/session/dockview-repository-scripts.spec.ts b/apps/web/e2e/tests/session/dockview-repository-scripts.spec.ts new file mode 100644 index 0000000000..8353d7eefb --- /dev/null +++ b/apps/web/e2e/tests/session/dockview-repository-scripts.spec.ts @@ -0,0 +1,236 @@ +import { type Page } from "@playwright/test"; +import { test, expect } from "../../fixtures/test-base"; +import type { SeedData } from "../../fixtures/test-base"; +import type { ApiClient } from "../../helpers/api-client"; +import { SessionPage } from "../../pages/session-page"; + +async function seedTaskWithSession( + testPage: Page, + apiClient: ApiClient, + seedData: SeedData, + title: string, +): Promise { + const task = await apiClient.createTaskWithAgent( + seedData.workspaceId, + title, + seedData.agentProfileId, + { + description: "/e2e:simple-message", + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + repository_ids: [seedData.repositoryId], + }, + ); + + if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id"); + + await testPage.goto(`/t/${task.id}`); + + const session = new SessionPage(testPage); + await session.waitForLoad(); + await expect(session.idleInput()).toBeVisible({ timeout: 30_000 }); + + return session; +} + +/** Read the visible top-level menu items in the dockview "+" dropdown. */ +async function readMenuItemTexts(testPage: Page): Promise { + return testPage.locator('[role="menuitem"]:visible').allInnerTexts(); +} + +/** + * Read every xterm buffer on the page and return their concatenated text. Used + * to assert that *some* terminal contains given output regardless of which + * dockview group / tab order it ended up in. + */ +async function readAllTerminalBuffers(testPage: Page): Promise { + return testPage.evaluate(() => { + type XC = HTMLElement & { __xtermReadBuffer?: () => string }; + const panels = Array.from(document.querySelectorAll('[data-testid="terminal-panel"]')); + return panels + .map((panel) => { + const xtermEl = panel.querySelector(".xterm"); + const container = xtermEl?.parentElement as XC | null | undefined; + return container?.__xtermReadBuffer?.() ?? ""; + }) + .join("\n----\n"); + }); +} + +test.describe("Dockview repository scripts in + menu", () => { + test.describe.configure({ retries: 1 }); + + test("does not render Scripts section when repo has no scripts and no dev_script", async ({ + testPage, + apiClient, + seedData, + }) => { + // Ensure repo has no dev_script (seed doesn't set one, but be explicit). + await apiClient.updateRepository(seedData.repositoryId, { dev_script: "" }); + + const session = await seedTaskWithSession(testPage, apiClient, seedData, "No Scripts"); + await session.addPanelButton().click(); + + await expect(testPage.getByRole("menuitem", { name: "Terminal" })).toBeVisible(); + await expect(testPage.getByText("Scripts", { exact: true })).toHaveCount(0); + await expect(testPage.getByTestId("run-dev-script")).toHaveCount(0); + }); + + test("renders custom scripts at the end of the + menu", async ({ + testPage, + apiClient, + seedData, + }) => { + const buildScript = await apiClient.createRepositoryScript( + seedData.repositoryId, + "Run Build", + "echo build", + 0, + ); + const lintScript = await apiClient.createRepositoryScript( + seedData.repositoryId, + "Run Lint", + "echo lint", + 1, + ); + + const session = await seedTaskWithSession(testPage, apiClient, seedData, "Custom Scripts"); + await session.addPanelButton().click(); + + await expect(testPage.getByTestId(`run-script-${buildScript.id}`)).toBeVisible(); + await expect(testPage.getByTestId(`run-script-${lintScript.id}`)).toBeVisible(); + + // Scripts must be the LAST items in the menu. Verify by ordering: the + // "Browser" item appears before the script items in the visible menu. + const items = await readMenuItemTexts(testPage); + const browserIdx = items.findIndex((t) => t.includes("Browser")); + const buildIdx = items.findIndex((t) => t.includes("Run Build")); + const lintIdx = items.findIndex((t) => t.includes("Run Lint")); + expect(browserIdx).toBeGreaterThanOrEqual(0); + expect(buildIdx).toBeGreaterThan(browserIdx); + expect(lintIdx).toBeGreaterThan(browserIdx); + }); + + test("clicking a custom script opens a terminal that runs the script command", async ({ + testPage, + apiClient, + seedData, + }) => { + const marker = "CUSTOM_SCRIPT_RAN_OK_3131"; + const script = await apiClient.createRepositoryScript( + seedData.repositoryId, + "Echo Hello", + `echo ${marker}`, + 0, + ); + + const session = await seedTaskWithSession(testPage, apiClient, seedData, "Click Script"); + await session.addPanelButton().click(); + await testPage.getByTestId(`run-script-${script.id}`).click(); + + // The backend assigns script terminals an id prefixed with "script-". + await expect + .poll( + async () => { + return testPage.evaluate(() => { + type Panel = { id: string }; + type Api = { panels: Panel[] }; + const api = (window as unknown as { __dockviewApi__?: Api }).__dockviewApi__; + return api?.panels.some((p) => p.id.startsWith("script-")) ?? false; + }); + }, + { timeout: 10_000, message: "Expected a script terminal panel to be added" }, + ) + .toBe(true); + + // The script command must actually execute — *some* terminal buffer + // (the one belonging to the new script panel) must contain the marker. + await expect + .poll(async () => (await readAllTerminalBuffers(testPage)).includes(marker), { + timeout: 60_000, + message: `Expected a terminal to contain "${marker}"`, + }) + .toBe(true); + }); + + test("renders Dev Server entry when repository has dev_script", async ({ + testPage, + apiClient, + seedData, + }) => { + await apiClient.updateRepository(seedData.repositoryId, { + dev_script: "echo dev-server-running", + }); + + const session = await seedTaskWithSession(testPage, apiClient, seedData, "Dev Script"); + await session.addPanelButton().click(); + + await expect(testPage.getByTestId("run-dev-script")).toBeVisible(); + await expect(testPage.getByText("Dev Server", { exact: true })).toBeVisible(); + + // Also at the end of the menu — after Browser. + const items = await readMenuItemTexts(testPage); + const browserIdx = items.findIndex((t) => t.includes("Browser")); + const devIdx = items.findIndex((t) => t.includes("Dev Server")); + expect(devIdx).toBeGreaterThan(browserIdx); + }); + + test("dev_script and custom scripts coexist in the Scripts section", async ({ + testPage, + apiClient, + seedData, + }) => { + await apiClient.updateRepository(seedData.repositoryId, { dev_script: "echo dev" }); + const customScript = await apiClient.createRepositoryScript( + seedData.repositoryId, + "Test Suite", + "echo test", + 0, + ); + + const session = await seedTaskWithSession(testPage, apiClient, seedData, "Mixed Scripts"); + await session.addPanelButton().click(); + + await expect(testPage.getByTestId("run-dev-script")).toBeVisible(); + await expect(testPage.getByTestId(`run-script-${customScript.id}`)).toBeVisible(); + }); + + test("clicking Dev Server opens a terminal that runs the dev_script command", async ({ + testPage, + apiClient, + seedData, + }) => { + const marker = "DEV_SCRIPT_RAN_OK_4242"; + await apiClient.updateRepository(seedData.repositoryId, { + dev_script: `echo ${marker}`, + }); + + const session = await seedTaskWithSession(testPage, apiClient, seedData, "Run Dev Script"); + await session.addPanelButton().click(); + await testPage.getByTestId("run-dev-script").click(); + + // Backend assigns "script-"-prefixed ids to script terminals. + await expect + .poll( + async () => { + return testPage.evaluate(() => { + type Panel = { id: string }; + type Api = { panels: Panel[] }; + const api = (window as unknown as { __dockviewApi__?: Api }).__dockviewApi__; + return api?.panels.some((p) => p.id.startsWith("script-")) ?? false; + }); + }, + { timeout: 10_000, message: "Expected a dev-script terminal panel to be added" }, + ) + .toBe(true); + + // The dev_script must actually execute — *some* terminal buffer should + // contain the marker emitted by the script command. + await expect + .poll(async () => (await readAllTerminalBuffers(testPage)).includes(marker), { + timeout: 60_000, + message: `Expected a terminal to contain "${marker}"`, + }) + .toBe(true); + }); +}); diff --git a/apps/web/hooks/domains/session/use-terminals.ts b/apps/web/hooks/domains/session/use-terminals.ts index 9e1fb62c19..59287766ff 100644 --- a/apps/web/hooks/domains/session/use-terminals.ts +++ b/apps/web/hooks/domains/session/use-terminals.ts @@ -272,7 +272,7 @@ function useTerminalActions({ async (script: RepositoryScript) => { if (!sessionId) return; try { - const result = await createUserShell(sessionId, script.id); + const result = await createUserShell(sessionId, { scriptId: script.id }); setTerminals((prev) => [ ...prev, { id: result.terminalId, type: "script", label: result.label, closable: result.closable }, diff --git a/apps/web/lib/api/domains/user-shell-api.ts b/apps/web/lib/api/domains/user-shell-api.ts index edb2ff7b67..315fb02ebb 100644 --- a/apps/web/lib/api/domains/user-shell-api.ts +++ b/apps/web/lib/api/domains/user-shell-api.ts @@ -44,15 +44,25 @@ export type CreateUserShellResult = { initialCommand?: string; }; +/** + * Options for {@link createUserShell}. Pass `scriptId` to run a stored + * RepositoryScript, or `command` (with optional `label`) to run an arbitrary + * command — used for the repository's dev_script. Omit both for a plain shell. + */ +export type CreateUserShellOptions = { + scriptId?: string; + command?: string; + label?: string; +}; + /** * Create a new user shell terminal. * Backend assigns the terminal ID, label, and closable status. * First terminal is "Terminal" and not closable, subsequent are "Terminal 2", etc. and closable. - * If scriptId is provided, creates a script terminal with the script's name and command. */ export async function createUserShell( sessionId: string, - scriptId?: string, + options?: CreateUserShellOptions, ): Promise { const client = getWebSocketClient(); if (!client) { @@ -60,9 +70,9 @@ export async function createUserShell( } const payload: Record = { session_id: sessionId }; - if (scriptId) { - payload.script_id = scriptId; - } + if (options?.scriptId) payload.script_id = options.scriptId; + if (options?.command) payload.command = options.command; + if (options?.label) payload.label = options.label; const response = (await client.request("user_shell.create", payload)) as { terminal_id: string;