diff --git a/packages/app/component-tests/composer.spec.ts b/packages/app/component-tests/composer.spec.ts index 73358c2bb21..974cd782497 100644 --- a/packages/app/component-tests/composer.spec.ts +++ b/packages/app/component-tests/composer.spec.ts @@ -38,7 +38,9 @@ story("cycles full prompts with plain arrows without opening the picker", async await input.press("ArrowUp") await input.press("ArrowUp") await expect(input).toHaveText("Review the composer layout\nKeep keyboard navigation accessible") - await input.fill("") + // A history step places the caret a frame later. Keys flush it first; a fill's direct selection would lose to it. + await input.press("ControlOrMeta+a") + await input.press("Delete") await input.press("ArrowUp") await expect(input).toHaveText("Explain the latest changes") await expect(component.getByRole("img", { name: "layout.png", exact: true })).toHaveCount(0) @@ -60,7 +62,8 @@ story("cycles full prompts with plain arrows without opening the picker", async await input.press("ArrowUp") await expect(input).toHaveText("R!eview the composer layout\nKeep keyboard navigation accessible") - await input.fill("") + await input.press("ControlOrMeta+a") + await input.press("Delete") await input.press("ArrowUp") await expect(input).toHaveText("Explain the latest changes") await input.press("Enter") @@ -70,7 +73,8 @@ story("cycles full prompts with plain arrows without opening the picker", async await expect(input).toHaveText("Explain the latest changes") await expect(options).toHaveCount(0) - await input.fill("!") + await input.press("ControlOrMeta+a") + await input.press("!") await expect(input).toBeEmpty() await input.press("ArrowUp") await expect(input).toHaveText("bun typecheck") @@ -436,6 +440,9 @@ for (const direction of ["ltr", "rtl"]) { await expect(add).toBeInViewport() await add.click() await expect(page.getByRole("menuitem", { name: "Images and files" })).toBeVisible() + // The menu takes focus a task after it opens. Closed before that, it returns focus to the trigger later still, + // taking it from the prompt this test fills next. + await expect(page.getByRole("menu")).toBeFocused() await page.keyboard.press("Escape") await expect(add).toBeFocused() expect(await add.boundingBox()).toEqual(fixedAdd) @@ -482,6 +489,8 @@ story("keeps toolbar focus rings whole and keyboard-only", async ({ mount, page // A menu the pointer opened returns focus to its trigger without a ring, even when Escape closes it. await variant.click() await expect(page.getByRole("menuitemradio", { name: "high", exact: true })).toBeVisible() + // The menu takes focus a task after it opens; an Escape before that rings the trigger, which still holds focus. + await expect(page.getByRole("menu")).toBeFocused() await page.keyboard.press("Escape") await expect(variant).toBeFocused() await expect(variant).toHaveCSS("outline-style", "none") diff --git a/packages/app/component-tests/focus-ring.spec.ts b/packages/app/component-tests/focus-ring.spec.ts index f655bd0456d..50027375cae 100644 --- a/packages/app/component-tests/focus-ring.spec.ts +++ b/packages/app/component-tests/focus-ring.spec.ts @@ -6,6 +6,8 @@ story("returns focus to a menu trigger without a ring after a pointer open", asy await trigger.click() await expect(page.getByRole("menuitem", { name: "Save" })).toBeVisible() + // The menu takes focus a task after it opens; an Escape before that rings the trigger, which still holds focus. + await expect(page.getByRole("menu")).toBeFocused() await page.keyboard.press("Escape") await expect(trigger).toBeFocused() await expect(trigger).toHaveCSS("outline-style", "none") @@ -45,6 +47,8 @@ story("leaves focus where an outside click put it when a non-modal menu closes", await trigger.click() await expect(page.getByRole("menuitem", { name: "Pin" })).toBeVisible() + // Kobalte starts listening for outside presses a task after the menu opens, queued behind the one that focuses it. + await expect(page.getByRole("menu")).toBeFocused() await page.mouse.click(4, 300) await expect(page.getByRole("menuitem", { name: "Pin" })).toHaveCount(0) // The close focus restore has run once the story counts it; the click on empty space left focus on the body. diff --git a/packages/app/component-tests/session-question-dock.spec.ts b/packages/app/component-tests/session-question-dock.spec.ts index ec457e265f3..0baa97d51ec 100644 --- a/packages/app/component-tests/session-question-dock.spec.ts +++ b/packages/app/component-tests/session-question-dock.spec.ts @@ -1009,12 +1009,13 @@ story.describe("with the new question UI experiment enabled", () => { expect(values.slice(1).every((value, i) => way * (value - values[i]!) >= -0.01)).toBe(true) } - story("fades Back in and out and turns Next into Submit with the switch", async ({ mount }) => { + story("fades Back in and out and turns Next into Submit with the switch", async ({ mount, page }) => { const component = await mount("session-question-switch--question-series") const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') const back = question.locator('[data-slot="question-footer-back"]') await expect(question.getByRole("radio").first()).toBeFocused() await expect(question.getByRole("button", { name: "Back", exact: true })).toHaveCount(0) + await page.evaluate(() => document.fonts.ready.then(() => undefined)) // Going on from the first question, Back comes in and can be clicked at once, while Next stays where it is. const nextBox = await question.getByRole("button", { name: "Next", exact: true }).boundingBox() diff --git a/packages/app/e2e/regression/mcp-workspace-toggle.spec.ts b/packages/app/e2e/regression/mcp-workspace-toggle.spec.ts index 227abf79391..492ca9bf37b 100644 --- a/packages/app/e2e/regression/mcp-workspace-toggle.spec.ts +++ b/packages/app/e2e/regression/mcp-workspace-toggle.spec.ts @@ -479,6 +479,8 @@ test("toggling an MCP from the dialog keeps it highlighted", async ({ page }) => const row = view.panel.getByRole("option").filter({ hasText: "figma-desktop" }) const toggle = row.getByRole("switch", { name: "figma-desktop", exact: true }) + // The dialog focuses its search a task after it opens; keys pressed before then go to the composer behind it. + await expect(view.panel.getByRole("combobox", { name: "Search MCPs", exact: true })).toBeFocused() // From the keyboard, Enter toggles the highlighted server and the highlight stays on it. await page.keyboard.press("ArrowDown") await expect(row).toHaveAttribute("aria-selected", "true") diff --git a/packages/app/e2e/regression/tabs.spec.ts b/packages/app/e2e/regression/tabs.spec.ts index 7a5bd803a42..2dab3958d0a 100644 --- a/packages/app/e2e/regression/tabs.spec.ts +++ b/packages/app/e2e/regression/tabs.spec.ts @@ -1076,6 +1076,10 @@ test("a remote tab stays busy while a child session runs", async ({ page }) => { test("inactive tabs stay busy while work waits in their inbox, and pulse on a new prompt, as in the TUI", async ({ page, }) => { + // An inactive tab reads its inbox after a delay. The mock's inbox never gains pushed items, so a prompt pushed + // before that read starts would be replaced by the older snapshot. + const inboxC = page.waitForResponse(new RegExp(`/api/session/${c.id}/inbox(\\?|$)`)) + const workspace = await openSession(page, { name: "TabInbox", sessions: [a, b, c], @@ -1104,6 +1108,7 @@ test("inactive tabs stay busy while work waits in their inbox, and pulse on a ne const progress = '[data-component="activity-ring"]' await expect(tab(b.id).locator(progress)).toBeVisible() + await inboxC await expect(tab(c.id).locator("[data-titlebar-tab-title]")).toHaveText(c.title) await expect(tab(c.id).locator(progress)).toBeHidden() await expect(tab(c.id).locator('[data-slot="tab-prompt-pulse"]')).toHaveCount(0) @@ -2100,15 +2105,21 @@ test("the inbox waits for initial requests and orders attention by waiting age r }) const pending = await holdRoute(page, /\/api\/session\/ses_waiting_old\/permission(?:\?|$)/) + // Running sessions join Working only once this snapshot loads, which can be after the inbox shows; runs it reveals + // had already started, so they are not announced. + const running = await holdRoute(page, /\/api\/session\/active(?:\?|$)/) await page.goto("/") - await pending.arrived + await Promise.all([pending.arrived, running.arrived]) const inbox = page.locator('[data-slot="sidebar-inbox"]') await expect(inbox).toHaveAttribute("aria-busy", "true") await expect(inbox.getByText("Sessions you work on will appear here", { exact: true })).toHaveCount(0) + const checked = page.waitForResponse(/\/api\/session\/ses_waiting_old\/permission(?:\?|$)/) pending.release() + await checked + running.release() const needs = inbox .getByRole("group", { name: "Needs attention", exact: true }) diff --git a/packages/app/e2e/regression/terminal.spec.ts b/packages/app/e2e/regression/terminal.spec.ts index 762fd293853..3cbcf093aa7 100644 --- a/packages/app/e2e/regression/terminal.spec.ts +++ b/packages/app/e2e/regression/terminal.spec.ts @@ -58,6 +58,8 @@ test("after a reload, the close shortcut closes the restored terminal", async ({ await openSide(page) await showTerminal(page, "Shell", "pty_shell") + // Focus comes before the connection; a reload during its connect-token request would leave nothing connected. + await expect.poll(() => persistentPty.sockets.map((socket) => socket.id)).toEqual(["pty_shell"]) // The restored tab is selected before the server lists the session's terminals. const list = await holdRoute(page, /\/api\/experimental\/session\/ses_terminals\/terminal(\?|$)/, { method: "GET" }) diff --git a/packages/app/e2e/regression/timeline-history.spec.ts b/packages/app/e2e/regression/timeline-history.spec.ts index 8beb71693d0..954e4f96b67 100644 --- a/packages/app/e2e/regression/timeline-history.spec.ts +++ b/packages/app/e2e/regression/timeline-history.spec.ts @@ -40,7 +40,6 @@ test.describe("timeline history", () => { ] const requests: (string | undefined)[] = [] - await page.clock.install() await openSession(page, { name: "HistoryRestore", sessions: [{ id }, { id: other, directory: "C:/OpenCode/HistoryOther" }], @@ -68,6 +67,9 @@ test.describe("timeline history", () => { await page.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(other)}"]`).click() await expect(page.getByText("Other session", { exact: true })).toBeVisible() + // Only the return needs controlled time. A fake clock from the start also runs the first mount's frames late, + // and a scroll to the end queued by one of them lands after the upward gesture. + await page.clock.install() await page.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(id)}"]`).click() await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") // Exhaust the delayed leading-turn enrichment without a real-time sleep. diff --git a/packages/app/e2e/regression/timeline-stream.spec.ts b/packages/app/e2e/regression/timeline-stream.spec.ts index 64430108b6a..54f3e0dbc8e 100644 --- a/packages/app/e2e/regression/timeline-stream.spec.ts +++ b/packages/app/e2e/regression/timeline-stream.spec.ts @@ -3263,6 +3263,8 @@ test("opens an optional comment beside the quote action and skips it with Alt-cl await page.keyboard.press("Enter") await expect(comment).toHaveCount(0) await expect(chips.nth(0)).toContainText("Why first?") + // The editor takes focus back a frame after the comment closes, and its caret would replace the next selection. + await expect(editor).toBeFocused() await select("The second sentence to quote.") await toolbar.getByRole("button", { name: "Quote", exact: true }).click() diff --git a/packages/app/e2e/utils/timeline.ts b/packages/app/e2e/utils/timeline.ts index bfedc7ba936..3197f2ac0a6 100644 --- a/packages/app/e2e/utils/timeline.ts +++ b/packages/app/e2e/utils/timeline.ts @@ -1120,20 +1120,21 @@ function provider() { /** Hovers a user message, opens the chevron menu its bubble (or, without text, its footer) shows, and picks an action. */ export async function chooseUserMessageAction(page: Page, row: Locator, name: string) { - const bubble = row.locator('[data-slot="user-message-text"]') - - if ((await bubble.count()) > 0) await bubble.hover() - else await row.locator('[data-component="user-message"]').hover() - await row.getByRole("button", { name: "More actions", exact: true }).click() + await openUserMessageMenu(page, row) await page.getByRole("menuitem", { name, exact: true }).click() } /** Hovers a user message, opens its chevron menu, and returns the open menu. */ export async function openUserMessageMenu(page: Page, row: Locator) { - const bubble = row.locator('[data-slot="user-message-text"]') + const message = row.locator('[data-component="user-message"]') + const bubble = message.locator('[data-slot="user-message-text"]') + + // The bubble renders with its message. Counted before the row mounts, it reads 0, and hovering the whole message + // misses the bubble, the only place that reveals a text message's chevron. + await expect(message).toBeVisible() if ((await bubble.count()) > 0) await bubble.hover() - else await row.locator('[data-component="user-message"]').hover() + else await message.hover() await row.getByRole("button", { name: "More actions", exact: true }).click() return page.getByRole("menu") diff --git a/packages/app/src/runtime/plugin/panels.tsx b/packages/app/src/runtime/plugin/panels.tsx index 70a9a7eef48..0df68820c90 100644 --- a/packages/app/src/runtime/plugin/panels.tsx +++ b/packages/app/src/runtime/plugin/panels.tsx @@ -459,8 +459,11 @@ export function createRegion(input: { if (entry) entry.provider.enter?.(panelInput(input.view, input.screen, { tab: entry.tab })) settled(() => { const root = document.getElementById("review-panel") + const current = document.activeElement - if (root && !root.contains(document.activeElement)) root.focus({ preventScroll: true, focusVisible: false }) + // Focus the reader moved during the motion, such as into a menu they opened, stays where they put it. + if (!root || root.contains(current) || (current !== focused && current !== document.body)) return + root.focus({ preventScroll: true, focusVisible: false }) }) }, close(key: string) { diff --git a/packages/app/src/session/timeline/quote-machine.test.ts b/packages/app/src/session/timeline/quote-machine.test.ts index 434287efb45..631c3d7b2a6 100644 --- a/packages/app/src/session/timeline/quote-machine.test.ts +++ b/packages/app/src/session/timeline/quote-machine.test.ts @@ -75,7 +75,7 @@ function shown() { describe("quote machine", () => { test("a press that never sees its release no longer blocks the toolbar after a session switch", () => { - const pressed = transitionQuote(createQuoteState(), { type: "pointer.down" }) + const pressed = transitionQuote(createQuoteState(), { type: "pointer.down", collapsed: true }) expect(pressed.effects).toEqual([{ type: "press.watch" }]) expect(isQuotePressing(pressed.state)).toBe(true) @@ -98,7 +98,12 @@ describe("quote machine", () => { }) test("a release seen as a primary-button-up move reads the drag selection", () => { - const result = play([{ type: "pointer.down" }, SELECTION_CHANGED_QUOTE_EVENT, SELECTION_CHANGED_QUOTE_EVENT]) + const result = play([ + { type: "pointer.down", collapsed: true }, + SELECTION_CHANGED_QUOTE_EVENT, + SELECTION_CHANGED_QUOTE_EVENT, + ]) + // The selection waits for the release. expect(result.effects).toEqual([{ type: "press.watch" }]) @@ -122,7 +127,7 @@ describe("quote machine", () => { test("a settle timer from before a press is ignored", () => { const changed = transitionQuote(createQuoteState(), SELECTION_CHANGED_QUOTE_EVENT).state - const pressed = transitionQuote(changed, { type: "pointer.down" }) + const pressed = transitionQuote(changed, { type: "pointer.down", collapsed: false }) expect(pressed.effects).toEqual([{ type: "settle.cancel" }, { type: "press.watch" }]) expect(transitionQuote(pressed.state, { type: "settle.ready", attempt: settleOf(changed) }).state).toBe( pressed.state, @@ -134,7 +139,7 @@ describe("quote machine", () => { ["a new selection", SELECTION_CHANGED_QUOTE_EVENT], ["a cleared selection", SELECTION_CLEARED_QUOTE_EVENT], ])("the unselectable-press clear is cancelled by %s", (_name, event) => { - const pressed = transitionQuote(shown(), { type: "pointer.down", clearRange: selected.range }) + const pressed = transitionQuote(shown(), { type: "pointer.down", collapsed: false, clearRange: selected.range }) const clear = pressed.state.status === "shown" ? pressed.state.clear : undefined expect(clear).toBeDefined() expect(pressed.effects).toContainEqual({ type: "clear.schedule", attempt: clear!.attempt }) @@ -148,7 +153,12 @@ describe("quote machine", () => { }) test("the unselectable-press clear runs while its press is current", () => { - const pressed = transitionQuote(shown(), { type: "pointer.down", clearRange: selected.range }).state + const pressed = transitionQuote(shown(), { + type: "pointer.down", + collapsed: false, + clearRange: selected.range, + }).state + const clear = pressed.status === "shown" ? pressed.clear! : undefined expect(transitionQuote(pressed, { type: "clear.ready", attempt: clear!.attempt }).effects).toEqual([ @@ -219,9 +229,30 @@ describe("quote machine", () => { expect(transitionQuote(dismissed.state, SELECTION_CLEARED_QUOTE_EVENT).state.status).toBe("idle") }) + test("a press after the dismissed selection was cleared shows a drag over the same range", () => { + const dismissed = transitionQuote(shown(), { type: "escape", range: selected.range, toolbarFocused: false }).state + + // The clear's selectionchange is coalesced with the drag's, so the machine only sees the press on nothing. + const released = play( + [ + { type: "pointer.down", collapsed: true }, + SELECTION_CHANGED_QUOTE_EVENT, + { type: "pointer.up", collapsed: false }, + ], + dismissed, + ).state + + const read = transitionQuote(released, { type: "settle.ready", attempt: settleOf(released) }) + expect(read.effects).toEqual([{ type: "quote.read" }]) + + // A press while the dismissed selection is still there keeps it dismissed. + const held = transitionQuote(dismissed, { type: "pointer.down", collapsed: false }).state + expect(held.status).toBe("dismissed") + }) + test("a resize reads the quote again only once the press is released", () => { const state = shown() - const pressed = transitionQuote(state, { type: "pointer.down" }).state + const pressed = transitionQuote(state, { type: "pointer.down", collapsed: false }).state expect(transitionQuote(pressed, ROOT_RESIZED_QUOTE_EVENT).state).toBe(pressed) const resized = transitionQuote(state, ROOT_RESIZED_QUOTE_EVENT) diff --git a/packages/app/src/session/timeline/quote-machine.ts b/packages/app/src/session/timeline/quote-machine.ts index 3b3012a1de8..749b2d0d6d5 100644 --- a/packages/app/src/session/timeline/quote-machine.ts +++ b/packages/app/src/session/timeline/quote-machine.ts @@ -71,7 +71,8 @@ export type QuoteState = } export type QuoteEvent = - | { readonly type: "pointer.down"; readonly clearRange?: Range } + /** `collapsed`: nothing is selected as the press starts. */ + | { readonly type: "pointer.down"; readonly collapsed: boolean; readonly clearRange?: Range } | { readonly type: "pointer.up"; readonly collapsed: boolean } | { readonly type: "selection.changed"; readonly collapsed: boolean } | { readonly type: "settle.ready"; readonly attempt: number } @@ -155,12 +156,16 @@ export function transitionQuote(state: QuoteState, event: QuoteEvent): QuoteTran const attempt = state.attempt + 1 const clear = state.status === "shown" && event.clearRange ? { attempt, range: event.clearRange } : undefined - // A press ends any settling selection: the release reads it again. + // A press ends any settling selection: the release reads it again. A press that finds nothing selected also ends a + // dismissal, as Chrome can coalesce the clear's selectionchange with those of the next drag, which may select the + // dismissed range again. return { state: state.status === "shown" ? { ...state, attempt, pressing: true, settle: undefined, clear } - : { ...state, attempt, pressing: true, settle: undefined }, + : state.status === "dismissed" && event.collapsed + ? { status: "idle", attempt, pressing: true } + : { ...state, attempt, pressing: true, settle: undefined }, effects: [ ...(state.settle !== undefined ? [SETTLE_CANCEL] : NO_EFFECTS), ...(state.status === "shown" && state.clear ? [CLEAR_CANCEL] : NO_EFFECTS), diff --git a/packages/app/src/session/timeline/quote.tsx b/packages/app/src/session/timeline/quote.tsx index a39cf6c9d95..5e9d144c25a 100644 --- a/packages/app/src/session/timeline/quote.tsx +++ b/packages/app/src/session/timeline/quote.tsx @@ -266,7 +266,11 @@ export function createTimelineQuote(input: { event.clientY <= rect.bottom, ) - dispatch({ type: "pointer.down", clearRange: onSelection ? undefined : range }) + dispatch({ + type: "pointer.down", + collapsed: selection?.isCollapsed ?? true, + clearRange: onSelection ? undefined : range, + }) }) makeEventListener(document, "keydown", (event) => { if (event.defaultPrevented || event.isComposing) return diff --git a/packages/app/src/shell/titlebar/inbox.tsx b/packages/app/src/shell/titlebar/inbox.tsx index 11add571c60..0a1c3e01502 100644 --- a/packages/app/src/shell/titlebar/inbox.tsx +++ b/packages/app/src/shell/titlebar/inbox.tsx @@ -31,7 +31,7 @@ import type { LocalProject } from "@/shell/state/layout" import { sessionTabTitle } from "./tab-title" import { sessionTitle } from "@/session/title" import { createSessionInbox, inboxArchived, type InboxEntry, type InboxStatus } from "./inbox-model" -import { compareWorking } from "./inbox-working" +import { compareWorking, workingSince } from "./inbox-working" const RECENT_LIMIT = 10 @@ -56,16 +56,33 @@ export function SidebarInbox() { const [announcement, setAnnouncement] = createStore({ text: "" }) - createEffect((previous: Map | undefined) => { + createEffect((previous: { underway: Map; statuses: Map } | undefined) => { if (inbox.loading()) return const entries = inbox.entries() + // Runs the server's index shows as started at the first paint, keyed by their start. The running-session snapshot + // can land after that paint and move them into Working; they had already started, so they are not announced. + const underway = + previous?.underway ?? + new Map( + entries.flatMap((entry) => { + const since = workingSince(entry.session) + + return since === undefined ? [] : [[entry.key, since] as const] + }), + ) + if (previous) { const text = entries .flatMap((entry) => { - if (!previous.has(entry.key) || previous.get(entry.key) === entry.status || entry.status === "ready") - return [] + const status = previous.statuses.get(entry.key) + + if (status === undefined || status === entry.status || entry.status === "ready") return [] + + const since = workingSince(entry.session) + + if (entry.status === "working" && since !== undefined && underway.get(entry.key) === since) return [] return [ language.t(`sidebar.inbox.announce.${entry.status}`, { @@ -78,7 +95,7 @@ export function SidebarInbox() { if (text) setAnnouncement("text", text) } - return new Map(entries.map((entry) => [entry.key, entry.status])) + return { underway, statuses: new Map(entries.map((entry) => [entry.key, entry.status])) } }) const sections = createMemo(() => { diff --git a/packages/codemode/test/limits.test.ts b/packages/codemode/test/limits.test.ts index 5e6cbcce973..08539bd9c1a 100644 --- a/packages/codemode/test/limits.test.ts +++ b/packages/codemode/test/limits.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test" -import { Effect, Fiber } from "effect" -import { CodeMode } from "./lib/index.js" +import { Cause, Deferred, Effect, Exit, Fiber, Schema } from "effect" +import { CodeMode, Tool } from "./lib/index.js" import { MAX_ARRAY_LENGTH, MAX_PENDING_PROMISES, MAX_STRING_LENGTH } from "../src/interpreter/limits.js" const runtime = CodeMode.make({ tools: {} }) @@ -72,28 +72,36 @@ describe("one built-in cannot build an unbounded value", () => { describe("the host stays in control", () => { test("other host work keeps running while one long job runs", async () => { - let ticks = 0 - const result = await Effect.runPromise( + // Once the loop starts, the runner yields to the host every millisecond, so the host takes its 20 turns within + // about 20 slices: at most about a million iterations on a fast machine, far short of the job's 30 million. A job + // that kept the thread would finish first. Counting turns instead of timing them keeps this independent of how + // fast the loop runs, and waiting for the start keeps a cold engine's setup out of the count. + const exit = await Effect.runPromise( Effect.gen(function* () { - const counter = yield* Effect.forkChild( - Effect.forever( - Effect.andThen( - Effect.yieldNow, - Effect.sync(() => { - ticks += 1 - }), - ), + const started = yield* Deferred.make() + const job = yield* Effect.forkChild( + CodeMode.make({ + tools: { + host: { + started: Tool.make({ + description: "Mark the loop as started", + input: Schema.Struct({}), + output: Schema.Boolean, + execute: () => Deferred.succeed(started, undefined), + }), + }, + }, + }).execute( + `await tools.host.started({}); let t = 0; for (let i = 0; i < 30_000_000; i++) t += i % 3; return t`, ), ) - const result = yield* runtime.execute(`let t = 0; for (let i = 0; i < 1_000_000; i++) t += i % 3; return t`) - yield* Fiber.interrupt(counter) - return result + yield* Deferred.await(started) + for (let turn = 0; turn < 20; turn++) yield* Effect.yieldNow + yield* Fiber.interrupt(job) + return yield* Fiber.await(job) }), ) - expect(result).toMatchObject({ ok: true, value: 999_999 }) - // The loop takes well over 10 ms anywhere, and the runner yields to the host every millisecond; a job that kept - // the thread for its whole run would let the counter tick at most a couple of times around it. - expect(ticks).toBeGreaterThan(10) + expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true) }) // Each case would run for seconds or forever; the timeout must still stop it promptly. diff --git a/packages/core/test/plugin/module.test.ts b/packages/core/test/plugin/module.test.ts index ca2fde92ded..23f53e96343 100644 --- a/packages/core/test/plugin/module.test.ts +++ b/packages/core/test/plugin/module.test.ts @@ -1,5 +1,5 @@ import { expect } from "bun:test" -import { cp } from "node:fs/promises" +import { cp, mkdir } from "node:fs/promises" import path from "node:path" import { Brand, Cause, Deferred, Effect, Exit, Fiber, Layer, Option, Schedule, Schema, Scope, Stream } from "effect" import { Agent } from "@opencode/schema/agent" @@ -40,6 +40,15 @@ it.live("watches creation of an external helper with missing parent directories" const modules = yield* PluginModule.make() const operation = { type: "add" as const, target: path.dirname(entry), options: {} } expect(Exit.isFailure(yield* modules.load(operation).pipe(Effect.exit))).toBe(true) + // Parcel's Windows backend starts reading changes on its own thread after subscribe resolves, so a file created + // right away can go unseen. Create probe directories, one event each, until the watch reports one. + const armed = yield* modules.changes().pipe(Stream.runHead, Effect.forkScoped({ startImmediately: true })) + let probes = 0 + yield* Effect.promise(() => mkdir(path.join(directory.path, `probe-${probes++}`))).pipe( + Effect.andThen(Fiber.join(armed).pipe(Effect.timeout("500 millis"))), + Effect.retry(Schedule.forever), + Effect.timeout("10 seconds"), + ) const changed = yield* modules .changes() .pipe(Stream.runHead, Effect.timeout("5 seconds"), Effect.forkScoped({ startImmediately: true })) diff --git a/packages/sdk/test/import-boundaries.test.ts b/packages/sdk/test/import-boundaries.test.ts index 57779a47506..55250a5267e 100644 --- a/packages/sdk/test/import-boundaries.test.ts +++ b/packages/sdk/test/import-boundaries.test.ts @@ -1,5 +1,4 @@ import { expect, test } from "bun:test" -import { mkdtemp, rm } from "node:fs/promises" import { join, resolve, sep } from "node:path" const directory = resolve(import.meta.dir, "..") @@ -7,47 +6,33 @@ const client = resolve(import.meta.dir, "../../client") const core = resolve(import.meta.dir, "../../core") const server = resolve(import.meta.dir, "../../server") +// One in-process build parses the shared graph once and keeps entries and output in memory: two `bun build` children, +// each writing a 23 MB bundle to disk, ran past 5s on loaded Windows runners. The build still parses and links about +// 2,600 source files, hence the longer timeout. test("bundles the Promise and Effect clients with the in-memory host", async () => { - const bundles = await Promise.all([bundleInputs("@opencode/sdk"), bundleInputs("@opencode/sdk/effect")]) + const entrypoints = { promise: join(directory, "promise-entry.ts"), effect: join(directory, "effect-entry.ts") } + const result = await Bun.build({ + entrypoints: Object.values(entrypoints), + files: { + [entrypoints.promise]: 'export * from "@opencode/sdk"', + [entrypoints.effect]: 'export * from "@opencode/sdk/effect"', + }, + target: "bun", + format: "esm", + packages: "bundle", + metafile: true, + }) + const outputs = Object.values(result.metafile?.outputs ?? {}).filter((output) => output.entryPoint) + expect(outputs).toHaveLength(2) - for (const inputs of bundles) { + for (const output of outputs) { + // Metafile paths are relative to the working directory. + const inputs = Object.keys(output.inputs).map((input) => resolve(input)) expect(within(inputs, client).length).toBeGreaterThan(0) expect(within(inputs, core).length).toBeGreaterThan(0) expect(within(inputs, server).length).toBeGreaterThan(0) } -}) - -async function bundleInputs(specifier: string) { - const temporary = await mkdtemp(join(import.meta.dir, ".import-boundary-")) - const entrypoint = join(temporary, "index.ts") - const metafile = join(temporary, "meta.json") - try { - await Bun.write(entrypoint, `export * from ${JSON.stringify(specifier)}`) - const child = Bun.spawn( - [ - process.execPath, - "build", - entrypoint, - "--target=bun", - "--format=esm", - "--packages=bundle", - `--metafile=${metafile}`, - `--outdir=${join(temporary, "out")}`, - ], - { cwd: directory, stdout: "pipe", stderr: "pipe" }, - ) - const [exitCode, stdout, stderr] = await Promise.all([ - child.exited, - new Response(child.stdout).text(), - new Response(child.stderr).text(), - ]) - if (exitCode !== 0) throw new Error(stdout + stderr) - const metadata = await Bun.file(metafile).json() - return Object.keys(metadata.inputs).map((input) => resolve(directory, input)) - } finally { - await rm(temporary, { recursive: true, force: true }) - } -} +}, 15_000) function within(inputs: ReadonlyArray, directory: string) { const prefix = directory.endsWith(sep) ? directory : directory + sep diff --git a/packages/session-ui/component-tests/session-message-projection.spec.ts b/packages/session-ui/component-tests/session-message-projection.spec.ts index cc1ca0535f6..e273f2da61a 100644 --- a/packages/session-ui/component-tests/session-message-projection.spec.ts +++ b/packages/session-ui/component-tests/session-message-projection.spec.ts @@ -169,7 +169,8 @@ story( await page.mouse.move(0, 0) // Kobalte drops the expanded state a task before it returns focus to the trigger, so record every frame from the - // click until well after the menu has gone rather than the settled state. + // click until well after the menu has gone rather than the settled state. The first sample is taken now: the click + // can land and close the menu before the next frame. const frames = await message.evaluateHandle((element) => { const slots = ["user-message-copy-wrapper", "user-message-menu"] const samples = slots.map((): number[] => []) @@ -189,7 +190,7 @@ story( resolve(samples) } - requestAnimationFrame(tick) + tick() }) return { done } diff --git a/packages/tui/test/session-media-refs.test.tsx b/packages/tui/test/session-media-refs.test.tsx index 3efba502a40..549ac9ccdee 100644 --- a/packages/tui/test/session-media-refs.test.tsx +++ b/packages/tui/test/session-media-refs.test.tsx @@ -4,6 +4,7 @@ import { directory, json } from "./fixture/tui-client" import { takeDraft } from "../src/component/prompt/draft-stash" import type { PromptInfo } from "../src/prompt/history" import { copyPlugin } from "./fixture/fixture" +import { waitForHighlightedFrame } from "./fixture/frame" const hash = "e".repeat(64) const png = Buffer.from( @@ -117,7 +118,7 @@ async function openSession(server: { inbox?: unknown[]; plugins?: string[]; resp return response }, }) - await setup.waitForFrame((frame) => frame.includes("Looked at it")) + await waitForHighlightedFrame(setup, (frame) => frame.includes("Looked at it")) return Object.assign(setup, { calls, capabilities }) } @@ -303,7 +304,7 @@ async function leaveAndReturn(app: App) { app.mockInput.pressEnter() await app.waitForFrame((frame) => frame.includes("Sessions") && frame.includes("Media refs")) app.mockInput.pressEnter() - await app.waitForFrame((frame) => frame.includes("Looked at it")) + await waitForHighlightedFrame(app, (frame) => frame.includes("Looked at it")) } for (const queued of [false, true]) { diff --git a/packages/ui/src/forms/search-list/search-list.tsx b/packages/ui/src/forms/search-list/search-list.tsx index 027e775d615..81cd4e17647 100644 --- a/packages/ui/src/forms/search-list/search-list.tsx +++ b/packages/ui/src/forms/search-list/search-list.tsx @@ -187,8 +187,9 @@ export function SearchList(props: { createEffect(() => props.onActive?.(typeahead.activeItem())) // A new query starts from the top. Results that arrive later for the same query bring a chosen row back into view, - // but leave the list where the wheel put it while the first row is still the default. + // but leave the list where the wheel put it while the first row is still the default or the pointer took the row. let revealed = props.query + let pointed: string | undefined createEffect( on( @@ -197,7 +198,7 @@ export function SearchList(props: { const fresh = props.query !== revealed revealed = props.query - if (!fresh && typeahead.activeItem() === all[0]) return + if (!fresh && (typeahead.activeItem() === all[0] || activeKey() === pointed)) return const frame = requestAnimationFrame(reveal) onCleanup(() => cancelAnimationFrame(frame)) }, @@ -205,7 +206,12 @@ export function SearchList(props: { ), ) - props.ref?.({ active: typeahead.activeItem, setActive: typeahead.setActive }) + const choose = (key: string | undefined) => { + pointed = undefined + typeahead.setActive(key) + } + + props.ref?.({ active: typeahead.activeItem, setActive: choose }) const onKeyDown = (event: KeyboardEvent) => { if (event.isComposing) return @@ -232,7 +238,7 @@ export function SearchList(props: { const target = all[step(from)] if (target === undefined) return - typeahead.setActive(props.key(target)) + choose(props.key(target)) reveal() } @@ -254,7 +260,7 @@ export function SearchList(props: { }, onInput: (event) => { // A new query starts again from its first row. - typeahead.setActive(undefined) + choose(undefined) props.onQuery(event.currentTarget.value) }, onKeyDown, @@ -274,7 +280,9 @@ export function SearchList(props: { }, onMouseMove: (event) => { // A static cursor must not take the active row while the keyboard scrolls rows beneath it. - if (event.movementX !== 0 || event.movementY !== 0) typeahead.setActive(key) + if (event.movementX === 0 && event.movementY === 0) return + pointed = key + typeahead.setActive(key) }, // Focus stays in the field. onMouseDown: (event) => event.preventDefault(),