046ac5c1b6
* feat(backend): add session-scoped message search endpoint
Adds SearchMessages across repository/service/handler layers and a new
WebSocket action "message.search". Returns lightweight hits with a
60-char snippet around the first match. Session-scoped only: results
never leak across sessions. Uses dialect-aware LIKE/ILIKE so it works
on SQLite today and Postgres later.
* feat(web): add shared panel search bar and Ctrl+F hook
Introduces the reusable PanelSearchBar overlay and usePanelSearch hook
used by the per-panel search features. The hook listens on the window
and fires only when focus is within the panel root, preventDefaults the
browser find-in-page, and wires Esc to close. PanelRoot becomes a
forwardRef so panel components can expose their root element to the
hook. Adds SHORTCUTS.FIND_IN_PANEL plus shared highlight/flash styles.
* feat(web): add Ctrl+F search to terminal panels
Mounts the xterm addon-search on both passthrough and shell terminals,
exposing next/prev plus case-sensitivity and regex toggles. Invalid
regex surfaces an inline error without firing the search. Because xterm
consumes keystrokes before React, the Ctrl/Cmd+F intercept is added to
attachCustomKeyEventHandler so the shortcut opens the bar from inside
the terminal. Results counter comes from onDidChangeResults; decorations
clear on close.
* feat(web): add Ctrl+F search to plan panel
Adds a custom TipTap extension that builds a ProseMirror DecorationSet
over the document and exposes setPlanSearchQuery / planSearchNext /
planSearchPrev / clearPlanSearch commands. The current match gets an
extra class and scrolls into view. Match count is read from the plugin
state via transaction subscription, so edits to the document update the
counter automatically. Find-only — no replace.
* feat(web): add Ctrl+F search to session chat panel
Wires the new backend message.search action into a debounced client
hook and renders a hits dropdown under the search bar, with the query
highlighted in each snippet. Clicking a hit scrolls the message into
view and flashes it. When the target message is older than what is
currently loaded, the hook loops through loadOlder pages until the
message renders, making search work across lazy-loaded history without
needing to scroll-and-wait manually.
* fix(web): lazy-load xterm addon-search to avoid SSR crash
addon-search is published as a UMD bundle that references `self` at
module load. Statically importing it breaks the Next.js static
prerender of /. Deferring the import to an effect keeps the module out
of the SSR graph without changing runtime behaviour.
* fix(web): propagate plan editor via state so plan-search hook re-runs
The plan-search hook subscribed to editor transactions inside a
useEffect that depended on a ref object. Because ref.current changes do
not trigger effect re-runs, if the Editor instance was not yet ready
when the hook first mounted, the transaction handler never attached and
the match counter stayed at 0 / 0. Tracking the editor via state (in
addition to the ref) causes the deps to change when the Editor becomes
available, so the handler attaches and the counter updates.
* feat(web): allow overriding message list renderer via ?renderer= query
Exposes the "native" / "virtuoso" choice at runtime so E2E coverage can
exercise both paths without a redeploy or code change. Defaults to the
existing "native" strategy when no override is present.
* test(web): add Playwright coverage for panel-scoped Ctrl+F search
Adds an e2e/tests/search/ suite with five specs:
- panel-search-shared: cross-panel contract (Ctrl+F opens, autofocus,
Esc closes, close button, state reset on reopen) parametrised over
session, plan, and terminal.
- terminal-search: xterm addon-search integration — key intercept
without leaking "f" to the PTY, case + regex toggles (incl. invalid
regex error), Esc does not reach the shell, backspace adjusts count.
- plan-search: TipTap plugin — highlight count, exactly one current
match, counter, Enter / Shift+Enter wrapping, close clears
decorations, no case/regex toggles in plan bar.
- session-search: WebSocket-backed hits list, "No matches" state,
click-to-flash, cross-session isolation, close, and virtuoso renderer
coverage via the new ?renderer= override.
- panel-focus-routing: bar mounts inside the focused panel only.
Three tests capture GIFs for the PR description via prCapture when
CAPTURE_PR_ASSETS is set (one per panel). Helpers live in
e2e/helpers/panel-search.ts and e2e/helpers/seed-session-messages.ts;
SessionPage gains search-bar locators.
* fix(web): prevent plan-search update loop on spurious editor transactions
TipTap fires `transaction` on every cursor move/click. The match-info
handler allocated a fresh `{current, total}` object each time, so React
always saw new identity, re-rendered, and could cascade with downstream
effects (e.g. `rehydrateCommentMarks`) into a "Maximum update depth
exceeded" loop. Use a functional setState with equality bail-out so the
handler only schedules a render when the counter actually changes.
* fix(web): retry terminal search once xterm addon-search finishes loading
The SearchAddon is dynamic-imported and was stored in a ref. The
query→findNext effect called `addonRef.current?.findNext(...)` — a
silent no-op if the addon wasn't loaded yet — and its deps didn't
include addon readiness, so a query typed before the import resolved
was dropped forever. Track the addon via state so the search effect
re-runs when it becomes available (and re-binds cleanly if the terminal
is ever re-created). Also deduplicate match-info updates via functional
setState + equality check.
* fix(web): route Ctrl+F to the last-clicked panel when focus is ambient
The chat panel's message list has no focus-capturing child, so clicking
on a message left `document.activeElement === <body>` and the existing
`isFocusWithin` gate silently fell through to the browser's native find.
Fix with two complementary mechanisms:
- `usePanelSearch`: track the most-recently-clicked panel via a
window-level pointerdown capture listener. When focus is ambient
(body/html), that panel claims Ctrl+F. Window-level capture dodges
any descendant `stopPropagation` that would skip a container-level
listener.
- Chat panel root: tabIndex=-1 + onMouseDown that focuses the root when
the click target isn't already focusable. Normal path matches how
plan/terminal already work (TipTap/xterm capture focus on click).
* feat(web): show agent profile name and logo in session search hits
The hit list showed uppercase "AGENT"/"USER" with vivid blue/green
colors that clashed with the app's muted metadata aesthetic. Replace
with the actual author identity:
- Agent hits render the profile name (falling back to "Agent") with
the profile's <AgentLogo> inline — same mechanism session tabs use.
- User hits render "You" with a subtle `text-primary/80` tint that
echoes the user bubble's `bg-primary/30`, keeping a light color
differentiator without reintroducing loud blue/green.
Added `useSessionAgentIdentity` (plus a `useSessionAgentProfile` helper)
that reads from the store via two primitive selectors — the id, then
the profile — and composes the final object inside `useMemo`. A naive
single selector returning `{label, name}` triggers the "getSnapshot
should be cached" infinite loop in `useSyncExternalStore`.
* style: apply prettier formatting to search files
* fix(web): inline resolveStrategy in useMemo to satisfy react-hooks/use-memo
* fix(backend): escape LIKE metacharacters in message search
User query of `%` previously built LIKE pattern `%%` which matched every
message in the session; `file_name` also matched `filename`, `file name`,
etc. Escape the three LIKE metacharacters (`\`, `%`, `_`) before wrapping
the pattern, and declare `ESCAPE '\'` on the clause. Add regression tests
covering wildcard literals and the literal-percent happy path.
* fix(backend): slice search snippet in rune space to keep UTF-8 valid
`buildSnippet` indexed and sliced on byte offsets, so content containing
multi-byte characters (emoji, CJK, accented letters) could be cut
mid-rune — `encoding/json` then replaced the invalid bytes with `\ufffd`
in the websocket response. Switch to rune slicing and per-rune
case-folding via `unicode.ToLower`; this also avoids the
`strings.ToLower` byte-length-change pitfall (e.g. Turkish İ, German ß).
Add a handler test covering emoji, CJK, and large multi-byte content.
* fix(web): cancel backfill loop when user clicks a newer session hit
`setActiveHit` awaits up to 40 `loadOlder()` iterations when the target
message isn't in the DOM. If the user clicked a second hit while those
awaits were in flight, the in-progress loop kept running and eventually
scrolled to the original target, overriding the user's intent. Gate the
loop on a generation counter so only the most recent call's backfill
drives the scroll.
* fix(web): gate plan-search scroll side-effect on dispatch
TipTap invokes commands with `dispatch === undefined` during `can()`
checks to test applicability (e.g. before enabling a menu item). The
next/prev commands called `scrollToMatch` outside the `if (dispatch)`
guard, so a dry-run invocation would scroll the editor to a match the
user didn't navigate to. Move the scroll inside the dispatch block.
* fix(web): address review nits on search UX
- formatTime now checks Number.isNaN(d.getTime()) before formatting;
Invalid Date doesn't throw, so the catch branch was unreachable and
hits with a malformed created_at rendered the literal "Invalid Date".
- prefers-reduced-motion now silences the .search-flash animation
alongside the other custom keyframe animations.
- planScript escapes `title` symmetrically with `content` so callers
passing arbitrary strings don't produce malformed JSON.
* fix(web): fold description into opts to keep seedTask under param limit
`seedTask` had 6 parameters, violating the repo's 5-parameter cap and
failing CI lint. Fold `description` into the existing `opts` object and
update all callsites.
* test(web): add unit tests for useSessionSearch + remove redundant ternary
Cover the non-trivial hook logic called out in review: debounced fetch
coalescing, request-ID cancellation for superseded queries, null
sessionId short-circuit, and close() resets. Also simplify the
`matches.length ? 0 : 0` ternary flagged as a dead branch — both sides
were already 0.
* fix(web): exclude PanelRoot (tabindex=-1) from the focus short-circuit
`target.closest("[tabindex]")` was matching PanelRoot itself (which has
`tabIndex={-1}` so it can receive programmatic focus), causing the guard
to early-return and the `panelRef.focus()` call to never fire — defeating
the Ctrl+F focus-routing that this handler was added for.
Narrow the selector to `[tabindex]:not([tabindex='-1'])` so it only
short-circuits on genuinely interactive elements.
* fix(web): read isReadOnlyMode from live ref in shell-terminal key handler
`attachCustomKeyEventHandler` is called once and has no dispose hook, so
the inner handler keeps its initial closure forever. Other values
(sessionId, send, onFindInPanel) are read via `stateRef` so they stay
current, but `isReadOnlyMode` was captured by closure — if the prop ever
toggled mid-session, the Cmd+Arrow→Home/End path would continue firing
against a read-only terminal. Include it in the state ref for
consistency.
* fix(web): flatten doubly-nested seedTask opts in virtuoso spec; drop unused MODIFIER
The regex-based transform in 7152b936 over-nested one call in
session-search.spec.ts — `opts.description` received an object rather
than a string, so the virtuoso renderer test never received a proper
task description. Flatten it.
Also remove MODIFIER imports/declarations in terminal-search.spec.ts and
panel-search-shared.spec.ts that were left dangling behind `void` suppressors.
* fix(web): abort session-search backfill loop on close/unmount
Move reset logic into `close()` so the lifecycle is explicit (and avoids
the set-state-in-effect lint path the previous reset effect triggered).
Bump the `activeHitGenRef` generation counter on both `close()` and
unmount so an in-flight `setActiveHit` backfill can no longer issue
`loadOlder()` calls for a hidden UI.
Also extract `useDebouncedSearch`, `useSetActiveHit`, and a
`focusMessageElement` helper to keep `useSessionSearch` under the
100-line function cap.
* perf(web): skip PanelSearchBar debounce for session search
Session search already debounces the WS call inside `useDebouncedSearch`
(180ms), but the shared bar adds its own 150ms debounce on top — giving
a 330ms keystroke→request latency instead of the intended ~180ms.
Pass `debounceMs={0}` so the bar forwards queries immediately and the
hook-level debounce is the single source of timing truth.
716 lines
26 KiB
TypeScript
716 lines
26 KiB
TypeScript
import { type Locator, type Page, expect } from "@playwright/test";
|
|
|
|
/** Maps old state-section labels to the new per-task state icon data-testid. */
|
|
function sectionLabelToStateTestId(label: string): string {
|
|
if (label === "Running") return "task-state-running";
|
|
if (label === "Turn Finished") return "task-state-review";
|
|
return "task-state-backlog";
|
|
}
|
|
|
|
export class SessionPage {
|
|
readonly chat: Locator;
|
|
readonly sidebar: Locator;
|
|
readonly terminal: Locator;
|
|
readonly files: Locator;
|
|
readonly changes: Locator;
|
|
readonly planPanel: Locator;
|
|
readonly stepper: Locator;
|
|
readonly passthroughTerminal: Locator;
|
|
|
|
constructor(private readonly page: Page) {
|
|
this.chat = page.getByTestId("session-chat");
|
|
this.sidebar = page.getByTestId("task-sidebar");
|
|
this.terminal = page.getByTestId("terminal-panel");
|
|
this.files = page.getByTestId("files-panel");
|
|
this.changes = page.getByTestId("changes-panel");
|
|
this.planPanel = page.getByTestId("plan-panel");
|
|
this.stepper = page.getByTestId("workflow-stepper");
|
|
this.passthroughTerminal = page.getByTestId("passthrough-terminal");
|
|
}
|
|
|
|
// Port forward dialog locators
|
|
get portForwardButton() {
|
|
return this.page.getByTestId("port-forward-button");
|
|
}
|
|
get portForwardDialog() {
|
|
return this.page.getByTestId("port-forward-dialog");
|
|
}
|
|
get portForwardRefresh() {
|
|
return this.page.getByTestId("port-forward-refresh");
|
|
}
|
|
get portForwardInput() {
|
|
return this.page.getByTestId("port-forward-port-input");
|
|
}
|
|
get portForwardAddButton() {
|
|
return this.page.getByTestId("port-forward-add-button");
|
|
}
|
|
portForwardRow(port: number) {
|
|
return this.page.getByTestId(`port-forward-row-${port}`);
|
|
}
|
|
|
|
// Chat status bar locators
|
|
chatStatusBar() {
|
|
return this.page.getByTestId("chat-status-bar");
|
|
}
|
|
prMergedBanner() {
|
|
return this.page.getByTestId("pr-merged-banner");
|
|
}
|
|
prMergedArchiveButton() {
|
|
return this.page.getByTestId("pr-merged-archive-button");
|
|
}
|
|
todoIndicator() {
|
|
return this.page.getByTestId("todo-indicator");
|
|
}
|
|
/** Resume button shown in the FailedSessionBanner. */
|
|
failedSessionResumeButton(): Locator {
|
|
return this.page.getByTestId("failed-session-resume-button");
|
|
}
|
|
/** Span wrapper around the resume button — used to trigger tooltip on disabled state. */
|
|
failedSessionResumeWrapper(): Locator {
|
|
return this.page.getByTestId("failed-session-resume-wrapper");
|
|
}
|
|
/** Cancel button shown in the chat toolbar while an agent turn is running. */
|
|
cancelAgentButton(): Locator {
|
|
return this.page.getByTestId("cancel-agent-button");
|
|
}
|
|
|
|
async waitForLoad(timeout = 15_000) {
|
|
// When multiple session tabs are open, multiple session-chat panels exist in
|
|
// the DOM but only the active one is visible. Use :visible to avoid matching
|
|
// a hidden background panel (which would cause the wait to time out).
|
|
await this.page
|
|
.locator("[data-testid='session-chat']:visible")
|
|
.first()
|
|
.waitFor({ state: "visible", timeout });
|
|
}
|
|
|
|
/** Wait for the passthrough terminal to be visible (for TUI/passthrough sessions). */
|
|
async waitForPassthroughLoad(timeout = 15_000) {
|
|
await this.passthroughTerminal.waitFor({ state: "visible", timeout });
|
|
}
|
|
|
|
/** Wait for the passthrough loading indicator to be visible (scoped to agent terminal). */
|
|
async waitForPassthroughLoading(timeout = 5_000) {
|
|
await this.passthroughTerminal
|
|
.getByTestId("passthrough-loading")
|
|
.waitFor({ state: "visible", timeout });
|
|
}
|
|
|
|
/** Wait for the passthrough loading indicator to disappear (scoped to agent terminal). */
|
|
async waitForPassthroughLoaded(timeout = 15_000) {
|
|
await this.passthroughTerminal
|
|
.getByTestId("passthrough-loading")
|
|
.waitFor({ state: "hidden", timeout });
|
|
}
|
|
|
|
/**
|
|
* Read the text content of an xterm.js terminal buffer.
|
|
* xterm renders to canvas/WebGL so text isn't in the DOM. Uses the
|
|
* __xtermReadBuffer() helper exposed on the terminal container element.
|
|
*/
|
|
private readXtermBuffer(testId: string): Promise<string> {
|
|
return this.page.evaluate((tid) => {
|
|
const panel = document.querySelector(`[data-testid="${tid}"]`);
|
|
if (!panel) return "";
|
|
const xtermEl = panel.querySelector(".xterm");
|
|
type XC = HTMLElement & { __xtermReadBuffer?: () => string };
|
|
const container = xtermEl?.parentElement as XC | null | undefined;
|
|
return container?.__xtermReadBuffer?.() ?? "";
|
|
}, testId);
|
|
}
|
|
|
|
/**
|
|
* Assert the passthrough terminal buffer contains the given text.
|
|
*/
|
|
async expectPassthroughHasText(text: string, timeout = 15_000): Promise<void> {
|
|
await expect
|
|
.poll(async () => (await this.readXtermBuffer("passthrough-terminal")).includes(text), {
|
|
timeout,
|
|
message: `Expected passthrough terminal to contain "${text}"`,
|
|
})
|
|
.toBe(true);
|
|
}
|
|
|
|
/**
|
|
* Assert the passthrough terminal buffer does NOT contain the given text.
|
|
* Waits briefly to confirm absence (text could arrive asynchronously).
|
|
*/
|
|
async expectPassthroughNotHasText(text: string, stableMs = 2_000): Promise<void> {
|
|
const start = Date.now();
|
|
while (Date.now() - start < stableMs) {
|
|
if ((await this.readXtermBuffer("passthrough-terminal")).includes(text)) {
|
|
throw new Error(`Expected passthrough terminal NOT to contain "${text}", but it was found`);
|
|
}
|
|
await this.page.waitForTimeout(200);
|
|
}
|
|
}
|
|
|
|
/** Scoped to the sidebar — finds task title text rendered by TaskItem. */
|
|
taskInSidebar(title: string): Locator {
|
|
return this.sidebar.getByText(title, { exact: false });
|
|
}
|
|
|
|
/**
|
|
* Sidebar state indicator — returns the first icon matching the given state label.
|
|
* Accepts "Turn Finished" (review/completed), "Running" (in-progress), or "Backlog".
|
|
*/
|
|
sidebarSection(label: string): Locator {
|
|
const testId = sectionLabelToStateTestId(label);
|
|
return this.sidebar.getByTestId(testId).first();
|
|
}
|
|
|
|
/**
|
|
* Task item in the sidebar matching both a title and a state label.
|
|
* Accepts "Turn Finished" (review/completed), "Running" (in-progress), or "Backlog".
|
|
*/
|
|
taskInSection(title: string, sectionLabel: string): Locator {
|
|
const testId = sectionLabelToStateTestId(sectionLabel);
|
|
return this.sidebar
|
|
.getByTestId("sidebar-task-item")
|
|
.filter({ has: this.page.getByText(title, { exact: false }) })
|
|
.filter({ has: this.page.getByTestId(testId) });
|
|
}
|
|
|
|
/** Agent STARTING or RUNNING status indicator. */
|
|
agentStatus(): Locator {
|
|
return this.page.getByRole("status", { name: /Agent is (starting|running)/ });
|
|
}
|
|
|
|
/** Divider that appears after the "New session started" status message is rendered. */
|
|
turnComplete(): Locator {
|
|
return this.page.getByTestId("agent-turn-complete");
|
|
}
|
|
|
|
/** Chat input placeholder when agent is idle (default mode). */
|
|
idleInput(): Locator {
|
|
return this.page.locator('[data-placeholder="Continue working on the task..."]');
|
|
}
|
|
|
|
/** Chat input placeholder when agent is idle (plan mode). */
|
|
planModeInput(): Locator {
|
|
return this.page.locator('[data-placeholder="Continue working on the plan..."]');
|
|
}
|
|
|
|
/**
|
|
* "Plan mode" badge shown on a message that was sent with plan mode active.
|
|
* Appears when message.metadata.plan_mode = true, which the backend sets when
|
|
* a session is auto-started via the enable_plan_mode workflow event.
|
|
*/
|
|
planModeBadge(): Locator {
|
|
return this.chat.getByText("Plan mode", { exact: true });
|
|
}
|
|
|
|
/** Clarification overlay (visible when a clarification request is pending). */
|
|
clarificationOverlay(): Locator {
|
|
return this.page.getByTestId("clarification-overlay");
|
|
}
|
|
|
|
/** A specific clarification option button by its text label. */
|
|
clarificationOption(text: string): Locator {
|
|
return this.clarificationOverlay()
|
|
.getByTestId("clarification-option")
|
|
.filter({ hasText: text });
|
|
}
|
|
|
|
/** Skip (X) button on the clarification overlay. */
|
|
clarificationSkip(): Locator {
|
|
return this.page.getByTestId("clarification-skip");
|
|
}
|
|
|
|
/** Custom text input on the clarification overlay. */
|
|
clarificationInput(): Locator {
|
|
return this.page.getByTestId("clarification-input");
|
|
}
|
|
|
|
/** Deferred notice shown when agent has disconnected from clarification. */
|
|
clarificationDeferredNotice(): Locator {
|
|
return this.page.getByTestId("clarification-deferred-notice");
|
|
}
|
|
|
|
/** Expired notice rendered in chat history when the agent timed out waiting. */
|
|
clarificationExpiredNotice(): Locator {
|
|
return this.page.getByTestId("clarification-expired-notice");
|
|
}
|
|
|
|
/** Label span inside a clarification option. */
|
|
clarificationOptionLabels(): Locator {
|
|
return this.clarificationOverlay().getByTestId("clarification-option-label");
|
|
}
|
|
|
|
/** Description span inside a clarification option (hidden when option has none). */
|
|
clarificationOptionDescriptions(): Locator {
|
|
return this.clarificationOverlay().getByTestId("clarification-option-description");
|
|
}
|
|
|
|
/** Reset context button in the chat input toolbar. */
|
|
resetContextButton(): Locator {
|
|
return this.page.getByTestId("reset-context-button");
|
|
}
|
|
|
|
/** Confirm button in the reset context alert dialog. */
|
|
resetContextConfirm(): Locator {
|
|
return this.page.getByTestId("reset-context-confirm");
|
|
}
|
|
|
|
/** "Resume session" button shown after agent crash. */
|
|
recoveryResumeButton(): Locator {
|
|
return this.page.getByTestId("recovery-resume-button");
|
|
}
|
|
|
|
/** "Start fresh session" button shown after agent crash. */
|
|
recoveryFreshButton(): Locator {
|
|
return this.page.getByTestId("recovery-fresh-button");
|
|
}
|
|
|
|
/** Context reset divider shown in chat after resetting agent context. */
|
|
contextResetDivider(): Locator {
|
|
return this.chat.getByText("Context reset");
|
|
}
|
|
|
|
/**
|
|
* Delete a task via the sidebar context menu.
|
|
* Hovers to reveal the menu trigger, opens it, and clicks "Delete".
|
|
*/
|
|
async deleteTaskInSidebar(title: string): Promise<void> {
|
|
await this.openSidebarMenuAndClick(title, "Delete");
|
|
}
|
|
|
|
/**
|
|
* Archive a task via the sidebar context menu.
|
|
* Hovers to reveal the menu trigger, opens it, clicks "Archive",
|
|
* and confirms the archive dialog.
|
|
*/
|
|
async archiveTaskInSidebar(title: string): Promise<void> {
|
|
await this.openSidebarMenuAndClick(title, "Archive");
|
|
// Confirm the archive dialog
|
|
const confirmButton = this.page
|
|
.getByRole("alertdialog")
|
|
.getByRole("button", { name: "Archive" });
|
|
await confirmButton.click();
|
|
}
|
|
|
|
/**
|
|
* Open a sidebar task's dropdown menu and click an item.
|
|
* Retries the full open-click sequence if the menu gets detached by a
|
|
* React re-render (e.g. WS-driven sidebar update) between open and click.
|
|
*/
|
|
private async openSidebarMenuAndClick(
|
|
title: string,
|
|
itemName: string,
|
|
retries = 3,
|
|
): Promise<void> {
|
|
const taskRow = this.sidebar.locator('[role="button"]').filter({ hasText: title });
|
|
for (let attempt = 0; attempt < retries; attempt++) {
|
|
try {
|
|
await taskRow.hover();
|
|
await taskRow.getByRole("button", { name: "Task actions" }).click();
|
|
const menuItem = this.page.getByRole("menuitem", { name: itemName });
|
|
await menuItem.waitFor({ state: "visible", timeout: 3_000 });
|
|
await menuItem.click({ timeout: 3_000 });
|
|
return;
|
|
} catch {
|
|
// Menu was likely detached by a re-render — dismiss and retry
|
|
await this.page.keyboard.press("Escape");
|
|
await this.page.waitForTimeout(500);
|
|
}
|
|
}
|
|
// Final attempt without catch
|
|
await taskRow.hover();
|
|
await taskRow.getByRole("button", { name: "Task actions" }).click();
|
|
await this.page.getByRole("menuitem", { name: itemName }).click();
|
|
}
|
|
|
|
stepperStep(name: string): Locator {
|
|
return this.page.getByTestId(`workflow-step-${name}`);
|
|
}
|
|
|
|
/** PR button in the topbar (visible only when a PR is associated). */
|
|
prTopbarButton(): Locator {
|
|
return this.page.getByTestId("pr-topbar-button");
|
|
}
|
|
|
|
/** VCS split button primary action. Pass action to match a specific state. */
|
|
vcsPrimaryButton(action?: "commit" | "push" | "pr" | "rebase"): Locator {
|
|
if (action) {
|
|
return this.page.getByTestId(`vcs-primary-${action}`);
|
|
}
|
|
return this.page.locator('[data-testid^="vcs-primary-"]');
|
|
}
|
|
|
|
/** PR detail panel (auto-shown when task has an associated PR). */
|
|
prDetailPanel(): Locator {
|
|
return this.page.getByTestId("pr-detail-panel");
|
|
}
|
|
|
|
/**
|
|
* Assert the `pr-detail` panel's dockview group contains at least one
|
|
* `session:{sessionId}` panel — i.e. the PR opened as a tab next to a
|
|
* session chat, not as a split in a separate group. Regression guard for
|
|
* the "PR opens in a split instead of the center tab" bug.
|
|
*
|
|
* Checks group membership of the PR panel directly rather than picking a
|
|
* session panel first, so the assertion is deterministic even when outgoing
|
|
* and incoming session panels briefly coexist during a task switch.
|
|
*/
|
|
async expectPrPanelAndSessionShareGroup(): Promise<void> {
|
|
const result = await this.page.evaluate(() => {
|
|
type Panel = { id: string; group?: { id?: string } };
|
|
type Api = { panels: Panel[]; getPanel: (i: string) => Panel | undefined };
|
|
const api = (window as unknown as { __dockviewApi__?: Api }).__dockviewApi__;
|
|
if (!api) return { error: "dockview api not exposed" };
|
|
const pr = api.getPanel("pr-detail");
|
|
if (!pr) return { error: "pr-detail panel missing" };
|
|
const prGroupId = pr.group?.id ?? null;
|
|
const sessionPanels = api.panels.filter((p) => p.id.startsWith("session:"));
|
|
if (sessionPanels.length === 0) return { error: "no session panel" };
|
|
const sessionInPrGroup = sessionPanels.some((p) => p.group?.id === prGroupId);
|
|
return {
|
|
sessionInPrGroup,
|
|
prGroupId,
|
|
sessionLocations: sessionPanels.map((p) => `${p.id}@${p.group?.id ?? "?"}`),
|
|
};
|
|
});
|
|
expect(result.error, result.error).toBeUndefined();
|
|
expect(
|
|
result.sessionInPrGroup,
|
|
`PR panel landed in a dockview group that contains no session chat. ` +
|
|
`PR group=${result.prGroupId} sessions=[${result.sessionLocations?.join(", ")}]`,
|
|
).toBe(true);
|
|
}
|
|
|
|
/** Dockview tab for the PR detail panel (title starts as "Pull Request", updated to "PR #N"). */
|
|
prDetailTab(): Locator {
|
|
return this.page.locator(".dv-default-tab").filter({ hasText: /^(Pull Request|PR #\d+)$/ });
|
|
}
|
|
|
|
/** Click a dockview tab by its visible label (e.g. "Changes", "Files", "Terminal"). */
|
|
async clickTab(label: string): Promise<void> {
|
|
const tab = this.page.locator(`.dv-default-tab:has-text('${label}')`);
|
|
await tab.click();
|
|
}
|
|
|
|
/**
|
|
* Click the session/chat tab regardless of its current title.
|
|
* Session tabs are renamed from "Agent" to "#N AgentName" by useChatSessionTitle,
|
|
* so this uses the stable data-testid on the ContextMenuTrigger instead.
|
|
*/
|
|
async clickSessionChatTab(): Promise<void> {
|
|
await this.page.locator('[data-testid^="session-tab-"]').first().click();
|
|
}
|
|
|
|
/** PR files section within the changes panel. */
|
|
prFilesSection(): Locator {
|
|
return this.changes.getByTestId("pr-files-section");
|
|
}
|
|
|
|
/** Commits section within the changes panel (unified list of pushed + unpushed commits). */
|
|
commitsSection(): Locator {
|
|
return this.changes.getByTestId("commits-section");
|
|
}
|
|
|
|
/**
|
|
* Types a message into the TipTap chat input and sends it.
|
|
* Default submit key is Cmd+Enter (chatSubmitKey = "cmd_enter").
|
|
* TipTap maps "Mod" to Meta on macOS and Control on Linux/Windows.
|
|
*/
|
|
async sendMessage(text: string) {
|
|
const editor = this.page.locator(".tiptap.ProseMirror").first();
|
|
await editor.click();
|
|
await editor.fill(text);
|
|
const modifier = process.platform === "darwin" ? "Meta" : "Control";
|
|
await editor.press(`${modifier}+Enter`);
|
|
}
|
|
|
|
/** Toggle plan mode on/off by clicking the plan mode toggle button in the toolbar. */
|
|
async togglePlanMode() {
|
|
const btn = this.page.getByTestId("plan-mode-toggle-button");
|
|
await expect(btn).toBeVisible({ timeout: 10_000 });
|
|
await btn.click();
|
|
}
|
|
|
|
/**
|
|
* Wait for the terminal shell to be connected (buffer has content from
|
|
* the prompt), then type a command and press Enter.
|
|
*/
|
|
async typeInTerminal(command: string): Promise<void> {
|
|
await expect
|
|
.poll(async () => (await this.readXtermBuffer("terminal-panel")).length > 0, {
|
|
timeout: 15_000,
|
|
message: "Waiting for terminal shell to connect",
|
|
})
|
|
.toBe(true);
|
|
|
|
const xterm = this.terminal.locator(".xterm");
|
|
await xterm.click();
|
|
await this.page.keyboard.type(command);
|
|
await this.page.keyboard.press("Enter");
|
|
}
|
|
|
|
/**
|
|
* Assert the terminal buffer contains the given text.
|
|
*/
|
|
async expectTerminalHasText(text: string): Promise<void> {
|
|
await expect
|
|
.poll(async () => (await this.readXtermBuffer("terminal-panel")).includes(text), {
|
|
timeout: 10_000,
|
|
message: `Expected terminal to contain "${text}"`,
|
|
})
|
|
.toBe(true);
|
|
}
|
|
|
|
/**
|
|
* Click the maximize button on the dockview group that contains a tab
|
|
* with the given name. Defaults to "Terminal".
|
|
*/
|
|
async clickMaximize(tabName = "Terminal"): Promise<void> {
|
|
const header = this.page.locator(
|
|
`.dv-tabs-and-actions-container:has(.dv-default-tab:has-text('${tabName}'))`,
|
|
);
|
|
await header.getByTestId("dockview-maximize-btn").click();
|
|
}
|
|
|
|
/**
|
|
* Assert the layout is in maximized state: terminal visible,
|
|
* sidebar visible (UI: |sidebar|maximized-group|), chat and files hidden.
|
|
*/
|
|
async expectMaximized(): Promise<void> {
|
|
await expect(this.terminal).toBeVisible({ timeout: 10_000 });
|
|
await expect(this.sidebar).toBeVisible();
|
|
await expect(this.chat).not.toBeVisible({ timeout: 5_000 });
|
|
await expect(this.files).not.toBeVisible({ timeout: 5_000 });
|
|
}
|
|
|
|
/**
|
|
* Assert the layout is in the default (non-maximized) state:
|
|
* chat, terminal, files, and sidebar are all visible, and layout fills the viewport.
|
|
*/
|
|
async expectDefaultLayout(): Promise<void> {
|
|
await expect(this.chat).toBeVisible({ timeout: 10_000 });
|
|
await expect(this.terminal).toBeVisible({ timeout: 10_000 });
|
|
await expect(this.files).toBeVisible({ timeout: 10_000 });
|
|
await expect(this.sidebar).toBeVisible();
|
|
await this.expectNoLayoutGap();
|
|
}
|
|
|
|
/**
|
|
* Assert the dockview layout columns fill the container with no large empty gap.
|
|
* Catches bugs where columns don't expand after api.fromJSON() + setConstraints
|
|
* (e.g. missing api.layout() call).
|
|
*/
|
|
async expectNoLayoutGap(maxGapPx = 20): Promise<void> {
|
|
await expect
|
|
.poll(
|
|
async () => {
|
|
return this.page.evaluate((maxGap: number) => {
|
|
const dv = document.querySelector(".dv-dockview");
|
|
if (!dv) return false;
|
|
const dvRect = dv.getBoundingClientRect();
|
|
// Find the rightmost edge among all top-level column views
|
|
const views = dv.querySelectorAll(
|
|
".dv-split-view-container.dv-horizontal > .dv-view-container > .dv-view",
|
|
);
|
|
if (views.length === 0) return false;
|
|
let maxRight = 0;
|
|
for (const v of views) {
|
|
const r = v.getBoundingClientRect();
|
|
if (r.width > 0) maxRight = Math.max(maxRight, r.right);
|
|
}
|
|
return dvRect.right - maxRight <= maxGap;
|
|
}, maxGapPx);
|
|
},
|
|
{ timeout: 5_000, message: "Layout has an empty gap on the right side (squished layout)" },
|
|
)
|
|
.toBe(true);
|
|
}
|
|
|
|
/** Git operation error message in chat (shown when a git operation fails). */
|
|
gitOperationErrorMessage(): Locator {
|
|
return this.chat.locator("div:has([data-testid='git-fix-button'])").first();
|
|
}
|
|
|
|
/** Fix button on a git operation error message. */
|
|
gitFixButton(): Locator {
|
|
return this.chat.getByTestId("git-fix-button");
|
|
}
|
|
|
|
/** Locator for the VS Code dockview tab. */
|
|
vscodeTab(): Locator {
|
|
return this.page.locator(".dv-default-tab:has-text('VS Code')");
|
|
}
|
|
|
|
/** Locator for the VS Code code-server iframe. */
|
|
vscodeIframe(): Locator {
|
|
return this.page.locator('iframe[title="VS Code"]');
|
|
}
|
|
|
|
// --- New Session Dialog ---
|
|
|
|
/** "+" button in the dockview header to open the add-panel dropdown. */
|
|
addPanelButton(): Locator {
|
|
return this.page.getByTestId("dockview-add-panel-btn").first();
|
|
}
|
|
|
|
/** "New Session" menu item in the dockview + dropdown. */
|
|
newSessionMenuButton(): Locator {
|
|
return this.page.getByTestId("new-session-button");
|
|
}
|
|
|
|
/** Open the new session dialog via the + menu. */
|
|
async openNewSessionDialog(): Promise<void> {
|
|
await this.addPanelButton().click();
|
|
await this.newSessionMenuButton().click();
|
|
}
|
|
|
|
/** The new session dialog container. */
|
|
newSessionDialog(): Locator {
|
|
return this.page.getByRole("dialog").filter({ hasText: "New agent in" });
|
|
}
|
|
|
|
/** Prompt textarea inside the new session dialog. */
|
|
newSessionPromptInput(): Locator {
|
|
return this.newSessionDialog().locator("textarea");
|
|
}
|
|
|
|
/** Start Agent button inside the new session dialog. */
|
|
newSessionStartButton(): Locator {
|
|
return this.newSessionDialog().getByRole("button", { name: "Start Agent" });
|
|
}
|
|
|
|
/** Environment info badges inside the new session dialog. */
|
|
newSessionEnvironmentInfo(): Locator {
|
|
return this.newSessionDialog().getByText("Same environment as current session");
|
|
}
|
|
|
|
/** Session tab in dockview by session label (e.g., "Session 1", "Session 2"). */
|
|
sessionTab(label: string): Locator {
|
|
return this.page.locator(`.dv-default-tab:has-text('${label}')`);
|
|
}
|
|
|
|
/** Session item in the + dropdown's reopen list by session ID. */
|
|
sessionReopenItem(sessionId: string): Locator {
|
|
return this.page.getByTestId(`reopen-session-${sessionId}`);
|
|
}
|
|
|
|
/** All session reopen items in the + dropdown. */
|
|
sessionReopenItems(): Locator {
|
|
return this.page.locator("[data-testid^='reopen-session-']");
|
|
}
|
|
|
|
/** All session tabs in dockview (panels using the sessionTab tab component). */
|
|
sessionTabs(): Locator {
|
|
return this.page.locator(".dv-default-tab").filter({
|
|
has: this.page.locator("[data-testid^='reopen-session-'], .tabler-icon-star").first(),
|
|
});
|
|
}
|
|
|
|
/** Dockview session tab matched by partial text (e.g., "Mock Agent" or index "1"). */
|
|
sessionTabByText(text: string): Locator {
|
|
return this.page.locator(`[data-testid^='session-tab-']:has-text('${text}')`);
|
|
}
|
|
|
|
/** Session tab container identified by session ID (data-testid="session-tab-{id}"). */
|
|
sessionTabBySessionId(sessionId: string): Locator {
|
|
return this.page.getByTestId(`session-tab-${sessionId}`);
|
|
}
|
|
|
|
/** Context menu on a dockview tab — right-click the tab to trigger it. */
|
|
async rightClickTab(text: string): Promise<void> {
|
|
const tab = this.page.locator(`[data-testid^='session-tab-']:has-text('${text}')`);
|
|
await tab.click({ button: "right" });
|
|
}
|
|
|
|
/** Right-click the first session tab (useful when there is only one session). */
|
|
async rightClickFirstSessionTab(): Promise<void> {
|
|
const tab = this.page.locator("[data-testid^='session-tab-']").first();
|
|
await tab.click({ button: "right" });
|
|
}
|
|
|
|
/** Context menu item by visible label. */
|
|
contextMenuItem(label: string): Locator {
|
|
return this.page.getByRole("menuitem", { name: label });
|
|
}
|
|
|
|
/** Alert dialog (e.g., delete confirmation). */
|
|
alertDialog(): Locator {
|
|
return this.page.getByRole("alertdialog");
|
|
}
|
|
|
|
/** Primary star icon inside a dockview tab. */
|
|
primaryStarInTab(text: string): Locator {
|
|
const tab = this.page.locator(`.dv-default-tab:has-text('${text}')`);
|
|
return tab.locator(".tabler-icon-star").first();
|
|
}
|
|
|
|
/** "Move to next step" button in the chat status bar. */
|
|
proceedNextStepButton(): Locator {
|
|
return this.page.getByTestId("proceed-next-step");
|
|
}
|
|
|
|
/** Click a task in the sidebar by title. */
|
|
async clickTaskInSidebar(title: string): Promise<void> {
|
|
const taskRow = this.sidebar.locator("[role='button']").filter({ hasText: title });
|
|
await taskRow.click();
|
|
}
|
|
|
|
// --- File tree multi-select helpers ---
|
|
|
|
/** Find a tree node by its data-path attribute. */
|
|
fileTreeNode(nodePath: string): Locator {
|
|
return this.files.locator(`[data-testid="file-tree-node"][data-path="${nodePath}"]`);
|
|
}
|
|
|
|
/** All file tree nodes with data-selected="true". */
|
|
fileTreeSelectedNodes(): Locator {
|
|
return this.files.locator("[data-selected='true']");
|
|
}
|
|
|
|
// --- Changes panel multi-select helpers ---
|
|
|
|
/** Find a file row in the changes panel by path. */
|
|
changesFileRow(path: string): Locator {
|
|
return this.changes.locator(`[data-changes-file="${path}"]`);
|
|
}
|
|
|
|
/** All selected file rows in the changes panel. */
|
|
changesSelectedRows(): Locator {
|
|
return this.changes.locator("[data-selected='true']");
|
|
}
|
|
|
|
/** Bulk action bar for a variant (unstaged/staged). */
|
|
changesBulkActionBar(variant: "unstaged" | "staged"): Locator {
|
|
return this.changes.getByTestId(`bulk-actions-${variant}`);
|
|
}
|
|
|
|
/** Bulk stage button (unstaged section). */
|
|
changesBulkStageButton(): Locator {
|
|
return this.changes.getByTestId("bulk-stage");
|
|
}
|
|
|
|
/** Bulk unstage button (staged section). */
|
|
changesBulkUnstageButton(): Locator {
|
|
return this.changes.getByTestId("bulk-unstage-staged");
|
|
}
|
|
|
|
/** Bulk discard button for a variant. */
|
|
changesBulkDiscardButton(variant: "unstaged" | "staged" = "unstaged"): Locator {
|
|
return this.changes.getByTestId(`bulk-discard-${variant}`);
|
|
}
|
|
|
|
// --- Panel search helpers (Ctrl+F feature) ---
|
|
|
|
/** Any currently-mounted panel search bar. */
|
|
panelSearchBar(): Locator {
|
|
return this.page.locator("[data-panel-search-bar]");
|
|
}
|
|
|
|
/** Search input inside the currently-mounted bar. */
|
|
panelSearchInput(): Locator {
|
|
return this.panelSearchBar().locator('input[type="text"]');
|
|
}
|
|
|
|
/** "N / M" match counter. */
|
|
panelSearchCounter(): Locator {
|
|
return this.panelSearchBar().locator('[aria-live="polite"]');
|
|
}
|
|
}
|