diff --git a/.gitattributes b/.gitattributes index 9f43f6095a..d575062b44 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,3 +3,6 @@ packages/core/src/database/migration.gen.ts linguist-generated packages/core/src/models-dev/snapshot.txt linguist-generated packages/core/src/**/*.txt text eol=lf packages/httpapi-codegen/test/generated/*.ts text eol=lf + +# Preserve the audited bytes of the vendored CookieJar bundle on Windows. +packages/desktop/vendor/cm-ae/** -text diff --git a/.github/actions/setup-bun/action.yml b/.github/actions/setup-bun/action.yml index 013b334b56..6f250e2d99 100644 --- a/.github/actions/setup-bun/action.yml +++ b/.github/actions/setup-bun/action.yml @@ -20,7 +20,7 @@ runs: - name: Setup Node uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: - node-version: "24" + node-version: "24.15" - name: Get baseline download URL id: bun-url @@ -88,6 +88,7 @@ runs: shell: bash env: CM_WPP_SSH_KEY: ${{ inputs.wpp-ssh-key }} + GH_TOKEN: ${{ github.token }} run: | if [ -z "$CM_WPP_SSH_KEY" ]; then echo "::error::CM_WPP_SSH_KEY with read access to trmosala/CM-WPP-Bits is required." @@ -95,7 +96,7 @@ runs: fi umask 077 printf '%s\n' "$CM_WPP_SSH_KEY" > "$RUNNER_TEMP/cm-wpp-key" - curl --fail --silent --show-error https://api.github.com/meta | node -e ' + curl --fail --silent --show-error --header "Authorization: Bearer $GH_TOKEN" https://api.github.com/meta | node -e ' let data = "" process.stdin.on("data", chunk => data += chunk) process.stdin.on("end", () => { diff --git a/.github/workflows/cookiemonster-desktop.yml b/.github/workflows/cookiemonster-desktop.yml index 36f1875251..2277396aa6 100644 --- a/.github/workflows/cookiemonster-desktop.yml +++ b/.github/workflows/cookiemonster-desktop.yml @@ -87,6 +87,12 @@ jobs: OPENCODE_CHANNEL: dev run: bun test --preload ./test/preload.ts --timeout 20000 electron-builder.config.test.ts src/main/macos-user-install.test.ts + - name: Verify pinned WPP backend and host contracts + timeout-minutes: 3 + run: | + bun run --cwd packages/desktop/wpp/node_modules/@cookiemonster/wpp test + bun run --cwd packages/desktop test:wpp + - name: Import Developer ID certificate uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 # v2.0.0 with: @@ -148,6 +154,17 @@ jobs: cd packages/desktop/dist shasum -a 256 cookiemonster-mac-arm64.dmg > SHA256SUMS.txt + - name: Verify packaged macOS activation with a hidden worker + timeout-minutes: 3 + run: | + mount="$RUNNER_TEMP/cm-activation-mount" + mkdir "$mount" + hdiutil attach packages/desktop/dist/cookiemonster-mac-arm64.dmg -readonly -nobrowse -mountpoint "$mount" + trap 'hdiutil detach "$mount"' EXIT + mkdir "$RUNNER_TEMP/cm-activation" + ditto "$mount/CookieMonster.app" "$RUNNER_TEMP/cm-activation/CookieMonster.app" + bun packages/desktop/scripts/check-mac-activation.ts "$RUNNER_TEMP/cm-activation/CookieMonster.app" + - name: Upload verified installer if: ${{ !inputs.publish }} timeout-minutes: 3 diff --git a/.github/workflows/pr-management.yml b/.github/workflows/pr-management.yml index b6aa4e589d..ecb1c7b72d 100644 --- a/.github/workflows/pr-management.yml +++ b/.github/workflows/pr-management.yml @@ -6,7 +6,7 @@ on: jobs: check-duplicates: - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: ubuntu-24.04 permissions: contents: read pull-requests: write diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d004db4658..b15c1ae2d2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -23,7 +23,7 @@ env: jobs: affected: name: affected packages - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: ubuntu-24.04 outputs: app: ${{ steps.packages.outputs.app }} steps: @@ -58,9 +58,9 @@ jobs: matrix: settings: - name: linux - host: blacksmith-4vcpu-ubuntu-2404 + host: ubuntu-24.04 - name: windows - host: blacksmith-4vcpu-windows-2025 + host: windows-2025 runs-on: ${{ matrix.settings.host }} defaults: run: @@ -84,6 +84,23 @@ jobs: if: runner.os == 'Linux' run: bun run test:effect-simplification-rules + - name: Install Electron for desktop runtime tests + working-directory: packages/desktop + run: node -e "require(require.resolve('electron/install.js'))" + + - name: Install Chromium for browser unit tests + working-directory: packages/app + run: bunx playwright install --with-deps chromium + + - name: Install ripgrep for offline core tests + run: | + if [ "$RUNNER_OS" = "Linux" ]; then + sudo apt-get update + sudo apt-get install -y ripgrep + else + choco install ripgrep --yes --no-progress + fi + - name: Check Effect simplifications if: runner.os == 'Linux' run: bun run lint:effect-simplifications @@ -102,15 +119,23 @@ jobs: turbo-${{ runner.os }}-${{ hashFiles('turbo.json', '**/package.json') }}- turbo-${{ runner.os }}- + - name: Initialize installed PowerShell runtime + if: runner.os == 'Linux' + run: | + # Cold PowerShell startup can exceed a unit test's five-second budget. + if command -v pwsh > /dev/null; then + pwsh -NoLogo -NoProfile -NonInteractive -Command "Write-Output 'PowerShell ready'" + fi + - name: Run unit tests timeout-minutes: 20 run: | - # The runners have four vCPUs, and each Bun test process performs its own concurrent work. + # Each package creates concurrent work; serialize packages to bound hosted process pressure. if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then - GITHUB_ACTIONS=false bun turbo test --concurrency=3 + GITHUB_ACTIONS=false bun turbo test --concurrency=1 exit 0 fi - GITHUB_ACTIONS=false bun turbo test --affected --concurrency=3 + GITHUB_ACTIONS=false bun turbo test --affected --concurrency=1 env: OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER: ${{ runner.os == 'Windows' && 'true' || 'false' }} TURBO_SCM_BASE: ${{ github.event_name == 'pull_request' && format('{0}^1', github.sha) || github.event.before }} @@ -135,7 +160,7 @@ jobs: TURBO_SCM_HEAD: ${{ github.sha }} - name: Verify compiled service lifecycle - if: always() + if: ${{ !cancelled() }} timeout-minutes: 10 working-directory: packages/cli env: @@ -145,13 +170,13 @@ jobs: bun run script/service-smoke.ts - name: Setup Node build runtime - if: always() + if: ${{ !cancelled() }} uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: "26.4.0" - name: Verify Node build - if: always() + if: ${{ !cancelled() }} timeout-minutes: 15 working-directory: packages/cli env: @@ -178,9 +203,9 @@ jobs: matrix: settings: - name: linux - host: blacksmith-4vcpu-ubuntu-2404 + host: ubuntu-24.04 - name: windows - host: blacksmith-4vcpu-windows-2025 + host: windows-2025 runs-on: ${{ matrix.settings.host }} env: E2E_ENABLED: ${{ needs.affected.outputs.app == 'true' && github.ref_name != 'dev' && github.head_ref != 'dev' }} diff --git a/bun.lock b/bun.lock index 1b8e909115..090a64ef09 100644 --- a/bun.lock +++ b/bun.lock @@ -1107,6 +1107,7 @@ "solid-js@1.9.15": "patches/solid-js@1.9.15.patch", "vite@8.2.2": "patches/vite@8.2.2.patch", "@ff-labs/fff-bun@0.10.5": "patches/@ff-labs%2Ffff-bun@0.10.5.patch", + "@corvu/drawer@0.2.4": "patches/@corvu%2Fdrawer@0.2.4.patch", "@dnd-kit/dom@0.5.0": "patches/@dnd-kit%2Fdom@0.5.0.patch", "@ai-sdk/openai-compatible@2.0.41": "patches/@ai-sdk%2Fopenai-compatible@2.0.41.patch", }, diff --git a/package.json b/package.json index c703dc6f77..2a841c987c 100644 --- a/package.json +++ b/package.json @@ -184,6 +184,7 @@ "@ff-labs/fff-bun@0.10.5": "patches/@ff-labs%2Ffff-bun@0.10.5.patch", "ghostty-web@github:anomalyco/ghostty-web#83c0a07": "patches/ghostty-web@0.3.0.patch", "vite@8.2.2": "patches/vite@8.2.2.patch", - "@modelcontextprotocol/client@2.0.0": "patches/@modelcontextprotocol%2Fclient@2.0.0.patch" + "@modelcontextprotocol/client@2.0.0": "patches/@modelcontextprotocol%2Fclient@2.0.0.patch", + "@corvu/drawer@0.2.4": "patches/@corvu%2Fdrawer@0.2.4.patch" } } diff --git a/packages/app/component-tests/composer.spec.ts b/packages/app/component-tests/composer.spec.ts index a434d07c23..57113c7a7a 100644 --- a/packages/app/component-tests/composer.spec.ts +++ b/packages/app/component-tests/composer.spec.ts @@ -96,13 +96,17 @@ for (const direction of ["ltr", "rtl"]) { ).toBeLessThan(1) await page.keyboard.press("Enter") // Below the mobile breakpoint the variant picker opens in a bottom drawer instead of a menu. - await expect( + + const option = width < 768 ? page .getByRole("dialog", { name: "Choose model variant", exact: true }) .getByRole("button", { name: "high", exact: true }) - : page.getByRole("menuitemradio", { name: "high", exact: true }), - ).toBeVisible() + : page.getByRole("menuitemradio", { name: "high", exact: true }) + + await expect(option).toBeVisible() + // The mobile drawer starts below the viewport; wait until its options are presented before dismissal. + await expect(option).toBeInViewport({ ratio: 1 }) await page.keyboard.press("Escape") await expect(variant).toBeFocused() await expect(submit).toBeInViewport() @@ -110,7 +114,8 @@ for (const direction of ["ltr", "rtl"]) { await add.click() await expect(page.getByRole("menuitem", { name: "Images and files" })).toBeVisible() await page.keyboard.press("Escape") - expect(await add.boundingBox()).toEqual(fixedAdd) + // Menu dismissal restores focus and scroll position after its closing animation. + await expect.poll(() => add.boundingBox()).toEqual(fixedAdd) } if (alternate !== "none") { @@ -123,6 +128,36 @@ for (const direction of ["ltr", "rtl"]) { } } +for (const motion of ["no-preference", "reduce"] as const) { + story( + `returns focus when the mobile variant drawer closes before its opening paint (${motion})`, + async ({ mount, page }) => { + await page.setViewportSize({ width: 360, height: 720 }) + await page.emulateMedia({ reducedMotion: motion }) + const component = await mount("opencode-composer-flow--toolbar-overflow") + const variant = component.getByRole("button", { name: "Choose model variant" }) + await expect(variant).toBeVisible() + await page.clock.install({ time: 0 }) + await page.clock.pauseAt(1000) + await variant.focus() + await page.keyboard.press("Enter") + const drawer = page.getByRole("dialog", { name: "Choose model variant", exact: true }) + await expect(drawer.getByRole("button", { name: "high", exact: true })).toBeVisible() + // No opening animation-frame callback has run when Escape arrives. + await page.keyboard.press("Escape") + await page.clock.runFor(1000) + await expect(drawer).toBeHidden() + await expect(variant).toBeFocused() + await page.clock.resume() + await page.keyboard.press("Enter") + await expect(drawer.getByRole("button", { name: "high", exact: true })).toBeInViewport({ ratio: 1 }) + await page.keyboard.press("Escape") + await expect(drawer).toBeHidden() + await expect(variant).toBeFocused() + }, + ) +} + story("does not mask or pad controls when they fit", async ({ mount }) => { const component = await mount("opencode-composer-flow--model-and-variant") const controls = component.locator('[data-slot="composer-controls"]') diff --git a/packages/app/e2e/regression/composer.spec.ts b/packages/app/e2e/regression/composer.spec.ts index 87fe50661d..652fae7188 100644 --- a/packages/app/e2e/regression/composer.spec.ts +++ b/packages/app/e2e/regression/composer.spec.ts @@ -455,7 +455,7 @@ test("marks a Console provider with its workspace only when it is also connected await expect(menu.getByText(/Anomaly \//)).toHaveCount(0) }) -test("shows thinking on hover or a non-default selection while preserving keyboard access", async ({ page }) => { +test("keeps the effort picker visible while preserving selection and keyboard access", async ({ page }) => { const { editor: input } = await openSession(page, { name: "ComposerThinking", provider: provider({ id: "thinking-model", name: "Thinking Model", variants: { high: {} } }), @@ -467,13 +467,13 @@ test("shows thinking on hover or a non-default selection while preserving keyboa await page.mouse.move(0, 0) await expect(control).toHaveText("default") - await expect(control).toHaveCSS("opacity", "0") - await expect(control).toHaveCSS("pointer-events", "none") + await expect(control).toHaveCSS("opacity", "1") + await expect(control).toHaveCSS("pointer-events", "auto") await input.hover() await expect(control).toHaveCSS("opacity", "1") - // The menu keeps the control visible after the pointer leaves. + // The control stays visible while its menu is open. await control.click() await expect(option("high")).toBeVisible() await page.mouse.move(0, 0) @@ -491,7 +491,7 @@ test("shows thinking on hover or a non-default selection while preserving keyboa await input.click() await page.mouse.move(0, 0) await expect(control).toHaveText("default") - await expect(control).toHaveCSS("opacity", "0") + await expect(control).toHaveCSS("opacity", "1") // The single-agent fixture has only Add and Model before the thinking trigger. await page.keyboard.press("Tab") @@ -507,5 +507,5 @@ test("shows thinking on hover or a non-default selection while preserving keyboa await page.keyboard.press("Escape") await expect(control).toBeFocused() await page.keyboard.press("Tab") - await expect(control).toHaveCSS("opacity", "0") + await expect(control).toHaveCSS("opacity", "1") }) diff --git a/packages/app/e2e/regression/side-panels.spec.ts b/packages/app/e2e/regression/side-panels.spec.ts index a41039333b..3daa8e95dd 100644 --- a/packages/app/e2e/regression/side-panels.spec.ts +++ b/packages/app/e2e/regression/side-panels.spec.ts @@ -1,4 +1,4 @@ -import { expect, test, type Locator, type Page } from "@playwright/test" +import { expect, test, type CDPSession, type Locator, type Page } from "@playwright/test" import { tabKey } from "../utils/app" import { fileDiff, openSession } from "../utils/workspace" import { expectSessionTitle } from "../utils/waits" @@ -96,6 +96,8 @@ test("review and terminal follow the session tab and stay mounted", async ({ pag }) test("terminal stacks under review by default and spans the bottom when configured", async ({ page }) => { + const clock = await page.context().newCDPSession(page) + await clock.send("Animation.enable") await page.setViewportSize({ width: 1400, height: 900 }) // A large nested branch diff; its first file is the sentinel that proves the virtualized tree stays mounted. @@ -150,10 +152,10 @@ test("terminal stacks under review by default and spans the bottom when configur // Closing review mid-motion: the terminal grows upward with its bottom fixed and its content top-anchored. const stacked = await stackGeometry(page) - await holdTransitions(page) + await holdTransitions(page, clock) await toggle.click() const closing = await stackGeometry(page, 0.5) - await releaseTransitions(page) + await releaseTransitions(page, clock) await expect(reviewPanel).toBeHidden() await expect(terminalPanel).toBeVisible() const alone = await stackGeometry(page) @@ -171,10 +173,10 @@ test("terminal stacks under review by default and spans the bottom when configur // Hiding the terminal mid-motion: both surfaces fill their regions and the clipped terminal keeps its size. const open = await stackGeometry(page) - await holdTransitions(page) + await holdTransitions(page, clock) await page.keyboard.press("Control+Backquote") const hiding = await stackGeometry(page, 0.5) - await releaseTransitions(page) + await releaseTransitions(page, clock) await expect(terminalPanel).toBeHidden() expect(hiding.moving).toEqual(expect.arrayContaining(["session-side-region", "session-side-terminal-region"])) expect(hiding.terminalRegion).toBeLessThan(open.terminalRegion - 1) @@ -319,8 +321,12 @@ async function expectTreeSentinel(page: Page) { } // Pauses each CSS transition as it starts, so a real toggle can be measured mid-motion. -function holdTransitions(page: Page) { +async function holdTransitions(page: Page, clock: CDPSession) { + // Under CPU contention, transitionrun can arrive after the transition finished; stop compositor time first. + await clock.send("Animation.setPlaybackRate", { playbackRate: 0 }) + return page.evaluate(() => { + // SAFETY: This fixture owns the optional e2eHold state on this page. const host = window as Window & { e2eHold?: { active: boolean } } if (!host.e2eHold) { @@ -339,18 +345,22 @@ function holdTransitions(page: Page) { }) } -function releaseTransitions(page: Page) { - return page.evaluate(() => { - ;(window as Window & { e2eHold?: { active: boolean } }).e2eHold!.active = false +async function releaseTransitions(page: Page, clock: CDPSession) { + await page.evaluate(() => { + // SAFETY: holdTransitions created this page-owned state before release. + const host = window as Window & { e2eHold?: { active: boolean } } + host.e2eHold!.active = false document .getAnimations() .filter((item) => item instanceof CSSTransition && item.playState === "paused") .forEach((item) => item.finish()) }) + await clock.send("Animation.setPlaybackRate", { playbackRate: 1 }) } // With `progress`, waits for the held region height transitions and seeks every held transition to that point first. async function stackGeometry(page: Page, progress?: number) { + // SAFETY: These filtered CSS transitions have keyframe effects targeting the owning DOM elements. const held = () => page.evaluate(() => document @@ -371,6 +381,7 @@ async function stackGeometry(page: Page, progress?: number) { .getAnimations() .filter((item): item is CSSTransition => item instanceof CSSTransition && item.playState === "paused") + // SAFETY: CSS transitions on these regions have keyframe effects targeting DOM elements. const region = transitions.find( (item) => ((item.effect as KeyframeEffect).target as Element).getAttribute("data-slot") === "session-side-region", ) @@ -387,6 +398,7 @@ async function stackGeometry(page: Page, progress?: number) { const terminal = box("#terminal-panel")! const content = box('[data-slot="terminal-panel-content"]')! + // SAFETY: The filtered CSS transitions target DOM elements, as in the region lookup above. return { moving: transitions.map((item) => ((item.effect as KeyframeEffect).target as Element).getAttribute("data-slot")), terminalRegion: terminalRegion.height, @@ -414,6 +426,7 @@ async function expectTerminalControlsAligned(terminal: Locator, toggle: Locator) const centers = await Promise.all( [terminal.getByRole("button", { name: "New terminal", exact: true }), toggle].map((button) => button.locator("svg").evaluate((element) => { + // SAFETY: The locator selects svg elements, whose geometry is read below. const svg = element as SVGSVGElement const path = svg.getBBox() diff --git a/packages/app/e2e/regression/tabs.spec.ts b/packages/app/e2e/regression/tabs.spec.ts index f72b093331..a408aa4c22 100644 --- a/packages/app/e2e/regression/tabs.spec.ts +++ b/packages/app/e2e/regression/tabs.spec.ts @@ -692,6 +692,44 @@ test("inactive tabs load attention and inbox, but read the transcript only on se expect(errors).toEqual([]) }) +test("closing a tab releases its transcript, and reopening it reads the transcript again", async ({ page }) => { + const reads: string[] = [] + const errors: string[] = [] + page.on("pageerror", (error) => errors.push(error.message)) + page.on("request", (request) => { + if (request.method() === "GET") reads.push(new URL(request.url()).pathname) + }) + + const history = (id: string) => + page.locator(`[data-timeline-row="UserMessage"][data-message-id="msg_${id}_history"]`) + + await openSession(page, { + name: "TabRetention", + sessions: [a, b], + pageMessages: (id) => ({ + items: [{ id: `msg_${id}_history`, type: "user", text: `History of ${id}`, time: { created: 1 } }], + }), + }) + await expect(history(a.id)).toContainText(`History of ${a.id}`) + + await page.locator(`[data-titlebar-tab-link][href="${sessionHref(b.id)}"]`).click() + await expect(history(b.id)).toContainText(`History of ${b.id}`) + await page.keyboard.press("Control+w") + await expect(page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(b.id)}"])`)).toHaveCount(0) + await expectSessionTitle(page, a.title) + + // A release has no visible signal, so wait past the retention delay. The open tab keeps its transcript. + await page.waitForTimeout(2_000) + await expect(history(a.id)).toContainText(`History of ${a.id}`) + + await page.keyboard.press("Control+Shift+T") + await expectSessionTitle(page, b.title) + await expect(history(b.id)).toContainText(`History of ${b.id}`) + await expect.poll(() => reads.filter((path) => path === `/api/session/${b.id}/message`).length).toBe(2) + expect(reads.filter((path) => path === `/api/session/${a.id}/message`)).toHaveLength(1) + expect(errors).toEqual([]) +}) + test("five loaded workspace tabs stay rendered and reactive through repeated switches", async ({ page }) => { await page.setViewportSize({ width: 1440, height: 900 }) diff --git a/packages/app/e2e/regression/whats-new.spec.ts b/packages/app/e2e/regression/whats-new.spec.ts index 9e91bb5170..f08f5e367a 100644 --- a/packages/app/e2e/regression/whats-new.spec.ts +++ b/packages/app/e2e/regression/whats-new.spec.ts @@ -219,7 +219,10 @@ async function serveChangelog(page: Page, body: typeof changelog | typeof cliOnl async function start(page: Page, seed: SeedInput) { await mockWorkspace(page, { name: "Whats New", sessions: [], seed }) await page.goto("/") - await expectAppVisible(page.getByRole("button", { name: "Settings", exact: true })) + // The startup dialog may already hide the shell from accessibility queries. + await expectAppVisible( + page.getByRole("button", { name: "Settings", exact: true, includeHidden: true }).filter({ visible: true }), + ) } function stored(page: Page, key: string) { diff --git a/packages/app/src/cookiemonster/browser/browser-site.tsx b/packages/app/src/cookiemonster/browser/browser-site.tsx index 47fcf42fba..69eb46b618 100644 --- a/packages/app/src/cookiemonster/browser/browser-site.tsx +++ b/packages/app/src/cookiemonster/browser/browser-site.tsx @@ -8,6 +8,8 @@ export function BrowserSite(props: { tab: BrowserTab profile: BrowserProfile busy: boolean + // SAFETY: Command results are opaque except the documented false inspection outcome checked below. + // oxlint-disable-next-line anti-slop/no-unknown-returns command(value: BrowserCommand): Promise }) { const language = useLanguage() @@ -92,6 +94,7 @@ export function BrowserSite(props: { void props.command({ op: "site-permission", origin: origin(), + // SAFETY: This owned select offers only the three BrowserPermission values below. [device]: event.currentTarget.value as BrowserPermission, }) } @@ -114,6 +117,7 @@ export function BrowserSite(props: { void props.command({ op: "site-permission", origin: origin(), + // SAFETY: This owned select offers only the three BrowserPermission values below. [permission]: event.currentTarget.value as BrowserPermission, }) } @@ -158,12 +162,18 @@ export function BrowserSite(props: {
{language.t("browser.site.data")} + +

{language.t("browser.site.inspectFailed")}

+ +

{language.t("browser.site.stale")}

+
+
- {language.t(inspectionFailed() ? "browser.site.inspectFailed" : "browser.site.inspecting")} -

+ +

{language.t("browser.site.inspecting")}

+
} > {(inspection) => ( diff --git a/packages/app/src/cookiemonster/browser/en.ts b/packages/app/src/cookiemonster/browser/en.ts index 7ffa2c7ec7..0e071f61a9 100644 --- a/packages/app/src/cookiemonster/browser/en.ts +++ b/packages/app/src/cookiemonster/browser/en.ts @@ -106,6 +106,7 @@ export const browser = { "browser.site.data": "Site data", "browser.site.inspecting": "Inspecting Chromium site data…", "browser.site.inspectFailed": "Could not inspect this site. Try Refresh inspection.", + "browser.site.stale": "Showing previous inspection results. Site data may have changed.", "browser.site.cookies": "Cookies matching this page: {{count}}", "browser.site.usage": "Origin storage reported by Chromium: {{size}}", "browser.site.storage": "Stored categories: {{types}}", diff --git a/packages/app/src/runtime/i18n/desktop-native.ts b/packages/app/src/runtime/i18n/desktop-native.ts index 7fb1d7d49e..40881b1148 100644 --- a/packages/app/src/runtime/i18n/desktop-native.ts +++ b/packages/app/src/runtime/i18n/desktop-native.ts @@ -306,6 +306,9 @@ export const DESKTOP_NATIVE_ENGLISH = { "desktop.picker.error.notSelected": "File was not selected by the picker", "desktop.picker.error.sizeLimit": "Selected attachments exceed the {{limit}} MB limit", + + "desktop.openWith.error.appNotAllowed": "Application is not allowed: {{app}}", + "desktop.openWith.error.notAbsolute": "Open target must be an absolute path", } as const export type DesktopNativeKey = keyof typeof DESKTOP_NATIVE_ENGLISH @@ -314,6 +317,7 @@ export type DesktopNativeMessages = Record export type DesktopNativeBundle = { locale: DesktopNativeLocale; messages: DesktopNativeMessages } +// SAFETY: DesktopNativeKey is exactly the key union of this owned literal. export const DESKTOP_NATIVE_KEYS = Object.keys(DESKTOP_NATIVE_ENGLISH) as DesktopNativeKey[] export const DESKTOP_NATIVE_MAX_PAYLOAD_BYTES = 64 * 1024 @@ -324,10 +328,13 @@ export function createDesktopNativeBundle( ): DesktopNativeBundle { return { locale, + // SAFETY: Every declared key occurs once and the translator returns a string for each. messages: Object.fromEntries(DESKTOP_NATIVE_KEYS.map((key) => [key, translate(key)])) as DesktopNativeMessages, } } +// SAFETY: This IPC decoder checks payload size, locale, exact keys and string values before returning a bundle. +/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type */ export function parseDesktopNativeBundle(value: unknown): DesktopNativeBundle | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) return undefined @@ -337,11 +344,13 @@ export function parseDesktopNativeBundle(value: unknown): DesktopNativeBundle | return undefined } + // SAFETY: The guard above establishes an object; its fields remain unknown until checked below. const bundle = value as { locale?: unknown; messages?: unknown } if (!DESKTOP_NATIVE_LOCALES.some((locale) => locale === bundle.locale)) return undefined if (!bundle.messages || typeof bundle.messages !== "object" || Array.isArray(bundle.messages)) return undefined + // SAFETY: Messages is a non-array object; this boundary checks every unknown member below. const messages = bundle.messages as Record const keys = Object.keys(messages) @@ -351,8 +360,10 @@ export function parseDesktopNativeBundle(value: unknown): DesktopNativeBundle | if (!keys.every((key) => key in DESKTOP_NATIVE_ENGLISH)) return undefined + // SAFETY: The bounded payload now has a supported locale, the exact native keys and only string values. return bundle as DesktopNativeBundle } +/* oxlint-enable anti-slop/no-unknown-parameters, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type */ export function formatDesktopNativeMessage(message: string, params?: Record) { if (!params) return message diff --git a/packages/app/src/runtime/server/runtime.tsx b/packages/app/src/runtime/server/runtime.tsx index 13e686e8c3..a7560b83f2 100644 --- a/packages/app/src/runtime/server/runtime.tsx +++ b/packages/app/src/runtime/server/runtime.tsx @@ -1,6 +1,20 @@ import { createSimpleContext } from "@opencode/ui/context" -import { Accessor, batch, createEffect, createMemo, createResource, createRoot, getOwner, untrack } from "solid-js" +import { + Accessor, + batch, + createEffect, + createMemo, + createResource, + createRoot, + getOwner, + untrack, + useTransition, +} from "solid-js" +import { useLocation } from "@solidjs/router" import { createServerProjects, RECENTLY_CLOSED_DISPLAY_LIMIT, ServerConnection, useServers } from "./registry" +import { createSessionRetention } from "./session-retention" +import { sessionHref } from "@/shell/routes/session" +import { useTabs } from "@/shell/tabs/tabs" import { pathKey } from "@/workspaces/path-key" import { useServerHealth } from "@/runtime/server/health" import { createServerSdkContext } from "./client" @@ -198,6 +212,32 @@ function createServerController( createPermissionAutoApprover({ sdk, data }) const notification = createServerNotificationState({ sdk, data, key: connKey, coordinator: notificationCoordinator }) + const tabs = useTabs() + const location = useLocation() + // Parsed here because the shared route parser throws on routes it does not recognise. + const routes = sessionHref(connKey, "") + createSessionRetention({ + session: data.session, + ready: tabs.ready, + visible: () => { + const routed = location.pathname.startsWith(routes) + ? location.pathname.slice(routes.length).split("/")[0] + : undefined + + return [ + ...(routed ? [routed] : []), + ...tabs.store.flatMap((tab) => + tab.type === "session" && tab.server === connKey + ? [tab.sessionId, tab.routeSessionId, tab.routeParentId].flatMap((id) => (id ? [id] : [])) + : [], + ), + ] + }, + navigating: useTransition()[0], + // Covers an open path whose transcript read lands before the transition adding its tab commits. + delay: 1_000, + }) + function enrich(project: { worktree: string; expanded: boolean }) { const [childStore] = sync.child(project.worktree, { bootstrap: false }) const projectID = childStore.project diff --git a/packages/app/src/runtime/server/session-retention.ts b/packages/app/src/runtime/server/session-retention.ts new file mode 100644 index 0000000000..38b22f7d64 --- /dev/null +++ b/packages/app/src/runtime/server/session-retention.ts @@ -0,0 +1,64 @@ +import { createEffect, onCleanup, type Accessor } from "solid-js" +import type { Data } from "@opencode/client/solid" + +type Session = Pick + +/** + * Releases the cached transcripts of session families that no open tab, session route, running work or attention + * request keeps. A family is released once it has stayed unkept for `delay` with no transition pending, since an open + * path can read a transcript before the transition that adds its tab or route commits. Late reads and events that + * bring rows back to a released family start a new delay, so they cannot keep it cached. + */ +export function createSessionRetention(input: { + session: Session + /** Persisted tabs have loaded. */ + ready: Accessor + /** Sessions shown by open tabs or the current route. */ + visible: Accessor + navigating: Accessor + delay: number +}) { + const timers = new Map>() + onCleanup(() => timers.forEach((timer) => clearTimeout(timer))) + const unkept = () => new Set(input.ready() && !input.navigating() ? unkeptRoots(input.session, input.visible()) : []) + + const release = (root: string) => { + timers.set( + root, + setTimeout(() => { + timers.delete(root) + input.session.evict(root) + + // Eviction keeps unacknowledged submissions and sessions still being created, and settling them need not + // change the cached set this policy tracks. Retry while the family stays unkept and cached. + if (!timers.has(root) && unkept().has(root)) release(root) + }, input.delay), + ) + } + + createEffect(() => { + const roots = unkept() + timers.forEach((timer, root) => { + if (roots.has(root)) return + clearTimeout(timer) + timers.delete(root) + }) + // A family that keeps receiving rows still releases at its first deadline. + roots.forEach((root) => { + if (!timers.has(root)) release(root) + }) + }) +} + +function unkeptRoots(session: Session, visible: readonly string[]) { + const kept = new Set( + [...visible, ...session.active(), ...session.permission.sessions(), ...session.form.sessions()].map((id) => + session.root(id), + ), + ) + + return session + .cached() + .map((id) => session.root(id)) + .filter((root) => !kept.has(root)) +} diff --git a/packages/app/src/session/session-screen.stories.tsx b/packages/app/src/session/session-screen.stories.tsx index 9b47241bec..0c5d746a9b 100644 --- a/packages/app/src/session/session-screen.stories.tsx +++ b/packages/app/src/session/session-screen.stories.tsx @@ -15,6 +15,8 @@ import { terminalPassedDocument, } from "@opencode/session-ui/storybook" import { SessionPreview } from "./story-model" +import { SettingsProvider } from "@/settings/model" +import type { JSX } from "solid-js" const description = "opencode · modular-session-ui" @@ -51,6 +53,13 @@ export default { title: "OpenCode/Session/Complete workspace", id: "app-current-session-surface", component: SessionPreview, + decorators: [ + (Story: () => JSX.Element) => ( + + + + ), + ], parameters: { layout: "fullscreen", docs: { diff --git a/packages/app/src/session/timeline/observe-element-offset.test.ts b/packages/app/src/session/timeline/observe-element-offset.test.ts index 2a2eea1449..a770e75008 100644 --- a/packages/app/src/session/timeline/observe-element-offset.test.ts +++ b/packages/app/src/session/timeline/observe-element-offset.test.ts @@ -8,6 +8,8 @@ test("restores a view observed before its first attachment", async () => { const mutations = controlledMutations(targetWindow) const viewport = targetWindow.document.createElement("div") + // SAFETY: This observer and TanStack's offset delegate read only the window, element, offset, and listed options. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Happy DOM supplies the browser contract used by this focused fixture. const instance = { scrollElement: viewport, targetWindow, @@ -45,6 +47,8 @@ test("reports a divergent native offset once and ignores equal offsets and unrel route.append(viewport) targetWindow.document.body.append(route) + // SAFETY: This observer and TanStack's offset delegate read only the window, element, offset, and listed options. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Happy DOM supplies the browser contract used by this focused fixture. const instance = { scrollElement: viewport, targetWindow, @@ -93,6 +97,8 @@ test("keeps checking until stale reset-delay callbacks can no longer win", async route.append(viewport) targetWindow.document.body.append(route) + // SAFETY: This observer and TanStack's offset delegate read only the window, element, offset, and listed options. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Happy DOM supplies the browser contract used by this focused fixture. const instance = { scrollElement: viewport, targetWindow, @@ -137,6 +143,8 @@ test("cleanup suppresses queued delegated callbacks, reconnect checks, and later route.append(viewport) document.body.append(route) + // SAFETY: This observer and TanStack's offset delegate read only the window, element, offset, and listed options. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Happy DOM supplies the browser contract used by this focused fixture. const instance = { scrollElement: viewport, targetWindow: window, @@ -170,8 +178,50 @@ test("cleanup suppresses queued delegated callbacks, reconnect checks, and later route.remove() }) +test("ends a scroll at the live offset after a write without its own scroll event", async () => { + const viewport = document.createElement("div") + document.body.append(viewport) + + // SAFETY: This observer and TanStack's offset delegate read only the window, element, offset, and listed options. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Happy DOM supplies the browser contract used by this focused fixture. + const instance = { + scrollElement: viewport, + targetWindow: window, + scrollOffset: 0, + options: { + horizontal: false, + isRtl: false, + isScrollingResetDelay: 10, + useScrollendEvent: false, + }, + } as unknown as Virtualizer + + const calls: [number, boolean][] = [] + + const cleanup = observeElementOffsetReconnectAware(instance, (offset, isScrolling) => { + calls.push([offset, isScrolling]) + instance.scrollOffset = offset + }) + + try { + viewport.scrollTop = 100 + viewport.dispatchEvent(new Event("scroll")) + // A history prepend anchors with a write whose scroll event a long task can hold past the reset delay. + viewport.scrollTop = 2_620 + await new Promise((resolve) => setTimeout(resolve, 25)) + + expect(calls).toEqual([ + [100, true], + [2_620, false], + ]) + } finally { + cleanup?.() + viewport.remove() + } +}) + type FrameWindow = { - requestAnimationFrame(callback: () => void): unknown + requestAnimationFrame(callback: () => void): void performance: { now(): number } } @@ -188,6 +238,8 @@ function controlledMutations(targetWindow: Window) { class ControlledMutationObserver { constructor(callback: MutationCallback) { + // SAFETY: The callback uses only the observer lifecycle methods implemented by this controlled fixture. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Controlled observer intentionally omits unused browser internals. emit = (record) => callback([record], this as unknown as MutationObserver) } observe() {} @@ -199,7 +251,9 @@ function controlledMutations(targetWindow: Window) { Object.defineProperty(targetWindow, "MutationObserver", { value: ControlledMutationObserver }) + // SAFETY: The production observer reads only type, target, addedNodes, and removedNodes from these fixture records. const record = (target: Node, addedNodes: Node[], removedNodes: Node[]) => + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Happy DOM nodes implement the DOM methods consumed by the observer. ({ type: "childList", target, addedNodes, removedNodes }) as unknown as MutationRecord return { diff --git a/packages/app/src/session/timeline/observe-element-offset.ts b/packages/app/src/session/timeline/observe-element-offset.ts index 80f3d5fb4d..5571955cd9 100644 --- a/packages/app/src/session/timeline/observe-element-offset.ts +++ b/packages/app/src/session/timeline/observe-element-offset.ts @@ -6,14 +6,16 @@ export function observeElementOffsetReconnectAware void, ) { let active = true + const element = instance.scrollElement const deliver = (offset: number, isScrolling: boolean) => { if (!active) return - callback(offset, isScrolling) + // The core's reset-delay fallback repeats the offset read by the last scroll event. A long task can hold a + // write's own scroll event past that delay, so ending the scroll at the stored offset would revert the write. + callback(isScrolling || !element ? offset : element.scrollTop, isScrolling) } const cleanupOffset = observeElementOffset(instance, deliver) - const element = instance.scrollElement const targetWindow = instance.targetWindow const root = element?.closest("main") ?? element?.ownerDocument.body diff --git a/packages/app/test-browser/browser-site.test.ts b/packages/app/test-browser/browser-site.test.ts new file mode 100644 index 0000000000..1b9269fed7 --- /dev/null +++ b/packages/app/test-browser/browser-site.test.ts @@ -0,0 +1,104 @@ +import { expect, test } from "bun:test" +import { mkdtemp, rm } from "node:fs/promises" +import { join, resolve } from "node:path" +import { pathToFileURL } from "node:url" +import { build } from "vite" +import solid from "vite-plugin-solid" +import { browser } from "../src/cookiemonster/browser/en" + +test("mounted site inspection exposes failed refreshes over retained data and clears them on retry or navigation", async () => { + const directory = await mkdtemp(resolve("test-browser/.site-inspection-")) + const host = document.createElement("div") + document.body.append(host) + let dispose = () => {} + + try { + await build({ + configFile: false, + root: resolve("."), + logLevel: "warn", + plugins: [ + { + name: "site-inspection-fixture", + enforce: "pre", + resolveId(id) { + for (const name of ["site-inspection-fixture", "@/runtime/i18n/language"]) { + if (id === name || id.replaceAll("\\", "/") === resolve(name.replace("@/", "src/")).replaceAll("\\", "/")) + return "\0" + name + } + }, + load(id) { + if (id === "\0@/runtime/i18n/language") + return `import { browser } from ${JSON.stringify(resolve("src/cookiemonster/browser/en.ts"))}; + export const useLanguage = () => ({intl:()=>"en-US", t:(key, params={})=>Object.entries(params).reduce((text,[name,value])=>text.replaceAll("{{"+name+"}}",String(value)),browser[key] ?? key)});` + + if (id === "\0site-inspection-fixture") + return ` + import { createComponent } from "solid-js"; + import { createStore } from "solid-js/store"; + import { render } from "solid-js/web"; + import { BrowserSite } from ${JSON.stringify(resolve("src/cookiemonster/browser/browser-site.tsx"))}; + export function mount(host, initialFailure=false) { + const [state,setState]=createStore({result:initialFailure?"false":"true",tab:{id:"tab",url:"https://first.example/page",agentAccess:true,siteData:initialFailure?undefined:{origin:"https://first.example",cookies:1,usage:1024,storage:[]}}}); + const dispose=render(()=>createComponent(BrowserSite,{get tab(){return state.tab},profile:{},busy:false,command:async()=>{if(state.result==="reject")throw Error("inspection failed");return state.result!=="false"}}),host); + return {dispose,result:value=>setState("result",value),tab:value=>setState("tab",value)}; + }` + }, + }, + solid(), + ], + resolve: { alias: { "@": resolve("src") } }, + build: { + outDir: directory, + emptyOutDir: false, + minify: false, + lib: { entry: "site-inspection-fixture", formats: ["es"], fileName: () => "fixture.mjs" }, + }, + }) + const fixture = await import(pathToFileURL(join(directory, "fixture.mjs")).href) + const mounted = fixture.mount(host) + dispose = mounted.dispose + const tick = () => new Promise((resolve) => setImmediate(resolve)) + + const refresh = () => + [...host.querySelectorAll("button")] + .find((button) => button.textContent?.trim() === browser["browser.site.refresh"])! + .click() + + await tick() + expect(host.textContent).toContain("Cookies matching this page: 1") + + for (const failure of ["false", "reject"]) { + mounted.result(failure) + refresh() + await tick() + expect(host.textContent).toContain(browser["browser.site.inspectFailed"]) + expect(host.textContent).toContain(browser["browser.site.stale"]) + expect(host.textContent).toContain("Cookies matching this page: 1") + } + + mounted.result("true") + mounted.tab({ siteData: { origin: "https://first.example", cookies: 2, usage: 1024, storage: [] } }) + refresh() + await tick() + expect(host.textContent).toContain("Cookies matching this page: 2") + expect(host.textContent).not.toContain(browser["browser.site.inspectFailed"]) + expect(host.textContent).not.toContain(browser["browser.site.stale"]) + mounted.tab({ url: "https://second.example/" }) + await tick() + expect(host.textContent).toContain(browser["browser.site.inspecting"]) + expect(host.textContent).not.toContain("Cookies matching this page:") + dispose() + host.replaceChildren() + const initial = fixture.mount(host, true) + dispose = initial.dispose + await tick() + expect(host.textContent).toContain(browser["browser.site.inspectFailed"]) + expect(host.textContent).not.toContain(browser["browser.site.stale"]) + expect(host.textContent).not.toContain(browser["browser.site.inspecting"]) + } finally { + dispose() + host.remove() + await rm(directory, { recursive: true, force: true }) + } +}, 30_000) diff --git a/packages/app/test-browser/cm-loading.fixture.tsx b/packages/app/test-browser/cm-loading.fixture.tsx index 095e5ccb89..7430d129ec 100644 --- a/packages/app/test-browser/cm-loading.fixture.tsx +++ b/packages/app/test-browser/cm-loading.fixture.tsx @@ -17,7 +17,9 @@ function Fixture() { return (
+ section { display:flex; } svg { flex-shrink:0; } + /* Own layer per compared row, so identical rows raster from the same tile origin. */ + #project, #recent, #tabs { will-change: transform; }`} diff --git a/packages/app/test-browser/cm-loading.test.ts b/packages/app/test-browser/cm-loading.test.ts index bf123b3dec..a9fd0cd40f 100644 --- a/packages/app/test-browser/cm-loading.test.ts +++ b/packages/app/test-browser/cm-loading.test.ts @@ -9,7 +9,9 @@ import solid from "vite-plugin-solid" test("session cookies share their animation and phase across late mounts, updates, and reduced motion", async () => { const directory = await mkdtemp(join(tmpdir(), "cm-loading-")) - const browser = await chromium.launch() + // SVG images follow Chromium's own reduced-motion preference (the OS setting on Windows), not page emulation. + // Pin it so the motion checks are deterministic; page emulation below still covers reduced motion. + const browser = await chromium.launch({ args: ["--force-prefers-no-reduced-motion"] }) const server = createServer(async (request, response) => { const pathname = new URL(request.url ?? "/", "http://localhost").pathname @@ -31,6 +33,7 @@ test("session cookies share their animation and phase across late mounts, update await new Promise((done) => server.listen(0, "127.0.0.1", done)) const address = server.address() + // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Node returns a Unix socket path or a TCP address; this fixture binds TCP. if (!address || typeof address === "string") throw new Error("Loader fixture server did not bind") try { diff --git a/packages/app/test-browser/session-retention.test.ts b/packages/app/test-browser/session-retention.test.ts new file mode 100644 index 0000000000..338f170eca --- /dev/null +++ b/packages/app/test-browser/session-retention.test.ts @@ -0,0 +1,415 @@ +import { expect, test } from "bun:test" +import { OpenCode, type OpenCodeEvent, type SessionInfo } from "@opencode/client/promise" +import { createData, type CreateDataInput } from "@opencode/client/solid" +import { createRoot, createSignal } from "solid-js" +import { unwrap } from "solid-js/store" +import { createSessionRetention } from "@/runtime/server/session-retention" + +// Runs under the browser build: the server build of Solid never runs the policy's effect. +const delay = 10 + +test("releases unkept families after the delay and keeps visible, running and attention families", async () => { + const ids = ["ses_open", "ses_open_child", "ses_closed", "ses_closed_child", "ses_running", "ses_asked"] + const scope = setup({ visible: ["ses_open_child"] }) + + try { + scope.remember("ses_open") + scope.remember("ses_open_child", "ses_open") + scope.remember("ses_closed") + scope.remember("ses_closed_child", "ses_closed") + scope.remember("ses_running") + scope.remember("ses_asked") + scope.data.session.setStatus("ses_running", "running") + scope.emit(permissionAsked("ses_asked")) + + for (const id of ids) await scope.data.session.message.sync(id) + await settle() + + expect(ids.filter(scope.cached)).toEqual(["ses_open", "ses_open_child", "ses_running", "ses_asked"]) + // Eviction drops only transcript rows. + expect(scope.data.session.get("ses_closed_child")?.parentID).toBe("ses_closed") + expect(scope.data.session.family("ses_closed")).toEqual(["ses_closed", "ses_closed_child"]) + expect(scope.data.session.status("ses_running")).toBe("running") + expect(scope.data.session.permission.list("ses_asked")?.[0]?.id).toBe("per_ses_asked") + + scope.data.session.setStatus("ses_running", "idle") + await settle() + expect(ids.filter(scope.cached)).toEqual(["ses_open", "ses_open_child", "ses_asked"]) + } finally { + scope.dispose() + } +}) + +test("closing a child tab keeps its still-visible parent and sibling family", async () => { + const ids = ["ses_parent", "ses_child", "ses_sibling"] + const scope = setup({ visible: ["ses_parent", "ses_child"] }) + + try { + scope.remember("ses_parent") + scope.remember("ses_child", "ses_parent") + scope.remember("ses_sibling", "ses_parent") + + for (const id of ids) await scope.data.session.message.sync(id) + + scope.setVisible(["ses_parent"]) + await settle() + expect(ids.filter(scope.cached)).toEqual(ids) + + scope.setVisible([]) + await settle() + expect(ids.filter(scope.cached)).toEqual([]) + } finally { + scope.dispose() + } +}) + +test("waits for persisted tabs, and keeps a read that lands before its tab or navigation commits", async () => { + const scope = setup({ ready: false }) + + try { + scope.remember("ses_opening") + await scope.data.session.message.sync("ses_opening") + await settle() + expect(scope.cached("ses_opening")).toBe(true) + + // Home reads the transcript before its transition adds the tab. + scope.setReady(true) + scope.setVisible(["ses_opening"]) + await settle() + expect(scope.cached("ses_opening")).toBe(true) + + scope.setNavigating(true) + scope.setVisible([]) + await settle() + expect(scope.cached("ses_opening")).toBe(true) + + scope.setNavigating(false) + await settle() + expect(scope.cached("ses_opening")).toBe(false) + } finally { + scope.dispose() + } +}) + +test("late reads, late pages and later events are released again, and reopening reads the transcript", async () => { + const late = Promise.withResolvers() + const older = Promise.withResolvers() + const ids = ["ses_paged", "ses_late"] + + const scope = setup({ + visible: ids, + read(url) { + if (url.searchParams.has("cursor")) return older.promise + + if (url.pathname.endsWith("/ses_late/message")) return late.promise + + return undefined + }, + }) + + try { + scope.remember("ses_paged") + scope.remember("ses_late") + await scope.data.session.message.sync("ses_paged") + await scope.data.session.pending.sync("ses_late") + + const reads = Promise.allSettled([ + scope.data.session.message.sync("ses_late"), + scope.data.session.message.loadMore("ses_paged"), + ]) + + scope.setVisible([]) + await settle() + expect(ids.filter(scope.cached)).toEqual([]) + + late.resolve() + older.resolve() + await reads + // Both reads publish after their family was evicted. + expect(ids.filter(scope.cached)).toEqual(ids) + await settle() + expect(ids.filter(scope.cached)).toEqual([]) + + scope.emit(agentSelected("ses_paged")) + expect(scope.cached("ses_paged")).toBe(true) + await settle() + expect(scope.cached("ses_paged")).toBe(false) + + scope.setVisible(["ses_paged"]) + await scope.data.session.message.sync("ses_paged") + await settle() + expect(scope.transcriptReads("ses_paged")).toBe(2) + expect(scope.data.session.message.list("ses_paged").map((item) => item.id)).toEqual(["msg_ses_paged"]) + } finally { + late.resolve() + older.resolve() + scope.dispose() + } +}) + +test.each(["echo", "reject"] as const)( + "keeps a closed session's optimistic prompt past the deadline and releases it after its %s", + async (mode) => { + const answer = Promise.withResolvers() + + const scope = setup({ + async read(url) { + if (!url.pathname.endsWith("/prompt")) return undefined + await answer.promise + + return mode === "reject" + ? Response.json({ message: "rejected" }, { status: 400 }) + : Response.json({ id: "msg_local" }) + }, + }) + + try { + scope.remember("ses_submit") + + const prompt = Promise.allSettled([ + scope.data.session.prompt({ sessionID: "ses_submit", id: "msg_local", text: "local" }), + ]) + + await settle() + // The deadline passed while the submission awaited its acknowledgement. + expect(scope.data.session.message.list("ses_submit").map((item) => item.id)).toEqual(["msg_local"]) + + if (mode === "echo") scope.emit(enqueued("ses_submit", "msg_local")) + answer.resolve() + await prompt + await settle() + expect(scope.cached("ses_submit")).toBe(false) + expect(scope.data.session.pending.list("ses_submit")).toEqual([]) + } finally { + answer.resolve() + scope.dispose() + } + }, +) + +test("keeps a closed session's first prompt while its creation is unacknowledged, then releases it", async () => { + const created = Promise.withResolvers() + + const scope = setup({ + read(url) { + if (url.pathname === "/api/session") return created.promise + + if (url.pathname.endsWith("/prompt")) return Promise.resolve(Response.json({ id: "msg_first" })) + + return undefined + }, + }) + + try { + const session = scope.data.session.create({}) + + const prompt = Promise.allSettled([ + scope.data.session.prompt({ sessionID: session.id, id: "msg_first", text: "first" }), + ]) + + await settle() + // Eviction skips a session whose creation the server has not acknowledged. + expect(scope.data.session.message.list(session.id).map((item) => item.id)).toEqual(["msg_first"]) + + created.resolve(Response.json({ data: info(session.id) })) + await session.request + scope.emit(enqueued(session.id, "msg_first")) + await prompt + await settle() + expect(scope.cached(session.id)).toBe(false) + expect(scope.data.session.pending.list(session.id)).toEqual([]) + expect(scope.data.session.get(session.id)?.id).toBe(session.id) + } finally { + scope.dispose() + } +}) + +test("closed transcripts and the rows later events bring back do not stay on the heap", async () => { + if (process.env.CM_RETENTION_HEAP_PROBE !== "1") { + // Other browser tests can release their heaps between samples; measure this contract in its own process. + const result = Bun.spawnSync( + [ + process.execPath, + "test", + "--conditions=browser", + "--preload", + "./happydom.ts", + import.meta.path, + "-t", + "closed transcripts and the rows", + ], + { env: { ...process.env, CM_RETENTION_HEAP_PROBE: "1" }, timeout: 20_000, stdout: "pipe", stderr: "pipe" }, + ) + + expect(result.exitCode, result.stdout.toString() + result.stderr.toString()).toBe(0) + + return + } + + const count = 48 + const size = 512 * 1024 + const ids = Array.from({ length: count }, (_, index) => `ses_heavy_${index}`) + const scope = setup({ text: "x".repeat(size) }) + + try { + ids.forEach((id) => scope.remember(id)) + scope.setVisible(ids) + const base = heap() + + for (const id of ids) await scope.data.session.message.sync(id) + const rows = ids.map((id) => new WeakRef(unwrap(scope.data.session.message.list(id))[0]!)) + const loaded = heap() + + scope.setVisible([]) + await settle() + ids.forEach((id) => scope.emit(agentSelected(id))) + expect(ids.filter(scope.cached)).toEqual(ids) + await settle() + const released = heap() + + console.info(`[session-retention heap] base=${base} loaded=${loaded} released=${released}`) + expect(ids.filter(scope.cached)).toEqual([]) + expect(loaded - base).toBeGreaterThan(count * size * 0.8) + expect(released - base).toBeLessThan((loaded - base) * 0.1) + expect(rows.filter((row) => row.deref() !== undefined)).toHaveLength(0) + } finally { + scope.dispose() + } +}) + +function settle() { + return Bun.sleep(delay * 5) +} + +function heap() { + Bun.gc(true) + + return process.memoryUsage().heapUsed +} + +function setup( + input: { + visible?: string[] + ready?: boolean + text?: string + /** Delays a request, or answers it when the promise resolves to a response. */ + read?: (url: URL) => Promise | undefined + } = {}, +) { + const listeners = new Set[0]>() + const reads: URL[] = [] + + const api = OpenCode.make({ + baseUrl: "http://opencode.local", + fetch: async (request) => { + const url = new URL(request instanceof Request ? request.url : String(request)) + reads.push(url) + const response = await input.read?.(url) + + if (response) return response + const sessionID = url.pathname.split("/")[3] + + if (url.pathname.endsWith("/inbox")) + return Response.json({ + data: [ + { + id: `inb_${sessionID}`, + sessionID, + type: "user", + delivery: "steer", + payload: { text: "pending" }, + time: { created: 2 }, + }, + ], + }) + const older = url.searchParams.has("cursor") + + return Response.json({ + data: [ + { + id: older ? `msg_${sessionID}_older` : `msg_${sessionID}`, + type: "user", + text: input.text ?? "transcript", + time: { created: older ? 0 : 1 }, + }, + ], + cursor: older ? {} : { next: "older" }, + }) + }, + }) + + return createRoot((dispose) => { + const data = createData({ + api: () => api, + directory: "/project", + event: { + on: () => () => {}, + listen(handler) { + listeners.add(handler) + + return () => listeners.delete(handler) + }, + }, + }) + + const [visible, setVisible] = createSignal(input.visible ?? []) + const [ready, setReady] = createSignal(input.ready ?? true) + const [navigating, setNavigating] = createSignal(false) + createSessionRetention({ session: data.session, ready, visible, navigating, delay }) + + return { + data, + dispose, + setVisible, + setReady, + setNavigating, + emit: (details: OpenCodeEvent) => listeners.forEach((listener) => listener({ name: details.type, details })), + remember: (id: string, parentID?: string) => data.session.remember(info(id, parentID)), + cached: (id: string) => data.session.message.list(id).length > 0, + // Reads of the newest transcript page, not of older pages. + transcriptReads: (id: string) => + reads.filter((url) => url.pathname.endsWith(`/${id}/message`) && !url.searchParams.has("cursor")).length, + } + }) +} + +function info(id: string, parentID?: string): SessionInfo { + return { + id, + parentID, + projectID: "project", + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: 0, updated: 0 }, + location: { directory: "/project" }, + } +} + +function agentSelected(sessionID: string): OpenCodeEvent { + return { + id: `evt_agent_${sessionID}`, + created: 1, + type: "session.agent.selected", + durable: { aggregateID: sessionID, seq: 1, version: 1 }, + data: { sessionID, agent: "build" }, + } +} + +function permissionAsked(sessionID: string): OpenCodeEvent { + return { + id: `evt_permission_${sessionID}`, + created: 1, + type: "permission.asked", + data: { id: `per_${sessionID}`, sessionID, action: "bash", resources: ["bun test"] }, + } +} + +function enqueued(sessionID: string, inboxID: string): OpenCodeEvent { + return { + id: `evt_${inboxID}`, + created: 1, + type: "session.inbox.enqueued", + durable: { aggregateID: sessionID, seq: 1, version: 1 }, + data: { sessionID, inboxID, item: { type: "user", delivery: "steer", payload: { text: "echoed" } } }, + } +} diff --git a/packages/cli/script/build-node.ts b/packages/cli/script/build-node.ts index f7c64eeddc..566c797f76 100644 --- a/packages/cli/script/build-node.ts +++ b/packages/cli/script/build-node.ts @@ -155,7 +155,7 @@ for (const target of targets) { )}\n`, ) await verifyArtifact(path.join(outdir, name)) - if (host) await smoke(output) + if (host) await smoke(output, builder) } async function resolveHostNode() { @@ -225,14 +225,20 @@ async function resolveTargetNode(target: NodeTarget, host?: string) { return realpath(executable) } -async function smoke(output: string) { +async function smoke(output: string, node: string) { const root = await mkdtemp(path.join(os.tmpdir(), "opencode-node-smoke-")) const executable = path.join(root, path.basename(output)) await copyFile(output, executable) if (process.platform !== "win32") await chmod(executable, 0o755) run(executable, ["--version"], root) run(executable, ["--help"], root) - await rm(root, { recursive: true, force: true }) + // Use Node's retry-aware cleanup for transient Windows directory locks. + run(node, [ + "--input-type=module", + "-e", + "import { rm } from 'node:fs/promises'; await rm(process.argv[1], { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })", + root, + ]) } function targetName(target: NodeTarget) { diff --git a/packages/client/src/solid/data.ts b/packages/client/src/solid/data.ts index c5036a03f4..9b9300d9ec 100644 --- a/packages/client/src/solid/data.ts +++ b/packages/client/src/solid/data.ts @@ -1428,6 +1428,12 @@ export function createData(config: CreateDataInput) { status === "running" ? [sessionID] : [], ) }, + /** Sessions holding transcript or pending rows. Notifies only when that set changes, not per streamed row. */ + cached: createMemo( + () => [...new Set([...Object.keys(store.session.message), ...Object.keys(store.session.pending)])].toSorted(), + [], + { equals: (a, b) => a.length === b.length && a.every((id, index) => id === b[index]) }, + ), // Inputs are the pending user and synthetic items; compactions are control items. input: { list(sessionID: string) { diff --git a/packages/cm-browser/README.md b/packages/cm-browser/README.md index 677b6998c5..263246ee4a 100644 --- a/packages/cm-browser/README.md +++ b/packages/cm-browser/README.md @@ -2,6 +2,14 @@ The desktop browser uses main-owned Electron `WebContentsView` tabs. Tabs belong to a chat session and retain their pages when switching tabs, switching sessions, or hiding the browser panel. Closing a tab respects its `beforeunload` handler. Pop-ups open as new tabs and preserve normal opener behavior. +## Backend trust and request limits + +The desktop trusts its authenticated V2 backend, installed plugins, and the task/session IDs that backend supplies across tasks. This boundary does not isolate tasks after backend compromise. Web pages remain untrusted. Main still checks native ownership, task grants, delegated leases, pause state, document identity, and delivery validity for each operation. + +The V2 browser RPC validates serialized request events against a 64 KiB UTF-8 budget before publishing them. The largest permitted typed input is 10,000 characters, at most 40,000 UTF-8 bytes; site-tool arguments have an 8 KiB limit, and delegation is limited to 16 tab IDs. These inputs fit within the envelope budget. Rejected events disconnect the browser port and settle its pending operations. The native bridge also caps active requests at 256. These are admission limits, not a guarantee against the memory required to construct an input or a compromised backend bypassing its own schema. + +Responses keep their existing RPC compatibility limit and main-owned snapshot/image budgets. The previous request-event ceiling was 20 Mi UTF-16 code units. Ordinary request parsing already drops unused fields. The 1 MiB unused-field probe demonstrated acceptance, without establishing lasting retention or an OOM. The legacy DOM assertion memory spike was measured separately. + ## Autonomous agent browsing CM Browser is the default desktop browser for agent tasks. The model starts with `browser_read_state`, creates a tab with `browser_create_tab` when needed, then uses `browser_navigate`. Creation initializes upload interception before authorizing the blank tab. Create, select and close use standing task authority for agent-controlled tabs, without routine native approval. Explicit OpenCode ask/deny rules still apply. Selecting or creating a tab reveals the browser panel. diff --git a/packages/cm-browser/src/protocol.ts b/packages/cm-browser/src/protocol.ts index d6ef695263..d857c98027 100644 --- a/packages/cm-browser/src/protocol.ts +++ b/packages/cm-browser/src/protocol.ts @@ -4,6 +4,7 @@ export const ALLOWLIST_FILENAME = "cm-browser-allowlist.json" export const STATE_DIRECTORY_NAME = "CookieMonster" export const MAX_URL_LENGTH = 2_048 export const MAX_TYPED_TEXT = 10_000 +export const MAX_REQUEST_BYTES = 64 * 1024 export const MAX_SNAPSHOT_BYTES = 64 * 1024 export const OPERATION_TIMEOUT_MS = 15_000 export const MAX_SCREENSHOT_EDGE = 4096 diff --git a/packages/cm-browser/src/rpc.ts b/packages/cm-browser/src/rpc.ts index 9ec1a39ee8..17617fa7ad 100644 --- a/packages/cm-browser/src/rpc.ts +++ b/packages/cm-browser/src/rpc.ts @@ -1,8 +1,13 @@ import { Rpc } from "@opencode/schema/rpc" import { z } from "zod" +import { MAX_REQUEST_BYTES } from "./protocol" const connectionID = z.string().regex(/^[a-f\d-]{36}$/) const message = z.string().max(20 * 1024 * 1024) +const requestMessage = z + .string() + .max(MAX_REQUEST_BYTES) + .refine((value) => Buffer.byteLength(value) <= MAX_REQUEST_BYTES, "Browser request exceeds 64 KiB") export const BrowserRpc = Rpc.define({ id: "cookiemonster.browser", methods: { @@ -12,6 +17,6 @@ export const BrowserRpc = Rpc.define({ }, events: { attached: { schema: z.object({ connectionID }) }, - request: { schema: z.object({ connectionID, message }) }, + request: { schema: z.object({ connectionID, message: requestMessage }) }, }, }) diff --git a/packages/cm-browser/test/rpc-budget.test.ts b/packages/cm-browser/test/rpc-budget.test.ts new file mode 100644 index 0000000000..a714366122 --- /dev/null +++ b/packages/cm-browser/test/rpc-budget.test.ts @@ -0,0 +1,67 @@ +import { expect, test } from "bun:test" +import { mkdtemp, rm } from "node:fs/promises" +import { join } from "node:path" +import { tmpdir } from "node:os" +import { OpenCode } from "@opencode/sdk" +import { Plugin } from "@opencode/plugin" +import { BrowserRpc } from "../src/rpc" +import { MAX_REQUEST_BYTES, MAX_TYPED_TEXT } from "../src/protocol" + +test("the real RPC event boundary rejects oversized serialized browser requests in UTF-8 bytes", async () => { + const directory = await mkdtemp(join(tmpdir(), "cm-browser-budget-")) + const ready = Promise.withResolvers<(message: string) => Promise>() + try { + await using host = await OpenCode.create({ + config: { directory, project: false, content: "{}" }, + models: { fetch: false }, + fs: { filewatcher: false }, + plugins: [ + Plugin.define({ + id: "browser-budget", + async setup(ctx) { + const rpc = await ctx.rpc.register(BrowserRpc, { + attach: async () => null, + detach: async () => null, + result: async () => null, + }) + if (ctx.location.directory === directory) + ready.resolve((message) => + rpc.events.emit("request", { connectionID: "00000000-0000-4000-8000-000000000001", message }), + ) + return rpc.dispose + }, + }), + ], + }) + await host.model.list({ location: { directory } }) + const emit = await ready.promise + const fill = JSON.stringify({ + type: "browser_request", + id: "one", + sessionID: "task", + request: { op: "fill", tabID: "tab", ref: "element", text: "界".repeat(MAX_TYPED_TEXT) }, + }) + await expect(emit(fill)).resolves.toBeUndefined() + await expect(emit("x".repeat(MAX_REQUEST_BYTES))).resolves.toBeUndefined() + for (const message of [ + "x".repeat(MAX_REQUEST_BYTES + 1), + "界".repeat(Math.ceil(MAX_REQUEST_BYTES / 3)), + JSON.stringify({ + type: "browser_request", + id: "one", + sessionID: "task", + request: { op: "list_tabs" }, + unused: "x".repeat(1024 * 1024), + }), + ]) { + const rejected = await emit(message).then( + () => false, + () => true, + ) + expect(rejected).toBe(true) + } + await expect(emit(fill)).resolves.toBeUndefined() + } finally { + await rm(directory, { recursive: true, force: true }) + } +}, 20_000) diff --git a/packages/core/package.json b/packages/core/package.json index c249782e64..f1d67760e5 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -30,6 +30,10 @@ "./*": "./src/*.ts" }, "imports": { + "#cm-ae-plugin": { + "workerd": "./src/cm-ae/plugin.workerd.ts", + "default": "./src/cm-ae/plugin.ts" + }, "#sqlite": { "workerd": "./src/database/sqlite.workerd.ts", "bun": "./src/database/sqlite.bun.ts", diff --git a/packages/core/src/cm-ae/plugin.ts b/packages/core/src/cm-ae/plugin.ts index 7b6c8dbc91..0c544a30b6 100644 --- a/packages/core/src/cm-ae/plugin.ts +++ b/packages/core/src/cm-ae/plugin.ts @@ -238,3 +238,5 @@ export const Plugin = { ) }), } + +export const plugins = [Plugin] as const diff --git a/packages/core/src/cm-ae/plugin.workerd.ts b/packages/core/src/cm-ae/plugin.workerd.ts new file mode 100644 index 0000000000..e826884ffb --- /dev/null +++ b/packages/core/src/cm-ae/plugin.workerd.ts @@ -0,0 +1,4 @@ +export * as CmAePlugin from "./plugin.workerd.js" + +// The desktop bundle loader needs native files and dynamic imports unavailable in workerd. +export const plugins = [] as const diff --git a/packages/core/src/cm-ae/skills.ts b/packages/core/src/cm-ae/skills.ts index 028c83a856..d56f92786c 100644 --- a/packages/core/src/cm-ae/skills.ts +++ b/packages/core/src/cm-ae/skills.ts @@ -2,6 +2,7 @@ import path from "node:path" import { randomBytes } from "node:crypto" import { stat } from "node:fs/promises" import { AbsolutePath } from "@opencode/schema/schema" +import { Glob } from "@opencode/util/glob" import { Schema } from "effect" import type { Skill } from "@opencode/schema/skill" import { ManagedSkill } from "./managed.js" @@ -29,11 +30,10 @@ export function skills(input: { throw error }) if (!exists) continue - for await (const file of new Bun.Glob("**/SKILL.md").scan({ + for (const file of await Glob.scan("**/SKILL.md", { cwd: root, absolute: true, - onlyFiles: true, - followSymlinks: true, + symlink: true, })) files.add(AbsolutePath.make(file)) } diff --git a/packages/core/src/plugin/internal.ts b/packages/core/src/plugin/internal.ts index a026f6342a..2f8c50efc7 100644 --- a/packages/core/src/plugin/internal.ts +++ b/packages/core/src/plugin/internal.ts @@ -1,7 +1,7 @@ export * as PluginInternal from "./internal.js" import { ScheduleRuntime } from "../schedule/runtime.js" -import { CmAePlugin } from "../cm-ae/plugin.js" +import { CmAePlugin } from "#cm-ae-plugin" import { SchedulePlugin } from "../schedule/plugin.js" import { LLMClient } from "@opencode/ai" import type { Plugin } from "@opencode/plugin/effect/plugin" @@ -290,6 +290,6 @@ export const list = Effect.fn("PluginInternal.list")(function* () { ) return { pre: resolve(pre), - post: resolve(process.env.CM_DESKTOP === "1" ? [...post, SchedulePlugin.Plugin, CmAePlugin.Plugin] : post), + post: resolve(process.env.CM_DESKTOP === "1" ? [...post, SchedulePlugin.Plugin, ...CmAePlugin.plugins] : post), } }) diff --git a/packages/core/test/cm-ae-platform.test.ts b/packages/core/test/cm-ae-platform.test.ts new file mode 100644 index 0000000000..2ecb96898e --- /dev/null +++ b/packages/core/test/cm-ae-platform.test.ts @@ -0,0 +1,22 @@ +import { expect, test } from "bun:test" +import { join } from "node:path" +import { CmAePlugin } from "#cm-ae-plugin" + +test("native AE registration keeps the desktop plugin", () => { + expect(CmAePlugin.plugins).toHaveLength(1) + expect(CmAePlugin.plugins[0] === CmAePlugin.Plugin).toBe(true) +}) + +test("workerd omits the native AE bundle loader", () => { + const result = Bun.spawnSync( + [ + process.execPath, + "--conditions=workerd", + "-e", + 'import { CmAePlugin } from "#cm-ae-plugin"; console.log(CmAePlugin.plugins.length)', + ], + { cwd: join(import.meta.dir, "..") }, + ) + expect(result.exitCode, result.stderr.toString()).toBe(0) + expect(result.stdout.toString().trim()).toBe("0") +}) diff --git a/packages/core/test/git.test.ts b/packages/core/test/git.test.ts index be7576907f..fea5e6af2a 100644 --- a/packages/core/test/git.test.ts +++ b/packages/core/test/git.test.ts @@ -34,45 +34,52 @@ describe("Git", () => { }), ) - it.live("clones a remote and reads checkout metadata", () => - withRemote((fixture) => - Effect.gen(function* () { - const git = yield* Git.Service - const target = AbsolutePath.make(path.join(fixture.root, "checkout")) - const repository = yield* git.repo.clone({ remote: fixture.remote, directory: target }) - - expect(yield* git.remote.get(repository)).toBe(fixture.remote) - expect(yield* git.history.head(repository)).toBeString() - expect(yield* git.history.branch(repository)).toBe("main") - expect(yield* git.history.defaultRemoteBranch(repository)).toBe("main") - expect(repository.worktree).toBe(target) - expect(repository.gitDirectory).toBe(AbsolutePath.make(path.join(target, ".git"))) - expect(repository.commonDirectory).toBe(repository.gitDirectory) - expect(yield* read(path.join(target, "README.md"))).toBe("one\n") - }), - ), + // These fixtures launch several Git processes; hosted Windows cold starts can exceed five seconds. + it.live( + "clones a remote and reads checkout metadata", + () => + withRemote((fixture) => + Effect.gen(function* () { + const git = yield* Git.Service + const target = AbsolutePath.make(path.join(fixture.root, "checkout")) + const repository = yield* git.repo.clone({ remote: fixture.remote, directory: target }) + + expect(yield* git.remote.get(repository)).toBe(fixture.remote) + expect(yield* git.history.head(repository)).toBeString() + expect(yield* git.history.branch(repository)).toBe("main") + expect(yield* git.history.defaultRemoteBranch(repository)).toBe("main") + expect(repository.worktree).toBe(target) + expect(repository.gitDirectory).toBe(AbsolutePath.make(path.join(target, ".git"))) + expect(repository.commonDirectory).toBe(repository.gitDirectory) + expect(yield* read(path.join(target, "README.md"))).toBe("one\n") + }), + ), + { timeout: 15_000 }, ) - it.live("fetches, checks out, and resets remote changes", () => - withRemote((fixture) => - Effect.gen(function* () { - const git = yield* Git.Service - const target = AbsolutePath.make(path.join(fixture.root, "checkout")) - const repository = yield* git.repo.clone({ remote: fixture.remote, directory: target }) - - yield* Effect.promise(() => commit(fixture.source, "two\n", "second")) - yield* git.sync.fetchRemotes(repository) - yield* git.sync.resetHard(repository, "origin/main") - expect(yield* read(path.join(target, "README.md"))).toBe("two\n") - - yield* Effect.promise(() => branch(fixture.source, "feature/docs", "feature\n")) - yield* git.sync.fetchBranch(repository, { branch: "feature/docs" }) - yield* git.sync.checkoutRemoteBranch(repository, { branch: "feature/docs" }) - yield* git.sync.resetHard(repository, "origin/feature/docs") - expect(yield* git.history.branch(repository)).toBe("feature/docs") - expect(yield* read(path.join(target, "README.md"))).toBe("feature\n") - }), - ), + it.live( + "fetches, checks out, and resets remote changes", + () => + withRemote((fixture) => + Effect.gen(function* () { + const git = yield* Git.Service + const target = AbsolutePath.make(path.join(fixture.root, "checkout")) + const repository = yield* git.repo.clone({ remote: fixture.remote, directory: target }) + + yield* Effect.promise(() => commit(fixture.source, "two\n", "second")) + yield* git.sync.fetchRemotes(repository) + yield* git.sync.resetHard(repository, "origin/main") + expect(yield* read(path.join(target, "README.md"))).toBe("two\n") + + yield* Effect.promise(() => branch(fixture.source, "feature/docs", "feature\n")) + yield* git.sync.fetchBranch(repository, { branch: "feature/docs" }) + yield* git.sync.checkoutRemoteBranch(repository, { branch: "feature/docs" }) + yield* git.sync.resetHard(repository, "origin/feature/docs") + expect(yield* git.history.branch(repository)).toBe("feature/docs") + expect(yield* read(path.join(target, "README.md"))).toBe("feature\n") + }), + ), + { timeout: 15_000 }, ) }) diff --git a/packages/core/test/snapshot.test.ts b/packages/core/test/snapshot.test.ts index b725e6377f..4d4081a202 100644 --- a/packages/core/test/snapshot.test.ts +++ b/packages/core/test/snapshot.test.ts @@ -158,38 +158,42 @@ describe("Snapshot", () => { ), ) - testEffect(Layer.empty).live("captures concurrently from independent processes", () => - Effect.acquireUseRelease( - Effect.promise(() => tmpdir()), - (tmp) => - Effect.gen(function* () { - const project = path.join(tmp.path, "project") - yield* Effect.promise(async () => { - await fs.mkdir(project) - await Promise.all( - Array.from({ length: 200 }, (_, index) => - fs.writeFile(path.join(project, `f${index}.txt`), `${index}\n`), - ), - ) - await initGit(project, true) - }) - // Each layer owns its own Git service, so their in-process locks do not coordinate. - const writer = (id: number) => - Effect.gen(function* () { - const snapshot = yield* Snapshot.Service - return yield* Effect.forEach( - Array.from({ length: 8 }, (_, index) => index), - (index) => - Effect.promise(() => fs.writeFile(path.join(project, `writer-${id}.txt`), `${index}\n`)).pipe( - Effect.andThen(snapshot.capture()), - ), + // Keep the concurrent Git workload intact while allowing hosted Windows process startup. + testEffect(Layer.empty).live( + "captures concurrently from independent processes", + () => + Effect.acquireUseRelease( + Effect.promise(() => tmpdir()), + (tmp) => + Effect.gen(function* () { + const project = path.join(tmp.path, "project") + yield* Effect.promise(async () => { + await fs.mkdir(project) + await Promise.all( + Array.from({ length: 200 }, (_, index) => + fs.writeFile(path.join(project, `f${index}.txt`), `${index}\n`), + ), ) - }).pipe(Effect.provide(snapshotLayer(tmp.path, project))) - const results = yield* Effect.all([writer(0), writer(1), writer(2)], { concurrency: "unbounded" }) - expect(results.flat().every((tree) => tree !== undefined)).toBe(true) - }), - (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), - ), + await initGit(project, true) + }) + // Each layer owns its own Git service, so their in-process locks do not coordinate. + const writer = (id: number) => + Effect.gen(function* () { + const snapshot = yield* Snapshot.Service + return yield* Effect.forEach( + Array.from({ length: 8 }, (_, index) => index), + (index) => + Effect.promise(() => fs.writeFile(path.join(project, `writer-${id}.txt`), `${index}\n`)).pipe( + Effect.andThen(snapshot.capture()), + ), + ) + }).pipe(Effect.provide(snapshotLayer(tmp.path, project))) + const results = yield* Effect.all([writer(0), writer(1), writer(2)], { concurrency: "unbounded" }) + expect(results.flat().every((tree) => tree !== undefined)).toBe(true) + }), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ), + { timeout: 15_000 }, ) testEffect(Layer.empty).live("captures a Location in a directory whose name starts with two dots", () => diff --git a/packages/desktop/README.md b/packages/desktop/README.md index ce5a4e1a27..5ada061d13 100644 --- a/packages/desktop/README.md +++ b/packages/desktop/README.md @@ -77,6 +77,14 @@ CLI preparation uses these channel rules: default. `bun dev --download-server ` instead downloads that CLI version for local development. Neither path requires `OPENCODE_CLI_DIST` or runs the production prebuild. +## CookieMonster Linux launcher migration + +Branded packages use `com.ogilvy.cookiemonster` for their executable, desktop entry, icon basename, window class, and metainfo. The app keeps its existing `com.ogilvy.cookiemonster` profile directory, including WPP sign-in and settings. Packaging identity is independent of whether WPP is enabled. + +Earlier CookieMonster packages installed OpenCode-named launchers and icons. Upgrading removes those obsolete package-owned files; an upstream OpenCode installation supplies its own. If a pinned CookieMonster launcher stops resolving, remove that old pin and pin the new CookieMonster entry. CookieMonster deliberately supplies no OpenCode-named compatibility launcher, so installing or removing it cannot replace upstream OpenCode's files. + +After producing a branded Debian archive, run `bun scripts/check-cm-linux.ts /path/to/cookiemonster.deb` from this package. The check rejects upstream launcher/icon/metainfo paths and verifies the installed desktop entry. Installation and removal coexistence must also be checked in a disposable environment. + ## Startup benchmark `bun run bench:startup` measures a **packaged** build from process spawn to the restored tab being ready and the diff --git a/packages/desktop/electron-builder.config.test.ts b/packages/desktop/electron-builder.config.test.ts index f9e62d8033..e6e3ff0552 100644 --- a/packages/desktop/electron-builder.config.test.ts +++ b/packages/desktop/electron-builder.config.test.ts @@ -1,6 +1,6 @@ import { expect, test } from "bun:test" import { statSync } from "node:fs" -import { cp, mkdtemp, rm } from "node:fs/promises" +import { cp, mkdir, mkdtemp, rm } from "node:fs/promises" import { createRequire } from "node:module" import os from "node:os" import path from "node:path" @@ -18,7 +18,11 @@ const channels = [ { channel: "prod", appId: "ai.opencode.desktop" }, ] as const -function load(channel: string, target?: string): Configuration { +function load(channel: string, target?: string, branded = false, wpp = false): Configuration { + const previousWpp = process.env.CM_WPP + process.env.CM_WPP = wpp ? "1" : "0" + const previousBrand = process.env.CM_BRAND + process.env.CM_BRAND = branded ? "1" : "0" const previous = process.env.OPENCODE_CHANNEL const previousTarget = process.env.OPENCODE_CLI_TARGET process.env.OPENCODE_CHANNEL = channel @@ -29,6 +33,11 @@ function load(channel: string, target?: string): Configuration { try { return getConfig() } finally { + if (previousWpp === undefined) delete process.env.CM_WPP + else process.env.CM_WPP = previousWpp + + if (previousBrand === undefined) delete process.env.CM_BRAND + else process.env.CM_BRAND = previousBrand delete process.env.OPENCODE_CHANNEL delete process.env.OPENCODE_CLI_TARGET @@ -177,3 +186,54 @@ test("the trimmed Zip.js package can still export compressed logs", async () => await rm(dir, { recursive: true, force: true }) } }) + +test.each(channels)("CookieMonster identity is derived before Linux fields for $channel", ({ channel }) => { + const config = load(channel, undefined, true) + const id = "com.ogilvy.cookiemonster" + expect(config.appId).toBe(id) + expect(config.productName).toBe("CookieMonster") + expect(config.protocols).toEqual({ name: "CookieMonster", schemes: ["opencode"] }) + expect(config.extraMetadata?.desktopName).toBe(`${id}.desktop`) + expect(config.linux?.executableName).toBe(id) + expect(config.linux?.desktop?.entry?.StartupWMClass).toBe(id) + expect(config.rpm?.packageName).toBe("cookiemonster") + + for (const fpm of [config.deb?.fpm, config.rpm?.fpm]) { + expect(fpm).toHaveLength(1) + expect(fpm?.[0]).toEndWith(`=/usr/share/metainfo/${id}.metainfo.xml`) + } +}) + +test.each([false, true])("metainfo uses the same branded=%s desktop identity as packaging", async (branded) => { + const directory = await mkdtemp(path.join(os.tmpdir(), "desktop-metainfo-")) + + try { + await mkdir(path.join(directory, "resources")) + + const result = Bun.spawnSync( + [process.execPath, path.join(import.meta.dirname, "scripts/copy-metainfo.ts"), "prod"], + { + cwd: directory, + env: { ...process.env, CM_BRAND: branded ? "1" : "0" }, + stdout: "pipe", + stderr: "pipe", + }, + ) + + expect(result.exitCode, Buffer.concat([result.stdout, result.stderr]).toString()).toBe(0) + const id = branded ? "com.ogilvy.cookiemonster" : "ai.opencode.desktop" + const xml = await Bun.file(path.join(directory, "resources", `${id}.metainfo.xml`)).text() + expect(xml).toContain(`${id}`) + expect(xml).toContain(`${id}.desktop`) + expect(xml).toContain(`${branded ? "CookieMonster" : "OpenCode"}`) + } finally { + await rm(directory, { recursive: true, force: true }) + } +}) + +test.each([false, true])("WPP sign-in protocol follows the optional WPP build: %s", (wpp) => { + expect(load("prod", undefined, true, wpp).protocols).toEqual({ + name: "CookieMonster", + schemes: wpp ? ["opencode", "cookiemonster"] : ["opencode"], + }) +}) diff --git a/packages/desktop/electron-builder.config.ts b/packages/desktop/electron-builder.config.ts index 5aa01176b1..f5b21a216d 100644 --- a/packages/desktop/electron-builder.config.ts +++ b/packages/desktop/electron-builder.config.ts @@ -8,6 +8,7 @@ import type { CustomMacSignOptions } from "app-builder-lib" import { Arch, type Configuration } from "electron-builder" import { NativeArch } from "../../script/native-arch" import { CLI_BINARIES, getCurrentCli, nodePtyPackage } from "./scripts/utils" +import { desktopIdentity } from "./scripts/identity" const execFileAsync = promisify(execFile) @@ -63,17 +64,20 @@ function resolveChannel() { return "dev" } -const APP_IDS = { - dev: "ai.opencode.desktop.dev", - beta: "ai.opencode.desktop.beta", - prod: "ai.opencode.desktop", -} as const - const getBase = (appId: string): Configuration => { const target = getCurrentCli() return { artifactName: "opencode-desktop-${os}-${arch}.${ext}", + afterAllArtifactBuild: async (context) => { + if (appId === "com.ogilvy.cookiemonster") { + for (const artifact of context.artifactPaths.filter((file) => file.endsWith(".deb"))) { + await execFileAsync("bun", [path.join(packageDir, "scripts/check-cm-linux.ts"), artifact]) + } + } + + return [] + }, directories: { output: "dist", buildResources: "resources", @@ -176,10 +180,6 @@ const getBase = (appId: string): Configuration => { notarize: true, target: ["dmg", "zip"], }, - protocols: { - name: "OpenCode", - schemes: ["opencode"], - }, win: { icon: `resources/icons/icon.ico`, signtoolOptions: { @@ -213,17 +213,23 @@ const getBase = (appId: string): Configuration => { export function getConfig() { const channel = resolveChannel() - const appId = APP_IDS[channel] + const identity = desktopIdentity(channel) + const appId = identity.appId const base = getBase(appId) + base.protocols = { + name: appId === "com.ogilvy.cookiemonster" ? "CookieMonster" : channel === "beta" ? "OpenCode Beta" : "OpenCode", + schemes: + appId === "com.ogilvy.cookiemonster" && process.env.CM_WPP === "1" ? ["opencode", "cookiemonster"] : ["opencode"], + } switch (channel) { case "dev": { return { ...base, appId, - productName: "OpenCode Dev", + productName: identity.productName, deb: { fpm: [metainfoFpm(appId)] }, - rpm: { packageName: "opencode-dev", fpm: [metainfoFpm(appId)] }, + rpm: { packageName: identity.packageName, fpm: [metainfoFpm(appId)] }, } } @@ -231,15 +237,14 @@ export function getConfig() { return { ...base, appId, - productName: "OpenCode Beta", - protocols: { name: "OpenCode Beta", schemes: ["opencode"] }, + productName: identity.productName, publish: { provider: "generic", url: "https://opencode.ai/update/api/beta/desktop/opencode/", channel: "latest", }, deb: { fpm: [metainfoFpm(appId)] }, - rpm: { packageName: "opencode-beta", fpm: [metainfoFpm(appId)] }, + rpm: { packageName: identity.packageName, fpm: [metainfoFpm(appId)] }, } } @@ -247,15 +252,17 @@ export function getConfig() { return { ...base, appId, - productName: "OpenCode", - protocols: { name: "OpenCode", schemes: ["opencode"] }, + productName: identity.productName, publish: { provider: "generic", url: "https://opencode.ai/update/api/latest/desktop/opencode/", channel: "latest", }, - deb: { fpm: [metainfoFpm(appId), legacyDesktopEntryFpm] }, - rpm: { packageName: "opencode", fpm: [metainfoFpm(appId), legacyDesktopEntryFpm] }, + deb: { fpm: [metainfoFpm(appId), ...(appId === "ai.opencode.desktop" ? [legacyDesktopEntryFpm] : [])] }, + rpm: { + packageName: identity.packageName, + fpm: [metainfoFpm(appId), ...(appId === "ai.opencode.desktop" ? [legacyDesktopEntryFpm] : [])], + }, } } } @@ -267,36 +274,31 @@ const branded = process.env.CM_BRAND === "1" const unsigned = process.env.CM_UNSIGNED === "1" -const brandedConfig: Configuration = { - ...config, - ...(branded - ? { - appId: "com.ogilvy.cookiemonster", - productName: "CookieMonster", - artifactName: "cookiemonster-${os}-${arch}.${ext}", - extraMetadata: { - ...config.extraMetadata, - cmUserInstall: true, - ...(process.env.CM_VERSION ? { version: process.env.CM_VERSION } : {}), - }, - extraResources: [ - ...(config.extraResources ?? []), - { from: "resources/cm-plugins", to: "cm-plugins" }, - { from: "resources/vault-auth", to: "vault-auth" }, - { from: "resources/cm-ae", to: "cm-ae" }, +const brandedConfig: Configuration = branded + ? { + ...config, + artifactName: "cookiemonster-${os}-${arch}.${ext}", + extraMetadata: { ...config.extraMetadata, cmUserInstall: true }, + extraResources: [ + ...(config.extraResources ?? []), + { from: "resources/cm-plugins", to: "cm-plugins" }, + { from: "resources/vault-auth", to: "vault-auth" }, + { from: "resources/cm-ae", to: "cm-ae" }, + ], + dmg: { + backgroundColor: "#ffffff", + window: { width: 540, height: 360 }, + contents: [ + { x: 160, y: 160, type: "file" }, + { x: 380, y: 160, type: "file", path: path.join(packageDir, "resources", "Install CookieMonster.txt") }, ], - dmg: { - backgroundColor: "#ffffff", - window: { width: 540, height: 360 }, - contents: [ - { x: 160, y: 160, type: "file" }, - { x: 380, y: 160, type: "file", path: path.join(packageDir, "resources", "Install CookieMonster.txt") }, - ], - }, - publish: { provider: "github", owner: "trmosala", repo: "opencode", channel: "latest" }, - } - : {}), -} + }, + publish: { provider: "github", owner: "trmosala", repo: "opencode", channel: "latest" }, + } + : config + +if (branded && process.env.CM_VERSION) + brandedConfig.extraMetadata = { ...brandedConfig.extraMetadata, version: process.env.CM_VERSION } export default unsigned ? ({ diff --git a/packages/desktop/electron.vite.config.test.ts b/packages/desktop/electron.vite.config.test.ts index bde2052332..b66b4b77ca 100644 --- a/packages/desktop/electron.vite.config.test.ts +++ b/packages/desktop/electron.vite.config.test.ts @@ -39,7 +39,7 @@ test("minifies only builds, previews onboarding only in development, and ships s process.env.OPENCODE_CLI_TARGET = item.target const main = (await load("build")).config.main expect(main?.build?.externalizeDeps).toEqual({ - exclude: bundled, + exclude: ["@cookiemonster/wpp", ...bundled], include: [nodePtyPackage(item.target)], }) } diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 9f5cca8ce0..730a008ae2 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -11,7 +11,7 @@ }, "scripts": { "typecheck": "tsgo -b", - "test": "bun test --timeout 30000", + "test": "bun test --preload ./test/preload.ts --timeout 30000", "dev": "bun ./scripts/dev.ts", "migration": "bun ./scripts/migration.ts", "prebuild": "bun ./scripts/prebuild.ts", diff --git a/packages/desktop/scripts/check-cm-linux.ts b/packages/desktop/scripts/check-cm-linux.ts new file mode 100644 index 0000000000..423a2b96a8 --- /dev/null +++ b/packages/desktop/scripts/check-cm-linux.ts @@ -0,0 +1,56 @@ +import assert from "node:assert/strict" +import { $ } from "bun" + +const artifact = process.argv[2] + +assert(artifact?.endsWith(".deb"), "Pass a CookieMonster Debian archive") + +const id = "com.ogilvy.cookiemonster" + +const entries = (await $`dpkg-deb --fsys-tarfile ${artifact} | tar -tf -`.text()) + .split("\n") + .map((entry) => entry.replace(/^\.\//, "")) + .filter(Boolean) + +assert.equal((await $`dpkg-deb -f ${artifact} Package`.text()).trim(), "cookiemonster") + +assert(entries.includes(`usr/share/applications/${id}.desktop`), "CookieMonster desktop entry is missing") + +assert(entries.includes(`usr/share/metainfo/${id}.metainfo.xml`), "CookieMonster metainfo is missing") + +assert(entries.includes(`opt/CookieMonster/${id}`), "CookieMonster executable has the wrong name") + +assert( + entries.some((entry) => entry.startsWith("usr/share/icons/") && entry.endsWith(`/${id}.png`)), + "CookieMonster icons are missing", +) + +const collisions = entries.filter( + (entry) => + entry.startsWith("usr/share/applications/ai.opencode.") || + entry === "usr/share/applications/opencode-desktop.desktop" || + entry.startsWith("usr/share/metainfo/ai.opencode.") || + (entry.startsWith("usr/share/icons/") && /\/(?:ai\.opencode\.|opencode-desktop\.)/.test(entry)), +) + +assert.deepEqual(collisions, [], "CookieMonster archive contains upstream-owned launcher or icon paths") + +const desktop = await $`dpkg-deb --fsys-tarfile ${artifact} | tar -xOf - ./usr/share/applications/${id}.desktop`.text() + +assert.match(desktop, new RegExp(`^StartupWMClass=${id.replaceAll(".", "\\.")}$`, "m")) + +assert(desktop.includes(`Icon=${id}\n`), "Desktop icon identity differs from its file name") + +assert(desktop.includes(`/CookieMonster/${id}`), "Desktop launcher points at the wrong executable") + +const metadata = + await $`dpkg-deb --fsys-tarfile ${artifact} | tar -xOf - ./usr/share/metainfo/${id}.metainfo.xml`.text() + +assert(metadata.includes(`${id}`), "Metainfo identity differs from packaging") + +assert( + metadata.includes(`${id}.desktop`), + "Metainfo points at the wrong launcher", +) + +console.log(JSON.stringify({ artifact, appId: id, entries: entries.length, result: "pass" })) diff --git a/packages/desktop/scripts/check-mac-activation.ts b/packages/desktop/scripts/check-mac-activation.ts new file mode 100644 index 0000000000..3967c62726 --- /dev/null +++ b/packages/desktop/scripts/check-mac-activation.ts @@ -0,0 +1,228 @@ +import { join } from "node:path" +import { Schema } from "effect" + +if (process.platform !== "darwin") throw new Error("Packaged activation must be checked on macOS.") + +const bundle = process.argv[2] + +if (!bundle?.endsWith("/CookieMonster.app")) throw new Error("Pass the owned packaged CookieMonster.app path.") + +const executable = Bun.spawnSync([ + "/usr/libexec/PlistBuddy", + "-c", + "Print :CFBundleExecutable", + join(bundle, "Contents/Info.plist"), +]) + +if (executable.exitCode !== 0) throw new Error("Could not read the packaged executable.") + +const child = Bun.spawn( + [join(bundle, "Contents/MacOS", executable.stdout.toString().trim()), "--inspect=127.0.0.1:9347"], + { stdout: "inherit", stderr: "inherit" }, +) + +const Evaluation = Schema.Struct({ + result: Schema.Struct({ value: Schema.optionalKey(Schema.Boolean) }), + exceptionDetails: Schema.optionalKey( + Schema.Struct({ + text: Schema.String, + exception: Schema.optionalKey(Schema.Struct({ description: Schema.optionalKey(Schema.String) })), + }), + ), +}) + +const waiting = new Map void; reject: (error: Error) => void }>() + +const Reply = Schema.Struct({ + id: Schema.optionalKey(Schema.Number), + result: Schema.optionalKey(Evaluation), + error: Schema.optionalKey(Schema.Struct({ message: Schema.String })), +}) + +const Targets = Schema.Array(Schema.Struct({ type: Schema.String, webSocketDebuggerUrl: Schema.String })) + +let socket: WebSocket | undefined + +let sequence = 0 + +try { + const deadline = Date.now() + 30_000 + + while (!socket && Date.now() < deadline) { + const response = await fetch("http://127.0.0.1:9347/json/list", { signal: AbortSignal.timeout(500) }).catch( + () => undefined, + ) + + if (response?.ok) { + const target = Schema.decodeUnknownSync(Targets)(await response.json()).find((target) => target.type === "node") + + if (target) socket = new WebSocket(target.webSocketDebuggerUrl) + } + + if (!socket) await Bun.sleep(100) + } + + const connection = socket + + if (!connection) throw new Error("The owned packaged app did not open its inspector.") + await new Promise((resolve, reject) => { + connection.addEventListener("open", () => resolve(), { once: true }) + connection.addEventListener("error", () => reject(new Error("Packaged inspector connection failed.")), { + once: true, + }) + }) + connection.addEventListener("message", (event) => { + const reply = Schema.decodeUnknownSync(Reply)(JSON.parse(String(event.data))) + + if (reply.id === undefined) return + const request = waiting.get(reply.id) + waiting.delete(reply.id) + + if (reply.error) request?.reject(new Error(reply.error.message)) + else if (reply.result) request?.resolve(reply.result) + }) + + const evaluate = async (expression: string) => { + const id = ++sequence + + const result = await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + waiting.delete(id) + reject(new Error("Packaged inspector request timed out.")) + }, 5000) + + waiting.set(id, { + resolve: (value) => { + clearTimeout(timer) + resolve(value) + }, + reject: (error) => { + clearTimeout(timer) + reject(error) + }, + }) + // Inspector interrupts can reenter Node's module loader before its initialization finishes. + connection.send( + JSON.stringify({ + id, + method: "Runtime.evaluate", + params: { + expression: `new Promise(resolve => process.nextTick(() => setImmediate(resolve))).then(() => (${expression}))`, + returnByValue: true, + awaitPromise: true, + }, + }), + ) + }) + + if (result.exceptionDetails) + throw new Error(result.exceptionDetails.exception?.description ?? result.exceptionDetails.text) + + if (result.result.value === undefined) throw new Error("Packaged activation did not return a boolean.") + + return result.result.value + } + + if (!(await evaluate(`process.pid === ${child.pid}`))) + throw new Error("Inspector belongs to another process; refusing to operate it.") + const native = `process.getBuiltinModule('module').createRequire(process.execPath)('electron')` + const usable = `Boolean(${native}.BrowserWindow?.getAllWindows().some(w => w !== globalThis.__cmActivationWorker && w.isVisible() && w.webContents.getURL().startsWith('oc://renderer/')))` + + const waitFor = async (stage: string, expression: string) => { + console.log(`Checking packaged activation: ${stage}`) + const deadline = Date.now() + 30_000 + + while (Date.now() < deadline) { + if (await evaluate(expression)) return + await Bun.sleep(100) + } + + await evaluate(`(() => { + const {app, BrowserWindow} = ${native}; + console.log(JSON.stringify({ + stage: ${JSON.stringify(stage)}, + ready: app?.isReady(), + activationHandlers: app?.listenerCount('activate'), + activationEvents: globalThis.__cmActivationEvents ?? 0, + windows: BrowserWindow?.getAllWindows().map(window => { + const url = URL.parse(window.webContents.getURL()); + return { + id: window.id, + visible: window.isVisible(), + minimized: window.isMinimized(), + loading: window.webContents.isLoading(), + page: url ? url.protocol + '//' + url.host + url.pathname : '', + worker: window === globalThis.__cmActivationWorker, + }; + }), + })); + return true; + })()`) + throw new Error(`Packaged activation condition timed out: ${stage}`) + } + + // The inspector can precede BrowserWindow exports; the early window also needs lifecycle adoption before close. + await waitFor( + "initial main window and lifecycle adoption", + `${usable} && ${native}.app.listenerCount('activate') > 0`, + ) + + if (!(await evaluate(`${native}.app.isPackaged`))) throw new Error("This must exercise a packaged application.") + await evaluate(`(() => { + const {app, BrowserWindow} = ${native}; + globalThis.__cmActivationEvents = 0; + app.on('activate', () => globalThis.__cmActivationEvents++); + globalThis.__cmActivationWorker = new BrowserWindow({show:false, webPreferences:{sandbox:true,contextIsolation:true,nodeIntegration:false}}); + BrowserWindow.getAllWindows().filter(w => w !== globalThis.__cmActivationWorker).forEach(w => w.close()); + app.hide(); + return true; + })()`) + await waitFor( + "main windows closed with hidden worker preserved", + `${native}.BrowserWindow.getAllWindows().length === 1 && !globalThis.__cmActivationWorker.isDestroyed()`, + ) + + // Dock clicks send reopen; activate alone only brings the application to the foreground. + const activation = Bun.spawn( + [ + "/usr/bin/osascript", + "-e", + `tell application ${JSON.stringify(bundle)} to reopen`, + "-e", + `tell application ${JSON.stringify(bundle)} to activate`, + ], + { stdout: "inherit", stderr: "inherit" }, + ) + + const activationTimer = setTimeout(() => activation.kill("SIGTERM"), 15_000) + const activationCode = await activation.exited + clearTimeout(activationTimer) + + if (activationCode !== 0) throw new Error("macOS could not activate the owned packaged app.") + await waitFor( + "native activation and restored visible main window", + `globalThis.__cmActivationEvents > 0 && ${usable}`, + ) + + if (!(await evaluate(`!globalThis.__cmActivationWorker.isDestroyed()`))) + throw new Error("Activation destroyed the hidden worker.") + console.log( + JSON.stringify({ + result: "pass", + packaged: true, + platform: "darwin", + nativeActivation: true, + mainWindowRestored: true, + hiddenWorkerPreserved: true, + }), + ) +} finally { + socket?.close() + + if (child.exitCode === null) { + child.kill("SIGTERM") + const timer = setTimeout(() => child.kill("SIGKILL"), 5000) + await child.exited + clearTimeout(timer) + } +} diff --git a/packages/desktop/scripts/copy-metainfo.ts b/packages/desktop/scripts/copy-metainfo.ts index 0ad4b3e426..fcc734aa12 100644 --- a/packages/desktop/scripts/copy-metainfo.ts +++ b/packages/desktop/scripts/copy-metainfo.ts @@ -1,12 +1,19 @@ import { resolveChannel } from "./utils" +import { desktopIdentity } from "./identity" const arg = process.argv[2] const channel = arg === "dev" || arg === "beta" || arg === "prod" ? arg : resolveChannel() -const appId = channel === "prod" ? "ai.opencode.desktop" : `ai.opencode.desktop.${channel}` +const identity = desktopIdentity(channel) -const productName = channel === "prod" ? "OpenCode" : `OpenCode ${channel.charAt(0).toUpperCase() + channel.slice(1)}` +const appId = identity.appId + +const productName = identity.productName + +const branded = process.env.CM_BRAND === "1" + +const repository = branded ? "https://github.com/trmosala/opencode" : "https://github.com/anomalyco/opencode" const summary = `Open source AI coding agent${channel !== "prod" ? ` (${channel})` : ""}` @@ -20,13 +27,13 @@ const xml = ` ${productName} ${summary} - - Anomaly Innovations Inc. + + ${branded ? "CookieMonster contributors" : "Anomaly Innovations Inc."}

- OpenCode is an open source agent that helps you write and run code with any AI model. + ${branded ? productName : "OpenCode"} is an open source agent that helps you write and run code with any AI model.

@@ -34,9 +41,9 @@ const xml = ` - https://github.com/anomalyco/opencode/issues - https://opencode.ai - https://github.com/anomalyco/opencode + ${repository}/issues + ${branded ? repository : "https://opencode.ai"} + ${repository} diff --git a/packages/desktop/scripts/identity.ts b/packages/desktop/scripts/identity.ts new file mode 100644 index 0000000000..c95cb46223 --- /dev/null +++ b/packages/desktop/scripts/identity.ts @@ -0,0 +1,11 @@ +export function desktopIdentity(channel: "dev" | "beta" | "prod") { + if (process.env.CM_BRAND === "1") { + return { appId: "com.ogilvy.cookiemonster", productName: "CookieMonster", packageName: "cookiemonster" } + } + + return { + appId: channel === "prod" ? "ai.opencode.desktop" : `ai.opencode.desktop.${channel}`, + productName: { prod: "OpenCode", beta: "OpenCode Beta", dev: "OpenCode Dev" }[channel], + packageName: channel === "prod" ? "opencode" : `opencode-${channel}`, + } +} diff --git a/packages/desktop/src/main/browser/delegation.test.ts b/packages/desktop/src/main/browser/delegation.test.ts index 0af1f1d142..e712c4e8f6 100644 --- a/packages/desktop/src/main/browser/delegation.test.ts +++ b/packages/desktop/src/main/browser/delegation.test.ts @@ -598,3 +598,18 @@ test("lost grant ACK is cleaned by executionID and cannot be retried after revok f.close() } }) + +test("delegated children cannot change desktop panels", async () => { + const f = fixture() + + try { + await f.grant() + expect(f.manager.authority("child").kind).toBe("delegated") + + for (const view of ["review", "hidden"] as const) { + expect(await f.route({ op: "set_panel", view })).toMatchObject({ ok: false, code: "access_denied" }) + } + } finally { + f.close() + } +}) diff --git a/packages/desktop/src/main/browser/delegation.ts b/packages/desktop/src/main/browser/delegation.ts index e2be740b7d..6d469a1cbb 100644 --- a/packages/desktop/src/main/browser/delegation.ts +++ b/packages/desktop/src/main/browser/delegation.ts @@ -19,6 +19,7 @@ import { import { browserOwnerScopeCurrent, type BrowserOwnerScope, type BrowserSessionResolver } from "./session-resolver" export type BrowserAuthority = { + readonly kind: "task" | "delegated" signal?: AbortSignal token?: object check(): void @@ -317,6 +318,7 @@ export function createBrowserDelegations( } return { + kind: "delegated", token: lease, signal: lease.controller.signal, check: requireActive, @@ -335,6 +337,7 @@ export function createBrowserDelegations( } return { + kind: "task", check: () => { if (closed) throw new Error("Sidecar closed") }, diff --git a/packages/desktop/src/main/browser/download-recovery-data.ts b/packages/desktop/src/main/browser/download-recovery-data.ts index d8a77b8dcf..b8a891b23f 100644 --- a/packages/desktop/src/main/browser/download-recovery-data.ts +++ b/packages/desktop/src/main/browser/download-recovery-data.ts @@ -1,6 +1,6 @@ import { createHash, randomUUID } from "node:crypto" import { constants } from "node:fs" -import { open, mkdir, unlink, stat, copyFile } from "node:fs/promises" +import { open, mkdir, unlink, stat, lstat, copyFile } from "node:fs/promises" import { basename, dirname, extname, isAbsolute, join } from "node:path" import { physicalDownloadPath } from "./download-path" @@ -19,6 +19,8 @@ export type DownloadRecovery = { sha256: string } +// This is the persisted recovery JSON decoder; representation checks here establish the complete contract below. +/* oxlint-disable anti-slop/no-runtime-typeof, anti-slop/no-unknown-parameters, anti-slop/no-unsafe-dictionary-type */ export function recoveryURL(value: unknown): value is string { if (typeof value !== "string" || value.length > 8192 || !URL.canParse(value)) return false const url = new URL(value) @@ -34,6 +36,7 @@ export function recoveryURL(value: unknown): value is string { export function recoveryData(value: unknown): DownloadRecovery | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) return + // SAFETY: The guard above excludes null, arrays, and primitives; every consumed property is checked below. const row = value as Record const directoryDev = recoveryFileID(row.directoryDev) const directoryIno = recoveryFileID(row.directoryIno) @@ -92,6 +95,8 @@ function recoveryFileID(value: unknown) { return value } +/* oxlint-enable anti-slop/no-runtime-typeof, anti-slop/no-unknown-parameters, anti-slop/no-unsafe-dictionary-type */ + export async function recoveryDestination( recovery: Pick, ) { @@ -218,7 +223,19 @@ export async function publishDownload( return destination } catch (error) { - if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST") throw error + // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Filesystem exceptions are untyped; inspect only the OS error code. + if (!error || typeof error !== "object" || !("code" in error)) throw error + + if (error.code === "EEXIST") continue + + // Windows reports an existing directory as EPERM rather than EEXIST. + if ( + process.platform === "win32" && + error.code === "EPERM" && + (await lstat(destination).catch(() => undefined))?.isDirectory() + ) + continue + throw error } } diff --git a/packages/desktop/src/main/browser/panel-authority.test.ts b/packages/desktop/src/main/browser/panel-authority.test.ts new file mode 100644 index 0000000000..24385911ee --- /dev/null +++ b/packages/desktop/src/main/browser/panel-authority.test.ts @@ -0,0 +1,59 @@ +import { expect, test } from "bun:test" +import { EventEmitter } from "node:events" +import { success, type BrowserIpcResult, type PanelRequest } from "@cookiemonster/cm-browser/protocol" +import { attachBrowserBridge } from "./bridge" +import { setBrowserAgentEnabled, setBrowserPanelHandler, setBrowserTaskPaused } from "./registry" + +test("ordinary bridge authority reaches the panel owner while paused and disabled tasks remain denied", async () => { + const replies: BrowserIpcResult[] = [] + const calls: { sessionID: string; request: PanelRequest }[] = [] + const child = Object.assign(new EventEmitter(), { postMessage: (reply: BrowserIpcResult) => replies.push(reply) }) + setBrowserAgentEnabled(true) + setBrowserPanelHandler(async (sessionID, request) => { + calls.push({ sessionID, request }) + + return success({ + tabID: "", + url: "", + title: "", + visibleText: "", + elements: [], + panelResult: + request.view === "browser" + ? { view: "browser", tabID: request.tabID, browserReady: true } + : { view: request.view, browserReady: false }, + }) + }) + const stop = attachBrowserBridge(child) + + const requests: PanelRequest[] = [ + { op: "set_panel", view: "review" }, + { op: "set_panel", view: "hidden" }, + { op: "set_panel", view: "browser", tabID: "authorized-tab" }, + ] + + try { + for (const request of requests) { + child.emit("message", { type: "browser_request", id: String(replies.length), sessionID: "panel-owner", request }) + await new Promise((resolve) => setImmediate(resolve)) + expect(replies.at(-1)?.response.ok).toBe(true) + expect(calls.at(-1)).toEqual({ sessionID: "panel-owner", request }) + } + + setBrowserTaskPaused("panel-owner", true) + child.emit("message", { type: "browser_request", id: "paused", sessionID: "panel-owner", request: requests[0] }) + await new Promise((resolve) => setImmediate(resolve)) + expect(replies.at(-1)?.response).toMatchObject({ ok: false, code: "access_denied" }) + setBrowserTaskPaused("panel-owner", false) + setBrowserAgentEnabled(false) + child.emit("message", { type: "browser_request", id: "disabled", sessionID: "panel-owner", request: requests[0] }) + await new Promise((resolve) => setImmediate(resolve)) + expect(replies.at(-1)?.response).toMatchObject({ ok: false, code: "access_denied" }) + expect(calls).toHaveLength(3) + } finally { + stop() + setBrowserAgentEnabled(true) + setBrowserTaskPaused("panel-owner", false) + setBrowserPanelHandler(undefined) + } +}) diff --git a/packages/desktop/src/main/browser/router.test.ts b/packages/desktop/src/main/browser/router.test.ts index 60fe862f9e..20f667ccf2 100644 --- a/packages/desktop/src/main/browser/router.test.ts +++ b/packages/desktop/src/main/browser/router.test.ts @@ -228,6 +228,7 @@ test.each(["check", "resolve"] as const)( { signal: controller.signal, authority: { + kind: "task", check() { if (stage === "check") throw new Error("Private authority detail") }, diff --git a/packages/desktop/src/main/browser/router.ts b/packages/desktop/src/main/browser/router.ts index de755bcd62..a5307d24f1 100644 --- a/packages/desktop/src/main/browser/router.ts +++ b/packages/desktop/src/main/browser/router.ts @@ -7,7 +7,6 @@ import { success, parseRequest, type BrowserIpcRequest, - type FrameRequest, type BrowserState, type ActionStatus, type ActionFailureCause, @@ -193,20 +192,27 @@ export async function routeBrowserRequest( : response.error : undefined - const bounded = { ...response, actionStatus, ...(actionCause ? { actionCause } : {}), ...(error ? { error } : {}) } - - return Buffer.byteLength(JSON.stringify(bounded)) <= MAX_SNAPSHOT_BYTES - ? bounded - : { - ...failure( - "unavailable", - dispatchAttempted - ? nativeT("desktop.browser.actionObservationFailed") - : "Browser response exceeds the size limit.", - ), - actionStatus: dispatchAttempted ? "dispatched_uncertain" : "not_dispatched", - ...(dispatchAttempted ? { actionCause: "observation_failed" as const } : {}), - } + const bounded = { ...response, actionStatus } + + if (actionCause) Object.assign(bounded, { actionCause }) + + if (error) Object.assign(bounded, { error }) + + if (Buffer.byteLength(JSON.stringify(bounded)) <= MAX_SNAPSHOT_BYTES) return bounded + + const oversized: Response = { + ...failure( + "unavailable", + dispatchAttempted + ? nativeT("desktop.browser.actionObservationFailed") + : "Browser response exceeds the size limit.", + ), + actionStatus: dispatchAttempted ? "dispatched_uncertain" : "not_dispatched", + } + + if (dispatchAttempted) Object.assign(oversized, { actionCause: "observation_failed" }) + + return oversized } if (validated.op === "grant_tabs" || validated.op === "revoke_tabs") @@ -324,18 +330,17 @@ export async function routeBrowserRequest( if (!deliveryCheck) throw new Error("Missing browser delivery authority") deliveryCheck() } catch { - return report({ - ...failure("unavailable", nativeT(browserDeliveryError(validated.op, response.result))), - ...(response.actionStatus - ? { - actionStatus: - response.actionStatus === "dispatched_observed" ? "dispatched_uncertain" : response.actionStatus, - } - : {}), - ...(response.actionStatus - ? { actionCause: "observation_failed" as const, error: nativeT("desktop.browser.actionObservationFailed") } - : {}), - }) + const unavailable = failure("unavailable", nativeT(browserDeliveryError(validated.op, response.result))) + + if (response.actionStatus) + Object.assign(unavailable, { + actionStatus: + response.actionStatus === "dispatched_observed" ? "dispatched_uncertain" : response.actionStatus, + actionCause: "observation_failed", + error: nativeT("desktop.browser.actionObservationFailed"), + }) + + return report(unavailable) } } @@ -372,7 +377,7 @@ async function route( if (browserTaskPaused(message.sessionID)) return failure("access_denied", nativeT("desktop.browser.taskPaused")) if (parsed.op === "set_panel") { - if (access) return failure("access_denied", nativeT("desktop.browser.operationUnavailable")) + if (access?.kind === "delegated") return failure("access_denied", nativeT("desktop.browser.operationUnavailable")) return routeBrowserPanel(message.sessionID, parsed, signal, deadline) } @@ -614,15 +619,18 @@ async function route( if (discovered.origin !== origin) throw new Error("Site tool origin changed") onScreenshotDelivery(authority) - return success({ + const state: BrowserState = { tabID: tab.id, url: origin, title: "", visibleText: "", elements: [], siteTools: discovered.tools, - ...(discovered.truncated ? { siteToolsTruncated: true } : {}), - }) + } + + if (discovered.truncated) Object.assign(state, { siteToolsTruncated: true }) + + return success(state) } const prepared = await prepareSiteTool(contents, request.toolRef, request.arguments, authority) @@ -632,6 +640,10 @@ async function route( if (request.op === "prepare_site_tool") { onScreenshotDelivery(authority) + const siteToolRequest = { name: prepared.name, origin, arguments: request.arguments } + + if (prepared.public.title) Object.assign(siteToolRequest, { title: prepared.public.title }) + return success({ tabID: tab.id, url: origin, @@ -644,12 +656,7 @@ async function route( toolRevision: prepared.revision, argumentHash: prepared.argumentHash, }, - siteToolRequest: { - name: prepared.name, - ...(prepared.public.title ? { title: prepared.public.title } : {}), - origin, - arguments: request.arguments, - }, + siteToolRequest, }) } @@ -686,15 +693,7 @@ async function route( } if ("frameRef" in request) { - const frame = await executeFrame( - tab, - request as FrameRequest, - authority, - deadline, - isAllowed, - markDispatched, - markObservation, - ) + const frame = await executeFrame(tab, request, authority, deadline, isAllowed, markDispatched, markObservation) const delivery = () => { authority() @@ -719,6 +718,9 @@ async function route( } // Keep busy/rendering ownership until actual native settlement, even after an early reply. + // SAFETY: Registered tabs own Electron WebContents, whose event methods are outside the narrower driver contract. + const consoleContents = contents as typeof contents & EventEmitter + const response = request.op === "observe_console" ? success({ @@ -728,12 +730,7 @@ async function route( visibleText: "", elements: [], diagnostics: { - console: await observeConsole( - contents as unknown as EventEmitter, - request.durationMs, - authority, - consent!.signal, - ), + console: await observeConsole(consoleContents, request.durationMs, authority, consent!.signal), }, }) : await execute( @@ -779,17 +776,19 @@ async function route( let page: BrowserState = response.result if (tab.frameSessions) { - while (Buffer.byteLength(JSON.stringify(page)) > 24 * 1024 && page.elements.length) { - page = { ...page, elements: page.elements.slice(0, -1), truncated: true } + const bounded = { ...page } + + while (Buffer.byteLength(JSON.stringify(bounded)) > 24 * 1024 && bounded.elements.length) { + bounded.elements = bounded.elements.slice(0, -1) + bounded.truncated = true } - while (Buffer.byteLength(JSON.stringify(page)) > 24 * 1024 && page.visibleText.length) { - page = { - ...page, - visibleText: page.visibleText.slice(0, Math.floor(page.visibleText.length / 2)), - truncated: true, - } + while (Buffer.byteLength(JSON.stringify(bounded)) > 24 * 1024 && bounded.visibleText.length) { + bounded.visibleText = bounded.visibleText.slice(0, Math.floor(bounded.visibleText.length / 2)) + bounded.truncated = true } + + page = bounded } const discovered = await discoverDocuments( diff --git a/packages/desktop/src/main/files/apps.ts b/packages/desktop/src/main/files/apps.ts index ac897fb91c..f7e6e7bb52 100644 --- a/packages/desktop/src/main/files/apps.ts +++ b/packages/desktop/src/main/files/apps.ts @@ -1,6 +1,7 @@ import { execFile } from "node:child_process" import util from "node:util" import { Effect, FileSystem, Path } from "effect" +import { nativeT } from "../native/translations" const execFilePromise = util.promisify(execFile) @@ -12,10 +13,42 @@ export const checkAppExists = Effect.fn("DesktopFiles.checkAppExists")(function* return yield* checkMacosApp(appName) }) +// The apps a renderer may open a path with: the editors and terminals the app offers to open a path in on each OS, +// named as `open -a` (macOS) or a PATH lookup (Windows, Linux) finds them. Other platforms get Linux's choices. +const OPEN_WITH_APPS = { + darwin: new Set([ + "Visual Studio Code", + "Cursor", + "Zed", + "TextMate", + "Antigravity", + "Terminal", + "iTerm", + "Ghostty", + "Warp", + "Xcode", + "Android Studio", + "Sublime Text", + ]), + win32: new Set(["code", "cursor", "zed", "powershell", "Sublime Text"]), + linux: new Set(["code", "cursor", "zed", "Sublime Text"]), +} + +/** + * The executable that opens a path with an allowed app: its name, or on Windows the executable main locates + * for it, or null when Windows cannot. Any other app fails with a message for the user, so the renderer never + * picks an executable. + */ export const resolveAppPath = Effect.fn("DesktopFiles.resolveAppPath")(function* (appName: string) { - if (process.platform !== "win32") return appName + const platform = process.platform === "darwin" || process.platform === "win32" ? process.platform : "linux" + + if (!OPEN_WITH_APPS[platform].has(appName)) { + return yield* Effect.fail(nativeT("desktop.openWith.error.appNotAllowed", { app: appName })) + } + + if (platform !== "win32") return appName - return yield* resolveWindowsAppPath(appName) + return yield* resolveWindowsAppPath(appName).pipe(Effect.orElseSucceed(() => null)) }) const checkMacosApp = Effect.fn("DesktopFiles.checkMacosApp")(function* (appName: string) { @@ -125,7 +158,11 @@ const resolveWindowsAppPath = Effect.fn("DesktopFiles.resolveWindowsAppPath")(fu if (key) { for (const file of paths) { - const dirs = [path.dirname(file), path.dirname(path.dirname(file)), path.dirname(path.dirname(path.dirname(file)))] + const dirs = [ + path.dirname(file), + path.dirname(path.dirname(file)), + path.dirname(path.dirname(path.dirname(file))), + ] for (const dir of dirs) { const entries = yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => [])) diff --git a/packages/desktop/src/main/files/index.ts b/packages/desktop/src/main/files/index.ts index dfb8f7430d..d9c7283062 100644 --- a/packages/desktop/src/main/files/index.ts +++ b/packages/desktop/src/main/files/index.ts @@ -6,6 +6,7 @@ import { Context, Effect, FileSystem, Layer, Path } from "effect" import type { DirectoryPickerOptions, FilePickerOptions, SaveFilePickerOptions } from "../../shared/ipc-contract" import { scoped } from "../native/logging" import { nativeT } from "../native/translations" +import { resolveAppPath } from "./apps" import { assertAttachmentBudget, createPickedFileAuthorizations, readAttachment } from "./attachment-picker" import { resolveExternalURL, resolveLocalFilePath } from "./external-url" @@ -87,16 +88,33 @@ function make(fs: FileSystem.FileSystem, path: Path.Path) { }), openPath: Effect.fn("DesktopFiles.openPath")(function* (target: string, application?: string) { if (!application) return yield* Effect.promise(() => shell.openPath(target)) - yield* Effect.tryPromise(() => - new Promise((resolve, reject) => { - const command = - process.platform === "darwin" - ? { file: "open", arguments: ["-a", application, target] } - : { file: application, arguments: [target] } - - execFile(command.file, command.arguments, (error) => (error ? reject(error) : resolve())) - }), + + // The app reads the target as an argument, and an absolute path never starts as an option. Windows apps also + // read a leading `/` as one, so there the target must be a drive or UNC path. + const absolute = + process.platform === "win32" ? /^(?:[A-Za-z]:[\\/]|\\\\[^\\/])/.test(target) : target.startsWith("/") + + if (!absolute) return yield* Effect.fail(nativeT("desktop.openWith.error.notAbsolute")) + + const executable = yield* resolveAppPath(application).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), ) + + // Windows opens with the default app when it cannot locate an allowed app. + if (!executable) return yield* Effect.promise(() => shell.openPath(target)) + // Only the rejections above reach the renderer as messages to show; a launch that fails stays a defect. + yield* Effect.tryPromise( + () => + new Promise((resolve, reject) => { + const command = + process.platform === "darwin" + ? { file: "open", arguments: ["-a", executable, target] } + : { file: executable, arguments: [target] } + + execFile(command.file, command.arguments, (error) => (error ? reject(error) : resolve())) + }), + ).pipe(Effect.orDie) }), revealPath: Effect.fn("DesktopFiles.revealPath")(function* (target: string) { const exists = yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false)) diff --git a/packages/desktop/src/main/ipc-handlers/app.ts b/packages/desktop/src/main/ipc-handlers/app.ts index 90e03c4de9..00a1b17b10 100644 --- a/packages/desktop/src/main/ipc-handlers/app.ts +++ b/packages/desktop/src/main/ipc-handlers/app.ts @@ -3,7 +3,7 @@ import { parseDesktopNativeBundle } from "@opencode/app/i18n/desktop-native" import { Effect } from "effect" import { AppRpcs } from "../../shared/ipc-rpc" import { openExternalURL } from "../files" -import { checkAppExists, resolveAppPath } from "../files/apps" +import { checkAppExists } from "../files/apps" import { setForceFocus } from "../native/debug" import { showCliInstaller } from "../native/install-cli" import { DesktopLogging, scoped } from "../native/logging" @@ -35,7 +35,6 @@ export const appHandlers = AppRpcs.toLayer( AppFinishFirstLaunchOnboarding: ({ createDefaultProject }) => finishFirstLaunchOnboarding(createDefaultProject).pipe(Effect.orDie), AppCheckAppExists: ({ appName }) => checkAppExists(appName).pipe(Effect.orDie), - AppResolveAppPath: ({ appName }) => resolveAppPath(appName).pipe(Effect.orDie), AppSetBackgroundColor: ({ color }) => Effect.sync(() => setBackgroundColor(color)), AppExportDebugLogs: () => logging.exportDebug, AppSetForceFocus: ({ enabled }, context) => promise(() => setForceFocus(sender(handoff, context), enabled)), diff --git a/packages/desktop/src/main/ipc-handlers/files.test.ts b/packages/desktop/src/main/ipc-handlers/files.test.ts new file mode 100644 index 0000000000..13b6aca45f --- /dev/null +++ b/packages/desktop/src/main/ipc-handlers/files.test.ts @@ -0,0 +1,281 @@ +// SAFETY: This fixture owns its synthetic renderer port, sender and launcher; partial shapes stand in for Electron's +// and child_process's. +import { afterAll, afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test" +import childProcess, { type ExecFileOptions } from "node:child_process" +import { EventEmitter } from "node:events" +import { join } from "node:path" +import { MessageChannel } from "node:worker_threads" +import { NodeFileSystem, NodePath } from "@effect/platform-node" +import { createDesktopNativeBundle, DESKTOP_NATIVE_ENGLISH } from "@opencode/app/i18n/desktop-native" +import { shell, type MessagePortMain, type WebContents } from "electron" +import { Layer, ManagedRuntime, Predicate } from "effect" +import { RpcServer, type RpcMessage } from "effect/rpc" +import { nativeT, setNativeTranslations } from "../native/translations" + +// Bun module mocks persist across files; isolate the process launcher from the desktop suite. +if (process.env.CM_OPEN_PATH_TEST_CHILD !== "1") { + test("FilesOpenPath launches only the applications main allows", () => { + const result = Bun.spawnSync([process.execPath, "test", "--preload", "./test/preload.ts", import.meta.path], { + cwd: join(import.meta.dir, "../../.."), + // No usable PATH, so a launch that misses the mock fails instead of opening an installed editor. + env: { ...process.env, CM_OPEN_PATH_TEST_CHILD: "1", PATH: "/nonexistent" }, + timeout: 15_000, + stdout: "pipe", + stderr: "pipe", + }) + + expect(result.exitCode, Buffer.concat([result.stdout, result.stderr]).toString()).toBe(0) + }, 20_000) +} else { + const launches: string[][] = [] + const execFile = mock(launch) + mock.module("node:child_process", () => ({ ...childProcess, execFile })) + // electron-log's main entry runs its renderer preload on import, which needs a renderer global. Nothing here logs + // through it. + mock.module("electron-log/main.js", () => ({ default: {} })) + const { FileRpcs } = await import("../../shared/ipc-rpc") + const { DesktopFiles } = await import("../files") + const { IpcPortHandoff, IpcServerProtocolLive } = await import("../ipc-transport") + const { fileHandlers } = await import("./files") + + // The renderer pushes the app's language to main. No message here equals its English, so a rejection that main + // hardcodes instead of translating fails. + setNativeTranslations(createDesktopNativeBundle("de", (key) => `de: ${DESKTOP_NATIVE_ENGLISH[key]}`)) + + const runtime = ManagedRuntime.make( + RpcServer.layer(FileRpcs).pipe( + Layer.provide(fileHandlers), + Layer.provide(DesktopFiles.layer), + Layer.provide(Layer.merge(NodeFileSystem.layer, NodePath.layer)), + Layer.provideMerge(IpcServerProtocolLive), + ), + ) + + const handoff = await runtime.runPromise(IpcPortHandoff) + const channel = new MessageChannel() + handoff.bind(rendererSender(1), serverPort(channel.port1)) + const platform = Object.getOwnPropertyDescriptor(process, "platform")! + let nextId = 0 + + // Each OS's open-with apps, named as the renderer sends them, and the commands main runs for each. + const systems = [ + { + platform: "darwin", + target: "/Users/dev/project", + apps: [ + "Visual Studio Code", + "Cursor", + "Zed", + "TextMate", + "Antigravity", + "Terminal", + "iTerm", + "Ghostty", + "Warp", + "Xcode", + "Android Studio", + "Sublime Text", + ], + launched: (app: string, target: string) => [["open", "-a", app, target]], + }, + { + platform: "win32", + target: "C:\\Users\\dev\\project", + apps: ["code", "cursor", "zed", "powershell", "Sublime Text"], + // Main locates the executable itself; the renderer sends only the app's name. + launched: (app: string, target: string) => [ + ["where", app], + [`C:\\Apps\\${app}.exe`, target], + ], + }, + { + platform: "linux", + target: "/home/dev/project", + apps: ["code", "cursor", "zed", "Sublime Text"], + launched: (app: string, target: string) => [[app, target]], + }, + ] + + const notAllowed = "desktop.openWith.error.appNotAllowed" as const + const notAbsolute = "desktop.openWith.error.notAbsolute" as const + + beforeEach(() => { + launches.length = 0 + execFile.mockImplementation(launch) + spyOn(shell, "openPath").mockImplementation(async (target) => { + launches.push(["shell.openPath", target]) + + return "" + }) + }) + + afterEach(() => { + mock.restore() + Object.defineProperty(process, "platform", platform) + }) + + afterAll(async () => { + channel.port2.close() + await runtime.dispose() + }) + + describe("FilesOpenPath", () => { + test.each(systems.flatMap((system) => system.apps.map((app) => ({ ...system, app }))))( + "opens with $app on $platform", + async (row) => { + Object.defineProperty(process, "platform", { value: row.platform }) + + expect(await openPath({ path: row.target, application: row.app })).toEqual(success(null)) + expect(launches).toEqual(row.launched(row.app, row.target)) + }, + ) + + test.each(systems)("opens with the default app on $platform", async (row) => { + Object.defineProperty(process, "platform", { value: row.platform }) + + expect(await openPath({ path: row.target })).toEqual(success("")) + expect(launches).toEqual([["shell.openPath", row.target]]) + }) + + test("opens with the default app when Windows cannot locate an allowed app", async () => { + Object.defineProperty(process, "platform", { value: "win32" }) + execFile.mockImplementationOnce((file, args, _options, done) => { + launches.push([file, ...args]) + done?.(new Error("not found")) + + return new childProcess.ChildProcess() + }) + + expect(await openPath({ path: "C:\\Users\\dev\\project", application: "Sublime Text" })).toEqual(success("")) + expect(launches).toEqual([ + ["where", "Sublime Text"], + ["shell.openPath", "C:\\Users\\dev\\project"], + ]) + }) + + test.each([ + // Executables, and apps main does not offer on that OS. Windows renderers used to send the resolved path. + { platform: "linux", path: "/home/dev/project", application: "/bin/sh", error: notAllowed }, + { platform: "linux", path: "/home/dev/project", application: "Terminal", error: notAllowed }, + { platform: "darwin", path: "/Users/dev/project", application: "Calculator", error: notAllowed }, + { platform: "win32", path: "C:\\project", application: "C:\\Windows\\System32\\cmd.exe", error: notAllowed }, + // Targets an app could read as an option, and relative ones. + { platform: "linux", path: "--help", application: "code", error: notAbsolute }, + { platform: "linux", path: "project", application: "code", error: notAbsolute }, + { platform: "darwin", path: "-W", application: "Terminal", error: notAbsolute }, + { platform: "win32", path: "/Command", application: "powershell", error: notAbsolute }, + { platform: "win32", path: "-NoProfile", application: "powershell", error: notAbsolute }, + ])("rejects $application for $path on $platform", async (row) => { + Object.defineProperty(process, "platform", { value: row.platform }) + + // The renderer rejects with this message, which the open-with menu shows in its toast. + expect(await openPath({ path: row.path, application: row.application })).toEqual( + failed(nativeT(row.error, { app: row.application })), + ) + expect(launches).toEqual([]) + }) + }) + + // Stands in for execFile. Main's Windows lookup runs `where` through util.promisify, which resolves with the + // callback's second argument, so it answers in execFile's promisified shape. Nothing native runs. + function launch(file: string, args: string[], options: ExecFileOptions | Done, done?: Done) { + launches.push([file, ...args]) + // SAFETY: execFile's overload supplies either its typed options object or its callback in this slot. + // oxlint-disable-next-line anti-slop/no-runtime-typeof + const callback = typeof options === "function" ? options : done + callback?.(null, file === "where" ? { stdout: `C:\\Apps\\${args[0]}.exe\r\n`, stderr: "" } : undefined) + + return new childProcess.ChildProcess() + } + + // SAFETY: this is the RPC wire format's plain encoded request, which the renderer posts as is. + /* oxlint-disable anti-slop-effect/no-manual-tagged-construction -- see SAFETY above */ + // Posts what src/renderer/ipc-client.ts posts for `api.openPath`, and settles as it does: on this request's exit, + // or on a defect, which ends every pending request. + function openPath(payload: RpcMessage.RequestEncoded["payload"]) { + const id = nextId++ + + return new Promise((resolve) => { + const settle = (value: Settled) => { + channel.port2.off("message", onMessage) + resolve(value) + } + + const onMessage = (message: RpcMessage.FromServerEncoded) => { + if (Predicate.isTagged(message, "Defect")) return settle(message) + + if (!Predicate.isTagged(message, "Exit") || Number(message.requestId) !== id) return + settle(message.exit) + } + + channel.port2.on("message", onMessage) + channel.port2.postMessage({ _tag: "Request", id, tag: "FilesOpenPath", payload, headers: [] }) + }) + } + /* oxlint-enable anti-slop-effect/no-manual-tagged-construction */ +} + +type Done = (error: Error | null, output?: { stdout: string; stderr: string }) => void + +type Settled = RpcMessage.ResponseExitEncoded["exit"] | Extract + +// SAFETY: these are the RPC wire format's plain encoded exits, which the tests expect as is. +/* oxlint-disable anti-slop-effect/no-manual-tagged-construction -- see SAFETY above */ +function success(value: A) { + return { _tag: "Success", value } as const +} + +function failed(error: E) { + return { _tag: "Failure", cause: [{ _tag: "Fail", error }] } as const +} +/* oxlint-enable anti-slop-effect/no-manual-tagged-construction */ + +function rendererSender(id: number) { + const events = new EventEmitter() + + // SAFETY: the transport reads only a sender's `id` and `isDestroyed`, and its `destroyed` event. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above + return { + id, + isDestroyed: () => false, + once: events.once.bind(events), + off: events.off.bind(events), + } as unknown as WebContents +} + +function serverPort(port: MessageChannel["port1"]) { + const listeners = new Map<(event: Electron.MessageEvent) => void, (data: Electron.MessageEvent["data"]) => void>() + + const fake = { + on(event: string, listener: (event: Electron.MessageEvent) => void) { + if (event !== "message") { + port.on(event, listener) + + return + } + + // SAFETY: the transport reads only the `data` of a message event. + const wrapped = (data: Electron.MessageEvent["data"]) => listener({ data } as Electron.MessageEvent) + listeners.set(listener, wrapped) + port.on("message", wrapped) + }, + off(event: string, listener: (event: Electron.MessageEvent) => void) { + if (event !== "message") { + port.off(event, listener) + + return + } + + const wrapped = listeners.get(listener) + + if (wrapped) port.off("message", wrapped) + }, + postMessage: port.postMessage.bind(port), + start: port.start.bind(port), + close: port.close.bind(port), + } + + // SAFETY: the transport uses only these methods of a port. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above + return fake as unknown as MessagePortMain +} diff --git a/packages/desktop/src/main/ipc-handlers/files.ts b/packages/desktop/src/main/ipc-handlers/files.ts index b576c5b704..ddf76169d1 100644 --- a/packages/desktop/src/main/ipc-handlers/files.ts +++ b/packages/desktop/src/main/ipc-handlers/files.ts @@ -19,9 +19,10 @@ export const fileHandlers = FileRpcs.toLayer( ) .pipe(Effect.orDie), FilesReadPickedFile: ({ token, path }, context) => - files - .readPickedFile(sender(handoff, context).id, token, path) - .pipe(Effect.map((buffer) => new Uint8Array(buffer)), Effect.orDie), + files.readPickedFile(sender(handoff, context).id, token, path).pipe( + Effect.map((buffer) => new Uint8Array(buffer)), + Effect.orDie, + ), FilesReleasePickedFiles: ({ token }, context) => Effect.sync(() => files.releasePickedFiles(sender(handoff, context).id, token)), FilesSaveFile: ({ options, content }) => files.saveFile(options, content).pipe(Effect.orDie), @@ -29,10 +30,7 @@ export const fileHandlers = FileRpcs.toLayer( FilesOpenBrowser: ({ url }) => (/^https?:/i.test(url) ? openExternalURL(url) : Effect.succeed(false)), FilesOpenLocalFile: ({ url }) => openLocalFileURL(url), FilesOpenPath: ({ path, application }) => - files.openPath(path, application).pipe( - Effect.map((result) => result ?? null), - Effect.orDie, - ), + files.openPath(path, application).pipe(Effect.map((result) => result ?? null)), FilesRevealPath: ({ path }) => files.revealPath(path), FilesReadClipboardImage: () => files.readClipboardImage(), FilesWriteClipboardText: ({ text }) => files.writeClipboardText(text), diff --git a/packages/desktop/src/main/lifecycle/activation.test.ts b/packages/desktop/src/main/lifecycle/activation.test.ts new file mode 100644 index 0000000000..d2fd290097 --- /dev/null +++ b/packages/desktop/src/main/lifecycle/activation.test.ts @@ -0,0 +1,110 @@ +import { expect, mock, spyOn, test } from "bun:test" +import { EventEmitter } from "node:events" +import { join } from "node:path" +import { app, BrowserWindow } from "electron" +import { Effect, Layer, ManagedRuntime } from "effect" + +if (process.env.CM_ACTIVATION_TEST_CHILD !== "1") { + test("activation restores main windows independently of hidden worker windows", () => { + const result = Bun.spawnSync([process.execPath, "test", "--preload", "./test/preload.ts", import.meta.path], { + cwd: join(import.meta.dir, "../../.."), + env: { ...process.env, CM_ACTIVATION_TEST_CHILD: "1" }, + timeout: 15_000, + stdout: "pipe", + stderr: "pipe", + }) + + expect(result.exitCode, Buffer.concat([result.stdout, result.stderr]).toString()).toBe(0) + }, 20_000) +} else { + test("Dock activation restores a main window with hidden workers and focuses an existing main window", async () => { + const events = new EventEmitter() + app.on = (name, listener) => { + events.on(name, listener) + + return app + } + + app.off = (name, listener) => { + events.off(name, listener) + + return app + } + + const main: BrowserWindow[] = [] + const shown = mock(() => {}) + const focused = mock(() => {}) + const restored = mock(() => {}) + + // SAFETY: This owned native stand-in supplies every operation used by the activation focus path. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- native stand-in, see SAFETY above + const window = { + isMinimized: () => true, + restore: restored, + show: shown, + focus: focused, + isFocused: () => false, + } as unknown as BrowserWindow + + // SAFETY: The baseline only counts these hidden native workers; the main-window fixture excludes them. + spyOn(BrowserWindow, "getAllWindows").mockReturnValue([{} as BrowserWindow]) + + const restore = mock(() => { + main.push(window) + + return main + }) + + mock.module("../windows", () => ({ + getMainWindows: () => main, + getLastFocusedWindow: () => main[0] ?? null, + getWindowByID: () => null, + makeMainWindows: () => Effect.succeed({ create: () => window, restore }), + setAppQuitting: () => {}, + setRelaunchHandler: () => () => {}, + })) + mock.module("../storage", () => ({ + DesktopStorage: { layer: Layer.empty }, + })) + mock.module("../native/logging", () => ({ + DesktopLogging: { layer: Layer.empty }, + scoped: (_scope: string, effect: Effect.Effect) => effect, + })) + mock.module("./onboarding", () => ({ + initializeFirstLaunchOnboarding: () => Effect.void, + })) + mock.module("../ipc-events", () => ({ emitIpcEvent: () => {} })) + const login = Promise.withResolvers() + + const requestLogin = mock(async (origin: string) => { + login.resolve(origin) + }) + + mock.module("#cm-wpp", () => ({ wpp: { requestLogin } })) + const { ApplicationLifecycle } = await import("./index") + const runtime = ManagedRuntime.make(ApplicationLifecycle.layer) + + try { + const lifecycle = await runtime.runPromise(ApplicationLifecycle.Service) + lifecycle.restoreWindows() + expect(restore).toHaveBeenCalledTimes(1) + main.length = 0 + events.emit("activate") + expect(restore).toHaveBeenCalledTimes(2) + expect(main).toHaveLength(1) + events.emit("activate") + expect(restore).toHaveBeenCalledTimes(2) + expect(restored).toHaveBeenCalledTimes(1) + expect(shown).toHaveBeenCalledTimes(1) + expect(focused).toHaveBeenCalledTimes(1) + events.emit("second-instance", {}, ["cm", "cookiemonster://wpp/login?origin=http%3A%2F%2F127.0.0.1%3A18787"]) + expect(await login.promise).toBe("http://127.0.0.1:18787") + expect(requestLogin).toHaveBeenCalledTimes(1) + expect(lifecycle.consumeInitialDeepLinks()).toEqual([]) + expect(focused).toHaveBeenCalledTimes(1) + } finally { + await runtime.dispose() + mock.restore() + } + }) +} diff --git a/packages/desktop/src/main/lifecycle/deep-link.test.ts b/packages/desktop/src/main/lifecycle/deep-link.test.ts index c6e4623950..fedc69257d 100644 --- a/packages/desktop/src/main/lifecycle/deep-link.test.ts +++ b/packages/desktop/src/main/lifecycle/deep-link.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test" -import { consoleReturnWindow } from "./deep-link" +import { consoleReturnWindow, wppLoginOrigin } from "./deep-link" describe("Console return deep links", () => { test("reads the originating Desktop window", () => { @@ -15,3 +15,20 @@ describe("Console return deep links", () => { expect(consoleReturnWindow("opencode://console/authorized")).toBeUndefined() }) }) + +test("WPP sign-in handoff carries only one bounded origin and no commands or secrets", () => { + expect(wppLoginOrigin("cookiemonster://wpp/login?origin=http%3A%2F%2F127.0.0.1%3A18787")).toBe( + "http://127.0.0.1:18787", + ) + + for (const url of [ + "https://wpp/login?origin=http://127.0.0.1:8787", + "cookiemonster://wpp/other?origin=http://127.0.0.1:8787", + "cookiemonster://wpp/login", + "cookiemonster://wpp/login?origin=a&origin=b", + "cookiemonster://wpp/login?origin=a&command=execute", + "cookiemonster://wpp/login?origin=a#fragment", + "cookiemonster://user@wpp/login?origin=a", + ]) + expect(wppLoginOrigin(url)).toBeUndefined() +}) diff --git a/packages/desktop/src/main/lifecycle/deep-link.ts b/packages/desktop/src/main/lifecycle/deep-link.ts index a1fd4133a7..0f188fa741 100644 --- a/packages/desktop/src/main/lifecycle/deep-link.ts +++ b/packages/desktop/src/main/lifecycle/deep-link.ts @@ -12,3 +12,27 @@ export function consoleReturnWindow(value: string) { return } } + +export function wppLoginOrigin(value: string) { + try { + const url = new URL(value) + + if (url.protocol !== "cookiemonster:" || url.hostname !== "wpp" || url.pathname !== "/login") return + + if ( + url.username || + url.password || + url.port || + url.hash || + [...url.searchParams.keys()].some((key) => key !== "origin") + ) + return + const origins = url.searchParams.getAll("origin") + + if (origins.length !== 1 || !origins[0] || origins[0].length > 256) return + + return origins[0] + } catch { + return + } +} diff --git a/packages/desktop/src/main/lifecycle/environment.ts b/packages/desktop/src/main/lifecycle/environment.ts index 4b9b4e1fd4..9bca700f29 100644 --- a/packages/desktop/src/main/lifecycle/environment.ts +++ b/packages/desktop/src/main/lifecycle/environment.ts @@ -39,6 +39,13 @@ export const prepareDesktop = Effect.gen(function* () { if (app.isPackaged || process.env.OPENCODE_DESKTOP_DISABLE_PROTOCOL_REGISTRATION !== "1") app.setAsDefaultProtocolClient("opencode") + + if ( + import.meta.env.CM_BRAND && + import.meta.env.CM_WPP && + (app.isPackaged || process.env.OPENCODE_DESKTOP_DISABLE_PROTOCOL_REGISTRATION !== "1") + ) + app.setAsDefaultProtocolClient("cookiemonster") const runFork = Effect.runForkWith(yield* Effect.context()) setProtocolReporter((level, message, data) => runFork(scoped("protocol", level === "error" ? Effect.logError(message, data) : Effect.logWarning(message, data))), @@ -50,7 +57,7 @@ export const prepareDesktop = Effect.gen(function* () { export const loadProxyEnvironment = Effect.gen(function* () { yield* Effect.try(() => { ensureLoopbackNoProxy() - // Electron 41.2 has a newer Node API than the current @types/node package. + // SAFETY: Electron 41.2+ provides this Node API, which is missing from the current @types/node package. const proxyAwareHttp = http as typeof http & { setGlobalProxyFromEnv(): void } proxyAwareHttp.setGlobalProxyFromEnv() }).pipe(Effect.catch((error) => Effect.logWarning("failed to load proxy environment", { error }))) diff --git a/packages/desktop/src/main/lifecycle/index.ts b/packages/desktop/src/main/lifecycle/index.ts index 5ed4fb312b..35d722161f 100644 --- a/packages/desktop/src/main/lifecycle/index.ts +++ b/packages/desktop/src/main/lifecycle/index.ts @@ -8,11 +8,20 @@ import { emitIpcEvent } from "../ipc-events" import { DesktopLogging, scoped } from "../native/logging" import { DesktopStorage } from "../storage" import { safeWebContentsURL } from "../windows/state" -import { getLastFocusedWindow, getWindowByID, makeMainWindows, setAppQuitting, setRelaunchHandler } from "../windows" +import { + getLastFocusedWindow, + getMainWindows, + getWindowByID, + // SAFETY: This existing factory runs once inside this scoped lifecycle layer and propagates its requirements. + // oxlint-disable-next-line anti-slop-effect/no-service-constructor-imports + makeMainWindows, + setAppQuitting, + setRelaunchHandler, +} from "../windows" import { marks } from "./marks" import { initializeFirstLaunchOnboarding } from "./onboarding" import { Shutdown } from "./shutdown" -import { consoleReturnWindow } from "./deep-link" +import { consoleReturnWindow, wppLoginOrigin } from "./deep-link" export interface Interface { readonly relaunch: () => void @@ -45,10 +54,25 @@ const runtime = Layer.effect( } const emitDeepLinks = (urls: string[]) => { - if (!urls.length) return - pendingDeepLinks.push(...urls) + const links = urls.filter((url) => { + if (!url.startsWith("cookiemonster://")) return true + const origin = wppLoginOrigin(url) - const target = urls.flatMap((url) => { + if (origin) + runFork( + Effect.tryPromise(async () => { + const { wpp } = await import("#cm-wpp") + await wpp?.requestLogin(origin) + }).pipe(Effect.catch(() => Effect.logWarning("WPP sign-in could not be opened"))), + ) + + return false + }) + + if (!links.length) return + pendingDeepLinks.push(...links) + + const target = links.flatMap((url) => { const id = consoleReturnWindow(url) const win = id ? getWindowByID(id) : null @@ -57,7 +81,7 @@ const runtime = Layer.effect( const win = target ?? getLastFocusedWindow() - if (win) emitIpcEvent(win.webContents, new DeepLinksOpened({ urls })) + if (win) emitIpcEvent(win.webContents, new DeepLinksOpened({ urls: links })) return win } @@ -77,7 +101,7 @@ const runtime = Layer.effect( } const secondInstance = (_event: Event, argv: string[]) => { - const urls = argv.filter((arg) => arg.startsWith("opencode://")) + const urls = argv.filter((arg) => arg.startsWith("opencode://") || arg.startsWith("cookiemonster://")) if (urls.length) { runFork(Effect.logInfo("deep link received via second-instance", { urls })) @@ -130,7 +154,15 @@ const runtime = Layer.effect( } const activate = () => { - if (BrowserWindow.getAllWindows().length === 0) restoreWindows() + const main = getMainWindows() + + if (main.length === 0) { + restoreWindows() + + return + } + + focusWindow(main.find((win) => win.isFocused()) ?? main[0]) } const resetRelaunchHandler = setRelaunchHandler(relaunch) diff --git a/packages/desktop/src/main/macos-user-install.test.ts b/packages/desktop/src/main/macos-user-install.test.ts index 51002ca8df..4ccb9fe908 100644 --- a/packages/desktop/src/main/macos-user-install.test.ts +++ b/packages/desktop/src/main/macos-user-install.test.ts @@ -113,7 +113,8 @@ test("confirmation, failure handling and lock handoff precede launch", async () } }) -test("replaces the whole app, retains the previous bundle and preserves unrelated data", async () => { +// These filesystem fixtures require POSIX directory handles and permissions. +test.skipIf(process.platform === "win32")("replaces the whole app, retains the previous bundle and preserves unrelated data", async () => { const root = await mkdtemp(join(tmpdir(), "cm-install-test-")) const source = join(root, "Source", "CookieMonster.app") const applications = join(root, "Applications With Spaces") @@ -151,7 +152,7 @@ test("replaces the whole app, retains the previous bundle and preserves unrelate } }) -test("moves read-only bundle roots and restores their modes without changing the source", async () => { +test.skipIf(process.platform === "win32")("moves read-only bundle roots and restores their modes without changing the source", async () => { const root = await mkdtemp(join(tmpdir(), "cm-install-test-")) const source = join(root, "Source") const destination = join(root, "CookieMonster.app") @@ -208,7 +209,7 @@ test("moves read-only bundle roots and restores their modes without changing the } }) -test("backup cleanup is best-effort and retries after a later successful replacement", async () => { +test.skipIf(process.platform === "win32")("backup cleanup is best-effort and retries after a later successful replacement", async () => { const root = await mkdtemp(join(tmpdir(), "cm-install-test-")) const source = join(root, "Source") const destination = join(root, "CookieMonster.app") @@ -269,7 +270,7 @@ test("backup cleanup is best-effort and retries after a later successful replace } }) -test("pruning leaves unowned, changed, symlinked and unrelated backup candidates alone", async () => { +test.skipIf(process.platform === "win32")("pruning leaves unowned, changed, symlinked and unrelated backup candidates alone", async () => { for (const change of [ "unmarked", "extra", @@ -365,7 +366,7 @@ test("pruning leaves unowned, changed, symlinked and unrelated backup candidates } }) -test("backup ownership-write failure leaves older backups without failing the published install", async () => { +test.skipIf(process.platform === "win32")("backup ownership-write failure leaves older backups without failing the published install", async () => { const root = await mkdtemp(join(tmpdir(), "cm-install-test-")) const source = join(root, "Source") const destination = join(root, "CookieMonster.app") @@ -409,7 +410,7 @@ test("backup ownership-write failure leaves older backups without failing the pu } }) -test("failed staging, moves, permission cleanup and recovery never prune completed backups", async () => { +test.skipIf(process.platform === "win32")("failed staging, moves, permission cleanup and recovery never prune completed backups", async () => { for (const failure of ["staging", "backup", "publication", "recovery", "chmod", "close"]) { const root = await mkdtemp(join(tmpdir(), "cm-install-test-")) const source = join(root, "Source") @@ -513,7 +514,7 @@ test("failed staging, moves, permission cleanup and recovery never prune complet } }) -test("backup handle cleanup failures restore the moved app before reporting failure", async () => { +test.skipIf(process.platform === "win32")("backup handle cleanup failures restore the moved app before reporting failure", async () => { for (const failure of ["chmod", "close"]) { const root = await mkdtemp(join(tmpdir(), "cm-install-test-")) const source = join(root, "Source") @@ -578,7 +579,7 @@ test("backup handle cleanup failures restore the moved app before reporting fail } }) -test("publication handle cleanup failures retain the complete new app and any previous backup", async () => { +test.skipIf(process.platform === "win32")("publication handle cleanup failures retain the complete new app and any previous backup", async () => { for (const existing of [false, true]) { for (const failure of ["chmod", "close"]) { const root = await mkdtemp(join(tmpdir(), "cm-install-test-")) @@ -649,7 +650,7 @@ test("publication handle cleanup failures retain the complete new app and any pr } }) -test("permission and move failures are not masked by mode restoration or handle close failures", async () => { +test.skipIf(process.platform === "win32")("permission and move failures are not masked by mode restoration or handle close failures", async () => { for (const failure of ["chmod", "rename"]) { const root = await mkdtemp(join(tmpdir(), "cm-install-test-")) const source = join(root, "Source") @@ -711,7 +712,7 @@ test("permission and move failures are not masked by mode restoration or handle } }) -test("failed staging copies leave the installed app intact and can be retried", async () => { +test.skipIf(process.platform === "win32")("failed staging copies leave the installed app intact and can be retried", async () => { const root = await mkdtemp(join(tmpdir(), "cm-install-test-")) const source = join(root, "Source") const destination = join(root, "CookieMonster.app") @@ -796,7 +797,7 @@ test("rejects self-replacement and destinations changed while copying", async () } }) -test("concurrent first installs publish only one complete bundle", async () => { +test.skipIf(process.platform === "win32")("concurrent first installs publish only one complete bundle", async () => { const root = await mkdtemp(join(tmpdir(), "cm-install-test-")) const source = join(root, "Source") const destination = join(root, "CookieMonster.app") @@ -823,7 +824,7 @@ test("concurrent first installs publish only one complete bundle", async () => { } }) -test("publication failures restore the old app or retain its backup without overwriting concurrent data", async () => { +test.skipIf(process.platform === "win32")("publication failures restore the old app or retain its backup without overwriting concurrent data", async () => { for (const scenario of ["restore", "restore-fails", "concurrent-destination"]) { const root = await mkdtemp(join(tmpdir(), "cm-install-test-")) const source = join(root, "Source") diff --git a/packages/desktop/src/main/windows/security.test.ts b/packages/desktop/src/main/windows/security.test.ts new file mode 100644 index 0000000000..68cd36014b --- /dev/null +++ b/packages/desktop/src/main/windows/security.test.ts @@ -0,0 +1,69 @@ +import { expect, mock, test } from "bun:test" +import { EventEmitter } from "node:events" +import type { BrowserWindow, Session, WebContents } from "electron" +import { allowRendererPermissions } from "./security" + +test("session permission handlers cover every live main window and reject other frames and contents", () => { + const session = { + setPermissionRequestHandler: mock( + (_handler: NonNullable[0]>) => {}, + ), + setPermissionCheckHandler: mock((_handler: NonNullable[0]>) => {}), + } + + const first = window(session, 1) + const second = window(session, 2) + const unrelated = window(session, 3) + allowRendererPermissions(first.win) + allowRendererPermissions(second.win) + allowRendererPermissions(first.win) + expect(session.setPermissionRequestHandler).toHaveBeenCalledTimes(1) + expect(session.setPermissionCheckHandler).toHaveBeenCalledTimes(1) + const request = session.setPermissionRequestHandler.mock.calls[0][0] + const check = session.setPermissionCheckHandler.mock.calls[0][0] + + for (const permission of ["notifications", "clipboard-sanitized-write"] as const) { + for (const [fixture, allowed] of [ + [first, true], + [second, true], + [unrelated, false], + ] as const) { + const callback = mock((_allowed: boolean) => {}) + request(fixture.contents, permission, callback, { requestingUrl: "oc://renderer/index.html", isMainFrame: true }) + expect(callback).toHaveBeenCalledWith(allowed) + expect(check(fixture.contents, permission, "oc://renderer", { isMainFrame: true })).toBe(allowed) + } + + expect(check(null, permission, "oc://renderer", { isMainFrame: true })).toBe(false) + expect(check(first.contents, permission, "https://untrusted.example", { isMainFrame: true })).toBe(false) + expect(check(first.contents, permission, "oc://renderer", { isMainFrame: false })).toBe(false) + const subframe = mock((_allowed: boolean) => {}) + request(first.contents, permission, subframe, { requestingUrl: "oc://renderer/index.html", isMainFrame: false }) + expect(subframe).toHaveBeenCalledWith(false) + } + + expect(check(first.contents, "media", "oc://renderer", { isMainFrame: true })).toBe(false) + second.close() + expect(check(second.contents, "notifications", "oc://renderer", { isMainFrame: true })).toBe(false) + expect(check(first.contents, "notifications", "oc://renderer", { isMainFrame: true })).toBe(true) + first.close() + expect(check(first.contents, "notifications", "oc://renderer", { isMainFrame: true })).toBe(false) +}) + +function window(session: Pick, id: number) { + const state = { destroyed: false } + const contents = Object.assign(new EventEmitter(), { id, session, isDestroyed: () => state.destroyed }) + + // SAFETY: This fixture owns these native stand-ins. The handler reads session, lifetime, and event methods only. + return { + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- native stand-in, see SAFETY above + win: { webContents: contents } as unknown as BrowserWindow, + // SAFETY: This same owned object supplies lifetime, identity and session; it is never passed to Electron. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions + contents: contents as unknown as WebContents, + close() { + state.destroyed = true + contents.emit("destroyed") + }, + } +} diff --git a/packages/desktop/src/main/windows/security.ts b/packages/desktop/src/main/windows/security.ts index 100ff0e3e1..9c18303f28 100644 --- a/packages/desktop/src/main/windows/security.ts +++ b/packages/desktop/src/main/windows/security.ts @@ -1,27 +1,43 @@ -import type { BrowserWindow } from "electron" +import type { BrowserWindow, Session, WebContents } from "electron" import { SidecarCredentials } from "../service/sidecar-credentials" import { addRendererHeaders, hasHeader, upsertHeader } from "./headers" import { isRendererUrl } from "./scheme" const rendererPermissions = new Set(["clipboard-sanitized-write", "notifications"]) +const rendererWindows = new WeakMap>() + export function allowRendererPermissions(win: BrowserWindow) { - const webContentsId = win.webContents.id - win.webContents.session.setPermissionRequestHandler((webContents, permission, callback, details) => { + const contents = win.webContents + const session = contents.session + const registered = rendererWindows.get(session) ?? new Set() + + if (registered.has(contents)) return + registered.add(contents) + contents.once("destroyed", () => registered.delete(contents)) + + if (rendererWindows.has(session)) return + rendererWindows.set(session, registered) + + session.setPermissionRequestHandler((webContents, permission, callback, details) => { callback( - rendererPermissions.has(permission) && isRendererUrl(details.requestingUrl) && webContents.id === webContentsId, + rendererPermissions.has(permission) && + registered.has(webContents) && + !webContents.isDestroyed() && + details.isMainFrame && + isRendererUrl(details.requestingUrl), ) }) - win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { - if (!rendererPermissions.has(permission)) return false + session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { + if (!rendererPermissions.has(permission) || !webContents || !registered.has(webContents)) return false - if (webContents && webContents.id !== webContentsId) return false + if (webContents.isDestroyed() || !details.isMainFrame) return false return isRendererUrl(details.requestingUrl) || isRendererUrl(requestingOrigin) }) } -export function wireNavigationPolicy(win: BrowserWindow, openExternalURL: (url: string) => unknown) { +export function wireNavigationPolicy(win: BrowserWindow, openExternalURL: (url: string) => void) { win.webContents.setWindowOpenHandler(({ url }) => { if (!isRendererUrl(url)) openExternalURL(url) diff --git a/packages/desktop/src/main/wpp.ts b/packages/desktop/src/main/wpp.ts index 4e8f2f3cdf..a79210707f 100644 --- a/packages/desktop/src/main/wpp.ts +++ b/packages/desktop/src/main/wpp.ts @@ -1,3 +1,4 @@ +import type { WebContents } from "electron" import type { WppAuthState } from "../shared/wpp-auth" export type WppIntegration = { @@ -7,10 +8,12 @@ export type WppIntegration = { get(): WppAuthState check(): Promise } + requestLogin(origin: string): Promise toggleLogin(): void toggleWindows(): boolean - isLoggedWorker(contents: object): boolean + isLoggedWorker(contents: WebContents): boolean setWorkerLogWriter( + // oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Matches the optional backend diagnostic callback; values go only to the log sink. writer: (id: number, event: string, details: Record, level?: "info" | "warn" | "error") => void, ): void } diff --git a/packages/desktop/src/renderer/api-types.ts b/packages/desktop/src/renderer/api-types.ts index f5cc8b3146..a1ea3be20c 100644 --- a/packages/desktop/src/renderer/api-types.ts +++ b/packages/desktop/src/renderer/api-types.ts @@ -26,7 +26,6 @@ export type ElectronAPI = { isFirstLaunchOnboardingPending(): Promise finishFirstLaunchOnboarding(createDefaultProject: boolean): Promise checkAppExists(appName: string): Promise - resolveAppPath(appName: string): Promise storeItems(name: string): Promise<{ items: Record; revision: number }> storeUpdate(name: string, insert: Record, remove: string[]): Promise storeClear(name: string): Promise diff --git a/packages/desktop/src/renderer/api.ts b/packages/desktop/src/renderer/api.ts index 67da18b43f..624d47df91 100644 --- a/packages/desktop/src/renderer/api.ts +++ b/packages/desktop/src/renderer/api.ts @@ -55,7 +55,6 @@ export const api: ElectronAPI = { finishFirstLaunchOnboarding: (createDefaultProject) => invoke("AppFinishFirstLaunchOnboarding", { createDefaultProject }), checkAppExists: (appName) => invoke("AppCheckAppExists", { appName }), - resolveAppPath: (appName) => invoke("AppResolveAppPath", { appName }), // The first read of a namespace the preload already fetched is served from that snapshot; later // reads (a window re-opening a namespace) go to the main process as usual. storeItems: (name) => diff --git a/packages/desktop/src/renderer/platform/files.test.ts b/packages/desktop/src/renderer/platform/files.test.ts index 5f8a018f15..953283894d 100644 --- a/packages/desktop/src/renderer/platform/files.test.ts +++ b/packages/desktop/src/renderer/platform/files.test.ts @@ -24,7 +24,6 @@ function fileApi(events: string[]): Parameters[0] { openExternal: () => {}, openBrowser: async () => true, openLocalFile: () => {}, - resolveAppPath: async () => null, openPath: async () => undefined, revealPath: async () => false, readClipboardImage: async () => null, @@ -37,7 +36,7 @@ function fileApi(events: string[]): Parameters[0] { describe("desktop attachment files", () => { test("returns the native browser launch result and forwards clipboard text", async () => { const events: string[] = [] - const files = createDesktopFiles({ ...fileApi(events), openBrowser: async () => false }, "macos") + const files = createDesktopFiles({ ...fileApi(events), openBrowser: async () => false }) expect(await files.openBrowser("https://opencode.ai/console")).toBe(false) await files.writeClipboardText("ses_123") @@ -46,7 +45,7 @@ describe("desktop attachment files", () => { test("reads selected files sequentially and releases the token", async () => { const events: string[] = [] - const files = createDesktopFiles(fileApi(events), "windows") + const files = createDesktopFiles(fileApi(events)) await files.openAttachmentPickerDialog({}, async (file) => { events.push(`file:${file.name}`) @@ -63,7 +62,7 @@ describe("desktop attachment files", () => { test("releases the token when a selected file callback fails", async () => { const events: string[] = [] - const files = createDesktopFiles(fileApi(events), "windows") + const files = createDesktopFiles(fileApi(events)) await expect( files.openAttachmentPickerDialog({}, async () => { diff --git a/packages/desktop/src/renderer/platform/files.ts b/packages/desktop/src/renderer/platform/files.ts index d4735fea56..fcb0afc8c5 100644 --- a/packages/desktop/src/renderer/platform/files.ts +++ b/packages/desktop/src/renderer/platform/files.ts @@ -1,8 +1,6 @@ import type { Platform } from "@opencode/app/desktop" import type { ElectronAPI } from "../api-types" -type DesktopOS = Extract["os"] - type DesktopFileAPI = Pick< ElectronAPI, | "openDirectoryPicker" @@ -14,14 +12,13 @@ type DesktopFileAPI = Pick< | "openExternal" | "openBrowser" | "openLocalFile" - | "resolveAppPath" | "openPath" | "revealPath" | "readClipboardImage" | "writeClipboardText" > -export function createDesktopFiles(api: DesktopFileAPI, os: DesktopOS) { +export function createDesktopFiles(api: DesktopFileAPI) { const attachmentPaths = new WeakMap() const openDirectoryPickerDialog: Extract["openDirectoryPickerDialog"] = async ( @@ -63,15 +60,9 @@ export function createDesktopFiles(api: DesktopFileAPI, os: DesktopOS) { openExternal: (url: string) => api.openExternal(url), openBrowser: (url: string) => api.openBrowser(url), openLocalFile: (url: string) => api.openLocalFile(url), + // Main owns the allowed apps and resolves their executables, so only the app's name crosses. async openPath(path: string, app?: string) { - if (os !== "windows") { - await api.openPath(path, app) - - return - } - - const resolvedApp = app ? await api.resolveAppPath(app).catch(() => null) : null - await api.openPath(path, resolvedApp ?? undefined) + await api.openPath(path, app) }, async revealPath(path: string) { return api.revealPath(path) diff --git a/packages/desktop/src/renderer/platform/index.ts b/packages/desktop/src/renderer/platform/index.ts index 9eecedc2d8..a9ff953ccf 100644 --- a/packages/desktop/src/renderer/platform/index.ts +++ b/packages/desktop/src/renderer/platform/index.ts @@ -34,7 +34,7 @@ export function createDesktopPlatform(api: ElectronAPI, windowState: DesktopWind version: windowState.version, windowID: windowState.id, - ...createDesktopFiles(api, os), + ...createDesktopFiles(api), ...createDesktopStorage(api), exportDebugLogs: () => api.exportDebugLogs(), setForceFocus: (enabled) => api.setForceFocus(enabled), diff --git a/packages/desktop/src/shared/cm-native.ts b/packages/desktop/src/shared/cm-native.ts index 805a6d1a56..8f530f73ce 100644 --- a/packages/desktop/src/shared/cm-native.ts +++ b/packages/desktop/src/shared/cm-native.ts @@ -632,6 +632,8 @@ export const DESKTOP_NATIVE_ENGLISH = { "The saved login operation was cancelled or could not complete. Keep the WPP Okta sign-in window visible, unlock saved passwords, and use the account shown on the page. The page or account may have changed. No sign-in was submitted by CookieMonster.", "desktop.browser.account.username": "Username", "desktop.browser.account.password": "Password", + "desktop.openWith.error.appNotAllowed": "Application is not allowed: {{app}}", + "desktop.openWith.error.notAbsolute": "Open target must be an absolute path", } as const export type DesktopNativeKey = keyof typeof DESKTOP_NATIVE_ENGLISH @@ -640,6 +642,7 @@ export type DesktopNativeMessages = Record export type DesktopNativeBundle = { locale: DesktopNativeLocale; messages: DesktopNativeMessages } +// SAFETY: DesktopNativeKey is exactly the key union of this owned literal. export const DESKTOP_NATIVE_KEYS = Object.keys(DESKTOP_NATIVE_ENGLISH) as DesktopNativeKey[] export const DESKTOP_NATIVE_MAX_PAYLOAD_BYTES = 64 * 1024 @@ -650,10 +653,13 @@ export function createDesktopNativeBundle( ): DesktopNativeBundle { return { locale, + // SAFETY: Every declared key occurs once and the translator returns a string for each. messages: Object.fromEntries(DESKTOP_NATIVE_KEYS.map((key) => [key, translate(key)])) as DesktopNativeMessages, } } +// SAFETY: This IPC decoder checks payload size, locale, exact keys and string values before returning a bundle. +/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type */ export function parseDesktopNativeBundle(value: unknown): DesktopNativeBundle | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) return undefined @@ -663,11 +669,13 @@ export function parseDesktopNativeBundle(value: unknown): DesktopNativeBundle | return undefined } + // SAFETY: The guard above establishes an object; its fields remain unknown until checked below. const bundle = value as { locale?: unknown; messages?: unknown } if (!DESKTOP_NATIVE_LOCALES.some((locale) => locale === bundle.locale)) return undefined if (!bundle.messages || typeof bundle.messages !== "object" || Array.isArray(bundle.messages)) return undefined + // SAFETY: Messages is a non-array object; this boundary checks every unknown member below. const messages = bundle.messages as Record const keys = Object.keys(messages) @@ -677,8 +685,10 @@ export function parseDesktopNativeBundle(value: unknown): DesktopNativeBundle | if (!keys.every((key) => key in DESKTOP_NATIVE_ENGLISH)) return undefined + // SAFETY: The bounded payload now has a supported locale, the exact native keys and only string values. return bundle as DesktopNativeBundle } +/* oxlint-enable anti-slop/no-unknown-parameters, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type */ export function formatDesktopNativeMessage(message: string, params?: Record) { if (!params) return message diff --git a/packages/desktop/src/shared/ipc-rpc/app.ts b/packages/desktop/src/shared/ipc-rpc/app.ts index 3e6de686cb..2181de5b72 100644 --- a/packages/desktop/src/shared/ipc-rpc/app.ts +++ b/packages/desktop/src/shared/ipc-rpc/app.ts @@ -27,11 +27,6 @@ export const AppCheckAppExists = Rpc.make("AppCheckAppExists", { success: Schema.Boolean, }) -export const AppResolveAppPath = Rpc.make("AppResolveAppPath", { - payload: { appName: Schema.String }, - success: Schema.NullOr(Schema.String), -}) - export const AppSetBackgroundColor = Rpc.make("AppSetBackgroundColor", { payload: { color: Schema.String }, }) @@ -67,7 +62,6 @@ export const AppRpcs = RpcGroup.make( AppIsFirstLaunchOnboardingPending, AppFinishFirstLaunchOnboarding, AppCheckAppExists, - AppResolveAppPath, AppSetBackgroundColor, AppExportDebugLogs, AppSetForceFocus, diff --git a/packages/desktop/src/shared/ipc-rpc/files.ts b/packages/desktop/src/shared/ipc-rpc/files.ts index 5d934b1ac2..5942e23a6d 100644 --- a/packages/desktop/src/shared/ipc-rpc/files.ts +++ b/packages/desktop/src/shared/ipc-rpc/files.ts @@ -66,6 +66,8 @@ export const FilesOpenLocalFile = Rpc.make("FilesOpenLocalFile", { export const FilesOpenPath = Rpc.make("FilesOpenPath", { payload: { path: Schema.String, application: Schema.optional(Schema.String) }, success: Schema.NullOr(Schema.String), + // A rejected app or target: a message in the app's language for the renderer to show. + error: Schema.String, }) export const FilesRevealPath = Rpc.make("FilesRevealPath", { diff --git a/packages/desktop/wpp/bun.lock b/packages/desktop/wpp/bun.lock index 46f895f554..40e80f1040 100644 --- a/packages/desktop/wpp/bun.lock +++ b/packages/desktop/wpp/bun.lock @@ -5,11 +5,11 @@ "": { "name": "@cookiemonster/desktop-wpp", "dependencies": { - "@cookiemonster/wpp": "git+ssh://git@github.com/trmosala/CM-WPP-Bits.git#2e470e8190c319f47c86dfb83af829eb869908bf", + "@cookiemonster/wpp": "git+ssh://git@github.com/trmosala/CM-WPP-Bits.git#8bb2cd4e7d0588c3ef37735453830e7206f5a455", }, }, }, "packages": { - "@cookiemonster/wpp": ["@cookiemonster/wpp@git+ssh://git@github.com/trmosala/CM-WPP-Bits.git#2e470e8190c319f47c86dfb83af829eb869908bf", { "peerDependencies": { "@opencode/plugin": "*", "@opencode/schema": "*", "electron": "44.4.5" }, "optionalPeers": ["@opencode/plugin", "@opencode/schema", "electron"] }, "2e470e8190c319f47c86dfb83af829eb869908bf"], + "@cookiemonster/wpp": ["@cookiemonster/wpp@git+ssh://git@github.com/trmosala/CM-WPP-Bits.git#8bb2cd4e7d0588c3ef37735453830e7206f5a455", { "peerDependencies": { "@opencode/plugin": "*", "@opencode/schema": "*", "electron": "44.4.5" }, "optionalPeers": ["@opencode/plugin", "@opencode/schema", "electron"] }, "8bb2cd4e7d0588c3ef37735453830e7206f5a455"], } } diff --git a/packages/desktop/wpp/contracts.test.ts b/packages/desktop/wpp/contracts.test.ts index f00d8a4f42..97dc5ff109 100644 --- a/packages/desktop/wpp/contracts.test.ts +++ b/packages/desktop/wpp/contracts.test.ts @@ -2,7 +2,9 @@ import { test } from "bun:test" if (process.env.CM_WPP === "1") { await import("./provider.fixture") + await import("./host-boundaries.fixture.mjs") await import("./responses.fixture.mjs") await import("./legacy-config.fixture") } + if (process.env.CM_WPP !== "1") test.skip("WPP contracts require the optional integration and CM_WPP=1", () => {}) diff --git a/packages/desktop/wpp/host-boundaries.fixture.mjs b/packages/desktop/wpp/host-boundaries.fixture.mjs new file mode 100644 index 0000000000..33b5bfe5b6 --- /dev/null +++ b/packages/desktop/wpp/host-boundaries.fixture.mjs @@ -0,0 +1,245 @@ +import { expect, test } from "bun:test" +import { mkdtemp, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { Schema } from "effect" +import { OpenCode } from "@opencode/sdk" +import { WriteTool } from "../../core/src/tool/plugin/write.ts" +import { EditTool } from "../../core/src/tool/plugin/edit.ts" +import { SessionCompaction } from "../../core/src/session/compaction.ts" +import cookiemonster from "@cookiemonster/wpp/plugin" +import { publishProxyKey } from "@cookiemonster/wpp/proxy/localKey.mjs" +import { formatJsonToolCall } from "@cookiemonster/wpp/proxy/jsonToolFormat.mjs" +import { formatAnthropicToolCall } from "@cookiemonster/wpp/proxy/anthropicToolFormat.mjs" +import { normalizeAssistantMessage } from "@cookiemonster/wpp/proxy/toolCallNormalizer.mjs" +import { normalizeToolCallArguments } from "@cookiemonster/wpp/proxy/openaiCompat.mjs" +import { handleResponses } from "@cookiemonster/wpp/proxy/responses.mjs" + +test("WPP history roundtrips preserve actual V2 write/edit inputs and reject null strings", () => { + for (const format of [formatJsonToolCall, formatAnthropicToolCall]) { + for (const owner of [WriteTool, EditTool]) { + const tools = [ + { + type: "function", + function: { name: owner.name, parameters: Schema.toJsonSchemaDocument(owner.Input).schema }, + }, + ] + + for (const text of [ + "001", + "true", + "null", + '{"value":1}', + "```js\nconst x = 1\n```\n", + "C:\\Users\\日本\\file.txt\r\n", + ]) { + const input = + owner === WriteTool + ? { path: "test.txt", content: text } + : { path: "test.txt", oldString: text, newString: `${text} changed`, replaceAll: false } + + const result = normalizeAssistantMessage( + format({ id: "call_stable", function: { name: owner.name, arguments: JSON.stringify(input) } }), + { tools }, + ) + + normalizeToolCallArguments(result.tool_calls, tools) + expect(result.tool_calls).toHaveLength(1) + expect(result.tool_calls[0].id).toBe("call_stable") + expect(Schema.decodeUnknownSync(owner.Input)(JSON.parse(result.tool_calls[0].function.arguments))).toEqual( + input, + ) + } + + const input = + owner === WriteTool + ? { path: "test.txt", content: null } + : { path: "test.txt", oldString: null, newString: "replacement" } + + const result = normalizeAssistantMessage( + format({ function: { name: owner.name, arguments: JSON.stringify(input) } }), + { tools }, + ) + + normalizeToolCallArguments(result.tool_calls, tools) + const args = JSON.parse(result.tool_calls[0].function.arguments) + expect(args[owner === WriteTool ? "content" : "oldString"]).toBeNull() + expect(() => Schema.decodeUnknownSync(owner.Input)(args)).toThrow() + } + } +}) + +test("real V2 initial/update compaction prompts survive Responses translation without chat affinity", async () => { + const previous = process.env.O1_CODE_PROXY_LOGS + process.env.O1_CODE_PROXY_LOGS = "0" + + try { + for (const update of [false, true]) { + for (const kind of ["compaction", "primary"]) { + const calls = [] + + const response = { + body: "", + setHeader() {}, + writeHead() {}, + end(text = "") { + this.body += text + }, + } + + await handleResponses( + { headers: { "x-opencode-request-kind": kind } }, + response, + { + model: "CM_Opus5.5-XHigh", + input: SessionCompaction.buildPrompt(update), + stream: false, + }, + { + bridge: { + hasSession: () => true, + run: async (text, options) => { + calls.push({ prompt: JSON.parse(text), options }) + + return { response: { finalText: "## Objective\nKeep the work.", source: "network", toolCallParts: {} } } + }, + }, + }, + ) + expect(calls).toHaveLength(1) + expect(calls[0].prompt.purpose === "compaction").toBe(kind === "compaction") + + if (kind === "compaction") { + expect(calls[0].options.continueThread).toBe(false) + expect(calls[0].options.sessionKey).toBe("") + } + + expect(JSON.parse(response.body).output[0].content[0].text).toContain("Keep the work.") + } + } + } finally { + if (previous === undefined) delete process.env.O1_CODE_PROXY_LOGS + else process.env.O1_CODE_PROXY_LOGS = previous + } +}) + +test.each(["native", "packaged"])( + "the live V2 %s provider rereads a rotated user key without restarting its backend", + async (kind) => { + const directory = await mkdtemp(join(tmpdir(), "wpp-managed-provider-")) + const previousHome = process.env.XDG_CONFIG_HOME + const previousPort = process.env.O1_CODE_PROXY_PORT + process.env.XDG_CONFIG_HOME = directory + const keys = [] + const headers = [] + + const server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + async fetch(request) { + headers.push(request.headers) + + if (request.headers.get("authorization") !== `Bearer ${keys.at(-1)}`) + return new Response("unauthorized", { status: 401 }) + const body = await request.json() + + const message = { + type: "message", + id: `msg_${headers.length}`, + role: "assistant", + status: "completed", + content: [{ type: "output_text", text: "Managed credential accepted.", annotations: [] }], + } + + const response = { + id: `resp_${headers.length}`, + object: "response", + created_at: 0, + status: "completed", + model: body.model, + output: [message], + usage: { input_tokens: 10, output_tokens: 2, total_tokens: 12 }, + } + + return new Response( + [ + { type: "response.created", response: { ...response, status: "in_progress", output: [] } }, + { + type: "response.output_item.added", + output_index: 0, + item: { ...message, status: "in_progress", content: [] }, + }, + { + type: "response.content_part.added", + output_index: 0, + content_index: 0, + item_id: message.id, + part: { type: "output_text", text: "", annotations: [] }, + }, + { + type: "response.output_text.delta", + output_index: 0, + content_index: 0, + item_id: message.id, + delta: "Managed credential accepted.", + }, + { type: "response.output_item.done", output_index: 0, item: message }, + { type: "response.completed", response }, + ] + .map( + (event, sequence_number) => + `event: ${event.type}\ndata: ${JSON.stringify({ ...event, sequence_number })}\n\n`, + ) + .join(""), + { headers: { "content-type": "text/event-stream" } }, + ) + }, + }) + + process.env.O1_CODE_PROXY_PORT = String(server.port) + keys.push(publishProxyKey(server.url.origin)) + + try { + await using host = await OpenCode.create({ + config: { + directory, + project: false, + content: JSON.stringify({ + model: "cookiemonster/CM_GPT6_Sol_High", + providers: { cookiemonster: { settings: { baseURL: `${server.url}v1` } } }, + plugins: + kind === "packaged" ? [new URL("../resources/cm-plugins/provider/", import.meta.url).pathname] : [], + }), + }, + models: { fetch: false }, + fs: { filewatcher: false }, + plugins: kind === "native" ? [cookiemonster] : [], + }) + + const session = await host.sessions.create({ title: "Managed local credential", location: { directory } }) + + for (const text of ["First request", "Second request after key rotation"]) { + if (headers.length) keys.push(publishProxyKey(server.url.origin)) + await host.sessions.prompt({ sessionID: session.id, text }) + await host.sessions.wait({ sessionID: session.id }) + expect((await host.sessions.get({ sessionID: session.id })).outcome).toBe("succeeded") + } + + expect(headers).toHaveLength(2) + expect(keys[0] === keys[1]).toBe(false) + expect(headers[0].get("authorization") === `Bearer ${keys[0]}`).toBe(true) + expect(headers[1].get("authorization") === `Bearer ${keys[1]}`).toBe(true) + expect(headers.map((value) => value.get("x-opencode-request-kind"))).toEqual(["primary", "primary"]) + } finally { + server.stop(true) + + if (previousHome === undefined) delete process.env.XDG_CONFIG_HOME + else process.env.XDG_CONFIG_HOME = previousHome + + if (previousPort === undefined) delete process.env.O1_CODE_PROXY_PORT + else process.env.O1_CODE_PROXY_PORT = previousPort + await rm(directory, { recursive: true, force: true }) + } + }, + 30_000, +) diff --git a/packages/desktop/wpp/index.mjs b/packages/desktop/wpp/index.mjs index e0b26e588b..0dbdc9e3a3 100644 --- a/packages/desktop/wpp/index.mjs +++ b/packages/desktop/wpp/index.mjs @@ -1,4 +1,5 @@ import { startWppBridge } from "@cookiemonster/wpp" +import { requestProxyLogin } from "@cookiemonster/wpp/proxy/localKey.mjs" import { wppAuth, openWppLogin, toggleWppLogin } from "@cookiemonster/wpp/session" import { toggleWorkerWindows } from "@cookiemonster/wpp/worker-pool" import { DEFAULT_MODEL_ID } from "@cookiemonster/wpp/proxy/modelProfiles.mjs" @@ -8,6 +9,7 @@ import { attachWppLoginControls } from "../src/main/wpp-integration/login-contro export const wpp = { model: `cookiemonster/${DEFAULT_MODEL_ID}`, auth: wppAuth, + requestLogin: requestProxyLogin, toggleLogin: toggleWppLogin, toggleWindows: toggleWorkerWindows, isLoggedWorker, diff --git a/packages/desktop/wpp/package.json b/packages/desktop/wpp/package.json index 5ad96ed277..c86ac3d564 100644 --- a/packages/desktop/wpp/package.json +++ b/packages/desktop/wpp/package.json @@ -3,6 +3,6 @@ "private": true, "type": "module", "dependencies": { - "@cookiemonster/wpp": "git+ssh://git@github.com/trmosala/CM-WPP-Bits.git#2e470e8190c319f47c86dfb83af829eb869908bf" + "@cookiemonster/wpp": "git+ssh://git@github.com/trmosala/CM-WPP-Bits.git#8bb2cd4e7d0588c3ef37735453830e7206f5a455" } } diff --git a/packages/desktop/wpp/provider.fixture.ts b/packages/desktop/wpp/provider.fixture.ts index d84f903ab6..e177d0e347 100644 --- a/packages/desktop/wpp/provider.fixture.ts +++ b/packages/desktop/wpp/provider.fixture.ts @@ -10,6 +10,7 @@ import { MODEL_IDS } from "@cookiemonster/wpp/proxy/modelProfiles.mjs" test("V2 registers the CookieMonster roster, optional desktop setup and official Figma tools and skills", async () => { const directory = await mkdtemp(join(tmpdir(), "cm-v2-plugins-")) + try { await using host = await OpenCode.create({ config: { @@ -23,6 +24,7 @@ test("V2 registers the CookieMonster roster, optional desktop setup and official fs: { filewatcher: false }, plugins: [figma], }) + const models = (await host.model.list({ location: { directory } })).data expect( models @@ -68,6 +70,7 @@ test("V2 registers the CookieMonster roster, optional desktop setup and official test("bundled CM provider exposes optional desktop setup without enabling desktop access", async () => { const directory = await mkdtemp(join(tmpdir(), "cm-computer-use-")) + try { await using host = await OpenCode.create({ config: { @@ -78,6 +81,7 @@ test("bundled CM provider exposes optional desktop setup without enabling deskto models: { fetch: false }, fs: { filewatcher: false }, }) + expect( (await host.model.list({ location: { directory } })).data.some((model) => model.providerID === "cookiemonster"), ).toBe(true) @@ -103,6 +107,7 @@ test.each(["native", "legacy"] as const)( async (kind) => { const directory = await mkdtemp(join(tmpdir(), "cm-v2-request-")) const headers: Headers[] = [] + const server = Bun.serve({ port: 0, async fetch(request) { @@ -110,6 +115,7 @@ test.each(["native", "legacy"] as const)( const body: unknown = await request.json() expect(body).toMatchObject({ model: "CM_GPT6_Sol_High", stream: true }) headers.push(request.headers) + const image = { type: "image_generation_call", id: `image_${headers.length}`, @@ -117,6 +123,7 @@ test.each(["native", "legacy"] as const)( output_format: "png", result: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=", } + const response = { id: `resp_${headers.length}`, object: "response", @@ -126,6 +133,7 @@ test.each(["native", "legacy"] as const)( output: [image], usage: { input_tokens: 10, output_tokens: 2, total_tokens: 12 }, } + return new Response( [ { type: "response.created", response: { ...response, status: "in_progress", output: [] } }, @@ -146,6 +154,7 @@ test.each(["native", "legacy"] as const)( ) }, }) + try { await using host = await OpenCode.create({ config: { @@ -176,7 +185,9 @@ test.each(["native", "legacy"] as const)( fs: { filewatcher: false }, plugins: [cookiemonster], }) + const session = await host.sessions.create({ title: "WPP transport", location: { directory } }) + for (const text of ["Generate an image", "Generate another image"]) { await host.sessions.prompt({ sessionID: session.id, text }) await host.sessions.wait({ sessionID: session.id }) @@ -200,10 +211,12 @@ test.each(["native", "legacy"] as const)( ), ).toBe(true) } + expect(headers).toHaveLength(2) expect(headers[0].get("x-opencode-runtime-id")).toMatch(/^[a-f\d-]{36}$/) expect(headers[1].get("x-opencode-runtime-id")).toBe(headers[0].get("x-opencode-runtime-id")) expect(headers[0].get("x-opencode-client")).toBeTruthy() + expect(headers.map((value) => value.get("x-opencode-request-kind"))).toEqual(["primary", "primary"]) } finally { server.stop(true) await rm(directory, { recursive: true, force: true }) @@ -215,6 +228,7 @@ test("packaged CM plugins activate with the complete official Figma skill bundle const directory = await mkdtemp(join(tmpdir(), "cm-v2-packaged-")) const resources = new URL("../resources/cm-plugins/", import.meta.url) const source = await Bun.file(new URL("figma/skills-source.json", resources)).json() + try { await using host = await OpenCode.create({ config: { @@ -227,6 +241,7 @@ test("packaged CM plugins activate with the complete official Figma skill bundle models: { fetch: false }, fs: { filewatcher: false }, }) + expect( (await host.model.list({ location: { directory } })).data.some((model) => model.providerID === "cookiemonster"), ).toBe(true) diff --git a/packages/gui-extensions/src/sdk/host-apis.ts b/packages/gui-extensions/src/sdk/host-apis.ts index e1d73599c6..aedabf4120 100644 --- a/packages/gui-extensions/src/sdk/host-apis.ts +++ b/packages/gui-extensions/src/sdk/host-apis.ts @@ -916,7 +916,8 @@ export interface Desktop { * Opens a path with an app, or with the default app. * * @param path - An absolute path. - * @param app - The app's name or path; omit it for the default app. + * @param app - The name of an editor or terminal the desktop offers on this OS; omit it for the default app. Any + * other app, or a relative path with an app, rejects with a message to show the user. */ launch(path: string, app?: string): Promise /** diff --git a/packages/server/test/config.test.ts b/packages/server/test/config.test.ts index 6bb6fec5a6..300f6f5a6f 100644 --- a/packages/server/test/config.test.ts +++ b/packages/server/test/config.test.ts @@ -181,6 +181,8 @@ it.live("persists a skill toggle across locations and preserves other configurat }) } }), + // Allow watched-server lifecycle overhead outside the per-update five-second polls. + 15_000, ) function isRecord(value: unknown): value is Record { diff --git a/packages/server/test/worktree.test.ts b/packages/server/test/worktree.test.ts index a50d5122b1..e8cf4ffdb7 100644 --- a/packages/server/test/worktree.test.ts +++ b/packages/server/test/worktree.test.ts @@ -45,48 +45,52 @@ it.live("list reads saved inventory even when its checkout is missing, without b }), ) -it.live("refresh discovers both clones while list alone never discovers external worktrees", () => - Effect.gen(function* () { - const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-worktree-clones-"))) - const first = path.join(tmp.path, "first") - const second = path.join(tmp.path, "second") - const a = path.join(tmp.path, "a") - const b = path.join(tmp.path, "b") - yield* Effect.promise(async () => { - await fs.mkdir(first) - await initRepo(first) - await $`git remote add origin https://github.com/example/clones.git`.cwd(first).quiet() - await $`git clone --no-hardlinks ${first} ${second}`.quiet() - await $`git remote set-url origin https://github.com/example/clones.git`.cwd(second).quiet() - }) - const server = yield* startServer(path.join(tmp.path, "config")) - const api = OpenCode.make({ baseUrl: server.base, headers: server.headers }) - yield* Effect.promise(async () => { - const session = await api.session.create({ location: { directory: first } }) - const other = await api.session.create({ location: { directory: second } }) - const projectID = session.projectID - expect(other.projectID).toBe(projectID) - await $`git worktree add --detach ${a} HEAD`.cwd(first).quiet() - await $`git worktree add --detach ${b} HEAD`.cwd(second).quiet() - expect(await api.worktree.list({ projectID })).toHaveLength(2) - await api.worktree.refresh({ projectID }) - expect(await api.worktree.list({ projectID })).toEqual( - expect.arrayContaining([ - { directory: first }, - { directory: second }, - { directory: a, strategy: "git" }, - { directory: b, strategy: "git" }, - ]), - ) - await fs.rm(second, { recursive: true }) - await $`git worktree remove ${a}`.cwd(first).quiet() - await api.worktree.refresh({ projectID }) - const rows = await api.worktree.list({ projectID }) - expect(rows).not.toContainEqual({ directory: a, strategy: "git" }) - expect(rows).not.toContainEqual({ directory: second }) - expect(rows).toContainEqual({ directory: b, strategy: "git" }) - }) - }), +// This fixture boots a server and several Git processes; cold Windows startup can exceed five seconds. +it.live( + "refresh discovers both clones while list alone never discovers external worktrees", + () => + Effect.gen(function* () { + const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-worktree-clones-"))) + const first = path.join(tmp.path, "first") + const second = path.join(tmp.path, "second") + const a = path.join(tmp.path, "a") + const b = path.join(tmp.path, "b") + yield* Effect.promise(async () => { + await fs.mkdir(first) + await initRepo(first) + await $`git remote add origin https://github.com/example/clones.git`.cwd(first).quiet() + await $`git clone --no-hardlinks ${first} ${second}`.quiet() + await $`git remote set-url origin https://github.com/example/clones.git`.cwd(second).quiet() + }) + const server = yield* startServer(path.join(tmp.path, "config")) + const api = OpenCode.make({ baseUrl: server.base, headers: server.headers }) + yield* Effect.promise(async () => { + const session = await api.session.create({ location: { directory: first } }) + const other = await api.session.create({ location: { directory: second } }) + const projectID = session.projectID + expect(other.projectID).toBe(projectID) + await $`git worktree add --detach ${a} HEAD`.cwd(first).quiet() + await $`git worktree add --detach ${b} HEAD`.cwd(second).quiet() + expect(await api.worktree.list({ projectID })).toHaveLength(2) + await api.worktree.refresh({ projectID }) + expect(await api.worktree.list({ projectID })).toEqual( + expect.arrayContaining([ + { directory: first }, + { directory: second }, + { directory: a, strategy: "git" }, + { directory: b, strategy: "git" }, + ]), + ) + await fs.rm(second, { recursive: true }) + await $`git worktree remove ${a}`.cwd(first).quiet() + await api.worktree.refresh({ projectID }) + const rows = await api.worktree.list({ projectID }) + expect(rows).not.toContainEqual({ directory: a, strategy: "git" }) + expect(rows).not.toContainEqual({ directory: second }) + expect(rows).toContainEqual({ directory: b, strategy: "git" }) + }) + }), + 15_000, ) it.live("remove loads canonical strategies and enforces project ownership", () => diff --git a/packages/storybook/.storybook/main.ts b/packages/storybook/.storybook/main.ts index f7fc034e7a..e650cb0e47 100644 --- a/packages/storybook/.storybook/main.ts +++ b/packages/storybook/.storybook/main.ts @@ -31,17 +31,22 @@ export default defineMain({ "../../gui-extensions/src/**/*.stories.@(js|jsx|mjs|ts|tsx)", ], async viteFinal(config) { - const { mergeConfig, searchForWorkspaceRoot } = await import("vite") - const merged = mergeConfig(config, { + const { mergeConfig, normalizePath, searchForWorkspaceRoot } = await import("vite") + return mergeConfig(config, { plugins: [tailwindcss(), playgroundCss()], + // The previous directory alias kept Solid Query unbundled. + optimizeDeps: { + exclude: ["@tanstack/solid-query"], + // Page fixtures and built-in renderers load outside the story entry graph. + entries: [ + normalizePath(path.resolve(here, "../../app/component-tests/*.fixture.tsx")), + normalizePath(path.resolve(extensions, "renderer.ts")), + ], + }, resolve: { - dedupe: ["solid-js", "solid-js/web", "@solidjs/meta"], + dedupe: ["solid-js", "solid-js/web", "@solidjs/meta", "@tanstack/solid-query"], alias: [ { find: "@solidjs/router", replacement: path.resolve(mocks, "solid-router.tsx") }, - { - find: "@tanstack/solid-query", - replacement: path.resolve(here, "../../app/node_modules/@tanstack/solid-query"), - }, { find: /^@\/providers\/models\/selection$/, replacement: path.resolve(mocks, "app/context/local.ts") }, { find: /^@\/workspaces\/files\/model$/, replacement: path.resolve(mocks, "app/context/file.ts") }, { find: /^@\/shell\/state\/layout$/, replacement: path.resolve(mocks, "app/context/layout.ts") }, @@ -73,10 +78,5 @@ export default defineMain({ }, }, }) - merged.plugins = merged.plugins?.flat(8).filter((plugin) => { - if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return true - return plugin.name !== "storybook:optimize-deps-plugin" - }) - return merged }, }) diff --git a/patches/@corvu%2Fdrawer@0.2.4.patch b/patches/@corvu%2Fdrawer@0.2.4.patch new file mode 100644 index 0000000000..9fec8eb662 --- /dev/null +++ b/patches/@corvu%2Fdrawer@0.2.4.patch @@ -0,0 +1,54 @@ +diff --git a/dist/index.js b/dist/index.js +index c5248382bac4a58b510b48e023e27d14b89c390c..d7166616257b473ca56c7969e9e861ee00be9bd0 100644 +--- a/dist/index.js ++++ b/dist/index.js +@@ -477,6 +477,7 @@ var DrawerRoot = (props) => { + if (_open) { + setTransitionAwareOpen(true); + afterPaint(() => { ++ if (!open()) return; + batch(() => { + setTransitionState("opening"); + setActiveSnapPoint(localProps.defaultSnapPoint); +@@ -492,8 +493,12 @@ var DrawerRoot = (props) => { + setActiveSnapPoint(0); + }); + afterPaint(() => { ++ if (open()) return; + const transitionDuration = parseFloat(drawerStyles().transitionDuration); +- if (transitionDuration === 0) { ++ // Closing before the opening paint produces no transitionend event. ++ if (transitionDuration === 0 || !dialogContext()?.contentRef()?.getAnimations().some( ++ animation => animation.playState === "running" || animation.playState === "paused" ++ )) { + closeDrawer(); + } + }); +diff --git a/dist/index.jsx b/dist/index.jsx +index fa3ca91ca526e9c11a10819a8bda27dcbb884af7..f0974f9d9fd3ac39a6e9fbaa53729b8bcaef31bd 100644 +--- a/dist/index.jsx ++++ b/dist/index.jsx +@@ -567,6 +567,7 @@ var DrawerRoot = (props) => { + if (_open) { + setTransitionAwareOpen(true); + afterPaint(() => { ++ if (!open()) return; + batch2(() => { + setTransitionState("opening"); + setActiveSnapPoint(localProps.defaultSnapPoint); +@@ -584,10 +585,14 @@ var DrawerRoot = (props) => { + setActiveSnapPoint(0); + }); + afterPaint(() => { ++ if (open()) return; + const transitionDuration = parseFloat( + drawerStyles().transitionDuration + ); +- if (transitionDuration === 0) { ++ // Closing before the opening paint produces no transitionend event. ++ if (transitionDuration === 0 || !dialogContext()?.contentRef()?.getAnimations().some( ++ animation => animation.playState === "running" || animation.playState === "paused" ++ )) { + closeDrawer(); + } + });