From 0996030161d57ce129553e3f0fa68d7d7dbf10f3 Mon Sep 17 00:00:00 2001
From: Aarav Sareen <96787824+arvsrn@users.noreply.github.com>
Date: Fri, 13 Nov 2026 00:01:25 +0530
Subject: [PATCH 01/42] feat(app): show a free limit panel in place of the
composer (#63531)
---
packages/app/e2e/regression/composer.spec.ts | 6 +-
packages/app/src/runtime/i18n/en.ts | 5 +
.../src/session/composer/free-limit-panel.tsx | 133 ++++++++++++++++++
packages/app/src/session/composer/region.tsx | 29 ++--
.../src/session/usage-exceeded-dialogs.tsx | 11 +-
5 files changed, 173 insertions(+), 11 deletions(-)
create mode 100644 packages/app/src/session/composer/free-limit-panel.tsx
diff --git a/packages/app/e2e/regression/composer.spec.ts b/packages/app/e2e/regression/composer.spec.ts
index d4b120493029..4e819b704ae0 100644
--- a/packages/app/e2e/regression/composer.spec.ts
+++ b/packages/app/e2e/regression/composer.spec.ts
@@ -149,7 +149,7 @@ test("closing the @ menu aborts its session search", async ({ page }) => {
}
})
-test("the free usage limit opens the Go dialog once, leaves a readable notice, and restores the prompt", async ({
+test("the free usage limit opens the Go dialog once, swaps the composer for the free limit panel, and restores the prompt", async ({
page,
context,
}) => {
@@ -251,7 +251,9 @@ test("the free usage limit opens the Go dialog once, leaves a readable notice, a
const upsell = page.getByRole("dialog", { name: "Free limit reached" })
await expect(upsell).toContainText("Your free messages reset at")
await expect(page.getByText(/^You've used today's free messages\. They reset at /)).toBeVisible()
- await expect(view.editor).toHaveText("Refactor the parser")
+ // With no paid provider the panel stands in for the composer until Go is connected.
+ await expect(page.locator('[data-component="session-free-limit"]')).toContainText("Free usage resets at")
+ await expect(view.editor).toHaveCount(0)
await expect(page.getByText("Free usage limit reached.")).toHaveCount(0)
// Subscribe -> Go API key -> Continue switches the model in the current session without opening a new draft tab.
diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts
index 6fb9d989c706..a73a7832e456 100644
--- a/packages/app/src/runtime/i18n/en.ts
+++ b/packages/app/src/runtime/i18n/en.ts
@@ -636,6 +636,11 @@ export const dict = {
"session.background.moveRunning": "Move to background",
"session.background.moveInline": "Press {{keybind}} to move running work to the background",
"command.session.background": "Move to background",
+ "session.freeLimit.title": "Free limit reached",
+ "session.freeLimit.reset": "Free usage resets at {{time}}. Connect a provider or subscribe to Go to continue.",
+ "session.freeLimit.noReset": "Connect a provider or subscribe to Go to continue.",
+ "session.freeLimit.connect": "Connect provider",
+ "session.freeLimit.subscribe": "Subscribe to Go ยท $10/mo",
"session.goLimit.title": "Go usage limit reached.",
"session.goLimit.titleNamed": "Go {{name}} usage limit reached.",
"session.goLimit.reset": "It resets at {{time}}.",
diff --git a/packages/app/src/session/composer/free-limit-panel.tsx b/packages/app/src/session/composer/free-limit-panel.tsx
new file mode 100644
index 000000000000..eb60da3d16b8
--- /dev/null
+++ b/packages/app/src/session/composer/free-limit-panel.tsx
@@ -0,0 +1,133 @@
+import { createSignal, onCleanup, Show } from "solid-js"
+import { Schema } from "effect"
+import { Button } from "@opencode/ui/button"
+import { useDialog } from "@opencode/ui/context/dialog"
+import { useLanguage } from "@/runtime/i18n/language"
+import { usePlatform } from "@/runtime/platform/platform"
+import { Persist, persisted } from "@/runtime/persistence/storage"
+import { Persistence } from "@/runtime/persistence/schema"
+import { useWorkspaceLocation } from "@/workspaces/location"
+import type { ModelSelection } from "@/providers/models/selection"
+import { limitResetAt } from "../usage-exceeded-dialogs"
+
+const GO_URL = "https://opencode.ai/go"
+
+// OpenCode Zen always says when free usage resets; this covers a refusal that doesn't, or a delay out of range.
+const FALLBACK_RESET_MS = 3_600_000
+
+const FreeLimitState = Persistence.struct({ resetAt: Schema.NullOr(Schema.Finite) })
+
+// Free usage is counted per network, not per session, so one refusal anywhere holds until it resets. Connecting a paid
+// provider ends it early.
+export function useFreeLimit(paid: () => boolean) {
+ const location = useWorkspaceLocation()
+ const [state, setState] = persisted(Persist.global("free-limit"), FreeLimitState, { resetAt: null })
+ const [now, setNow] = createSignal(Date.now())
+
+ onCleanup(
+ location().event.on("session.step.failed", (event) => {
+ if (event.data.error.type !== "provider.free-limit") return
+ setState(
+ "resetAt",
+ limitResetAt(event.created, event.data.error.retryAfterMs) ?? event.created + FALLBACK_RESET_MS,
+ )
+ }),
+ )
+
+ const resetAt = () => state.resetAt
+
+ // Re-check when the limit resets, so the composer comes back on its own.
+ const timer = setInterval(() => setNow(Date.now()), 30_000)
+ onCleanup(() => clearInterval(timer))
+
+ return {
+ resetAt,
+ active: () => {
+ const at = resetAt()
+
+ return !paid() && at !== null && at > now()
+ },
+ }
+}
+
+// Stands in for the composer while free usage is used up: with no paid provider there is nothing the composer can send.
+export function SessionFreeLimitPanel(props: { resetAt: number | null; selection: () => ModelSelection | undefined }) {
+ const language = useLanguage()
+ const platform = usePlatform()
+ const dialog = useDialog()
+ const location = useWorkspaceLocation()
+
+ const reset = () => {
+ const at = props.resetAt
+
+ if (at === null) return
+ const sameDay = new Date(at).toDateString() === new Date().toDateString()
+
+ return new Intl.DateTimeFormat(
+ language.locale(),
+ sameDay ? { timeStyle: "short" } : { dateStyle: "medium", timeStyle: "short" },
+ ).format(at)
+ }
+
+ const connect = (provider?: string) => {
+ void import("@/providers/connect/dialog").then((x) => {
+ const controller = x.useProviderConnectController()
+
+ if (provider) controller.select(provider)
+ void dialog.show(() => (
+
+ ))
+ })
+ }
+
+ const subscribe = () => {
+ platform.openExternal(GO_URL)
+ connect("opencode-go")
+ }
+
+ return (
+
+
+
+ {language.t("session.freeLimit.title")}
+
+
+
+ {(time) => language.t("session.freeLimit.reset", { time: time() })}
+
+
+
+
+
+
+
+
+ )
+}
diff --git a/packages/app/src/session/composer/region.tsx b/packages/app/src/session/composer/region.tsx
index e534adf59f2e..2ef53edc2d0c 100644
--- a/packages/app/src/session/composer/region.tsx
+++ b/packages/app/src/session/composer/region.tsx
@@ -38,6 +38,7 @@ import { SessionComposerRegion } from "./session-composer-region"
import { createSessionComposerController, type SessionComposerController } from "./controller"
import { SessionQueuePanel } from "./queue-panel"
import { SessionGoLimitTray } from "./go-limit-tray"
+import { SessionFreeLimitPanel, useFreeLimit } from "./free-limit-panel"
import { SessionActivityChips, type SessionActivityItem } from "./activity-chips"
import { SessionComposerLane, useComposerLaneAlignment } from "./composer-lane"
import { SessionTodoPill } from "./todo-pill"
@@ -554,6 +555,8 @@ export function ActiveSessionComposerRegion(props: {
return props.session.data.info()?.outcome
}
+ const freeLimit = useFreeLimit(() => props.model.composer.model.paid)
+
return (
-
-
-
+ props.model.composer.model.selection}
+ />
+ }
+ >
+
+
+
+
}
>
diff --git a/packages/app/src/session/usage-exceeded-dialogs.tsx b/packages/app/src/session/usage-exceeded-dialogs.tsx
index 589a4f6708f9..5259f2498a5b 100644
--- a/packages/app/src/session/usage-exceeded-dialogs.tsx
+++ b/packages/app/src/session/usage-exceeded-dialogs.tsx
@@ -22,7 +22,8 @@ const MAX_RETRY_AFTER_MS = 45 * 86_400_000
const CHATGPT_USAGE_LIMIT_WINDOW = 86_400_000 // 24 hrs
-export function formatLimitReset(locale: string, created: number, retryAfterMs: number | undefined) {
+// When a usage limit resets, or undefined when the refusal's delay is missing or out of range.
+export function limitResetAt(created: number, retryAfterMs: number | undefined) {
if (
retryAfterMs === undefined ||
!Number.isFinite(retryAfterMs) ||
@@ -36,6 +37,14 @@ export function formatLimitReset(locale: string, created: number, retryAfterMs:
if (Number.isNaN(new Date(at).getTime())) return undefined
+ return at
+}
+
+export function formatLimitReset(locale: string, created: number, retryAfterMs: number | undefined) {
+ const at = limitResetAt(created, retryAfterMs)
+
+ if (at === undefined) return undefined
+
const now = Date.now()
const sameDay = new Date(at).toDateString() === new Date(now).toDateString() && at - now < GO_UPSELL_WINDOW
From 89e66ae70ee3ee3f4e6aa8f4157ff19cd5527bd3 Mon Sep 17 00:00:00 2001
From: James Long
Date: Thu, 12 Nov 2026 12:33:17 -0600
Subject: [PATCH 02/42] fix(tui): restore the live draft after browsing prompt
history (#63262)
---
packages/tui/src/component/prompt/index.tsx | 22 ++------
packages/tui/src/prompt/history.tsx | 55 +++++++++++++------
.../tui/test/prompt/history-composer.test.tsx | 52 ++++++++++++++++++
.../tui/test/prompt/history-provider.test.tsx | 27 +++++++++
4 files changed, 122 insertions(+), 34 deletions(-)
create mode 100644 packages/tui/test/prompt/history-composer.test.tsx
diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx
index 7072853b5376..ca5ddbe41b90 100644
--- a/packages/tui/src/component/prompt/index.tsx
+++ b/packages/tui/src/component/prompt/index.tsx
@@ -211,7 +211,6 @@ export function Prompt(props: PromptProps) {
const dialog = useDialog()
const toast = useToast()
const status = createMemo(() => data.session.status(props.sessionID ?? ""))
- const history = usePromptHistory()
const stash = usePromptStash()
const keymap = Keymap.use()
const renderer = useRenderer()
@@ -369,6 +368,7 @@ export function Prompt(props: PromptProps) {
extmarkToPart: new Map(),
interrupt: 0,
})
+ const history = usePromptHistory(() => ({ ...unwrap(store.prompt), mode: store.mode }))
let disposed = false
let pasteQueue = Promise.resolve()
@@ -691,6 +691,7 @@ export function Prompt(props: PromptProps) {
setStore("mode", mode)
},
set(prompt) {
+ history.reset()
input.setText(prompt.text)
setStore("prompt", prompt)
restoreExtmarksFromPrompt(prompt)
@@ -705,6 +706,7 @@ export function Prompt(props: PromptProps) {
}
function resetComposer() {
+ history.reset()
input.extmarks.clear()
setStore("prompt", emptyPrompt())
setStore("extmarkToPart", new Map())
@@ -900,12 +902,7 @@ export function Prompt(props: PromptProps) {
enabled: stash.list().length > 0,
run: () => {
const entry = stash.pop()
- if (entry) {
- input.setText(entry.prompt.text)
- setStore("prompt", entry.prompt)
- restoreExtmarksFromPrompt(entry.prompt)
- input.gotoBufferEnd()
- }
+ if (entry) ref.set(entry.prompt)
dialog.clear()
},
},
@@ -915,16 +912,7 @@ export function Prompt(props: PromptProps) {
category: "Prompt",
enabled: stash.list().length > 0,
run: () => {
- dialog.replace(() => (
- {
- input.setText(entry.prompt.text)
- setStore("prompt", entry.prompt)
- restoreExtmarksFromPrompt(entry.prompt)
- input.gotoBufferEnd()
- }}
- />
- ))
+ dialog.replace(() => ref.set(entry.prompt)} />)
},
},
].map(
diff --git a/packages/tui/src/prompt/history.tsx b/packages/tui/src/prompt/history.tsx
index f86f059c532d..2ac78fd61d2a 100644
--- a/packages/tui/src/prompt/history.tsx
+++ b/packages/tui/src/prompt/history.tsx
@@ -90,7 +90,7 @@ export function parsePromptInfo(value: unknown): PromptInfo | undefined {
return input as PromptInfo
}
-export const { use: usePromptHistory, provider: PromptHistoryProvider } = createSimpleContext({
+const { use: useHistoryEntries, provider: PromptHistoryProvider } = createSimpleContext({
name: "PromptHistory",
init: () => {
const paths = useTuiPaths()
@@ -104,26 +104,15 @@ export const { use: usePromptHistory, provider: PromptHistoryProvider } = create
writeText(historyPath, lines.map((line) => JSON.stringify(line)).join("\n") + "\n").catch(() => {})
})
- const [store, setStore] = createStore({ index: 0, history: [] as PromptInfo[] })
+ const [store, setStore] = createStore({ history: [] as PromptInfo[] })
return {
- move(direction: 1 | -1, input: string) {
- if (!store.history.length) return undefined
- const current = store.history.at(store.index)
- if (!current) return undefined
- if (current.text !== input && input.length) return
- const next = store.index + direction
- if (Math.abs(next) > store.history.length || next > 0) return
- setStore("index", next)
- if (next === 0) return emptyPrompt()
- return store.history.at(next)
+ get entries() {
+ return store.history
},
append(item: PromptInfo) {
const entry = structuredClone(unwrap(item))
- if (isDuplicateEntry(store.history.at(-1), entry)) {
- setStore("index", 0)
- return
- }
+ if (isDuplicateEntry(store.history.at(-1), entry)) return
let trimmed = false
setStore(
produce((draft) => {
@@ -132,7 +121,6 @@ export const { use: usePromptHistory, provider: PromptHistoryProvider } = create
draft.history = draft.history.slice(-MAX_HISTORY_ENTRIES)
trimmed = true
}
- draft.index = 0
}),
)
@@ -145,3 +133,36 @@ export const { use: usePromptHistory, provider: PromptHistoryProvider } = create
}
},
})
+
+export { PromptHistoryProvider }
+
+export function usePromptHistory(currentDraft = emptyPrompt) {
+ const history = useHistoryEntries()
+ let index = 0
+ let draft: PromptInfo | undefined
+ function reset() {
+ index = 0
+ draft = undefined
+ }
+ return {
+ move(direction: 1 | -1, input: string) {
+ const next = index + direction
+ if (next < -history.entries.length || next > 0) return
+ if (index < 0 && input && history.entries.at(index)?.text !== input) return
+ if (index === 0) draft = structuredClone({ ...currentDraft(), text: input })
+ index = next
+ if (next !== 0) {
+ const entry = history.entries.at(next)
+ return entry ? { ...emptyPrompt(), ...structuredClone(unwrap(entry)) } : undefined
+ }
+ const restored = draft
+ draft = undefined
+ return restored
+ },
+ reset,
+ append(item: PromptInfo) {
+ reset()
+ history.append(item)
+ },
+ }
+}
diff --git a/packages/tui/test/prompt/history-composer.test.tsx b/packages/tui/test/prompt/history-composer.test.tsx
new file mode 100644
index 000000000000..b4a6d22d2d20
--- /dev/null
+++ b/packages/tui/test/prompt/history-composer.test.tsx
@@ -0,0 +1,52 @@
+import { expect, test } from "bun:test"
+import path from "node:path"
+import { takeDraft } from "../../src/component/prompt/draft-stash"
+import { createAppFixture } from "../fixture/app"
+import { tmpdir } from "../fixture/fixture"
+
+async function composerWithHistory(state: string) {
+ takeDraft(undefined)
+ const file = path.join(state, "prompt-history.jsonl")
+ // Matching the oldest entry lets Up recall "previous" even before the draft restoration fix.
+ const entries = ["echo pen", "previous"].map((text) => JSON.stringify({ text, mode: "normal", pasted: [] }))
+ await Bun.write(file, entries.join("\n"))
+ const setup = await createAppFixture({ state })
+ await setup.ready
+ await setup.waitForFrame((frame) => frame.includes("commands"))
+ // Loading history rewrites the file with a trailing newline.
+ await setup.waitFor(async () => (await Bun.file(file).text()).endsWith("\n"))
+ return setup
+}
+
+test("down past the newest entry restores the draft text and shell mode", async () => {
+ await using state = await tmpdir()
+ await using setup = await composerWithHistory(state.path)
+ const editor = setup.renderer.currentFocusedEditor!
+
+ await setup.mockInput.typeText("!echo pen")
+ setup.mockInput.pressKey("HOME")
+ setup.mockInput.pressArrow("up")
+ expect(editor.plainText).toBe("previous")
+ await setup.waitForFrame((frame) => frame.includes("previous") && !frame.includes("Shell"))
+
+ setup.mockInput.pressKey("END")
+ setup.mockInput.pressArrow("down")
+ expect(editor.plainText).toBe("echo pen")
+ await setup.waitForFrame((frame) => frame.includes("Shell"))
+})
+
+test("clearing a recalled entry drops the draft so down stays empty", async () => {
+ await using state = await tmpdir()
+ await using setup = await composerWithHistory(state.path)
+ const editor = setup.renderer.currentFocusedEditor!
+
+ await setup.mockInput.typeText("unsent")
+ setup.mockInput.pressKey("HOME")
+ setup.mockInput.pressArrow("up")
+ expect(editor.plainText).toBe("previous")
+
+ setup.mockInput.pressKey("c", { ctrl: true })
+ expect(editor.plainText).toBe("")
+ setup.mockInput.pressArrow("down")
+ expect(editor.plainText).toBe("")
+})
diff --git a/packages/tui/test/prompt/history-provider.test.tsx b/packages/tui/test/prompt/history-provider.test.tsx
index 5ff0afda08a5..889c6671c801 100644
--- a/packages/tui/test/prompt/history-provider.test.tsx
+++ b/packages/tui/test/prompt/history-provider.test.tsx
@@ -50,6 +50,33 @@ test("keeps legacy unscoped history on the home composer", async () => {
}
})
+test("reset clears browsing position and live draft, and move returns a deep copy", async () => {
+ await using tmp = await tmpdir()
+ const setup = await renderHistory(tmp.path)
+ try {
+ setup.history.append({
+ text: "[Pasted ~3 lines] ",
+ files: [],
+ agents: [],
+ pasted: [{ text: "a\nb\nc", source: { start: 0, end: 17, text: "[Pasted ~3 lines]" } }],
+ })
+
+ const recalled = setup.history.move(-1, "unsent draft")
+ expect(recalled?.text).toBe("[Pasted ~3 lines] ")
+ recalled!.pasted[0]!.source.start = 99
+ recalled!.pasted.push({ text: "extra", source: { start: 0, end: 5, text: "extra" } })
+
+ setup.history.reset()
+ expect(setup.history.move(1, "")).toBeUndefined()
+
+ const again = setup.history.move(-1, "fresh draft")
+ expect(again?.pasted).toEqual([{ text: "a\nb\nc", source: { start: 0, end: 17, text: "[Pasted ~3 lines]" } }])
+ expect(setup.history.move(1, "[Pasted ~3 lines] ")?.text).toBe("fresh draft")
+ } finally {
+ setup.app.renderer.destroy()
+ }
+})
+
async function renderHistory(root: string, persisted?: string) {
const state = path.join(root, "state")
await mkdir(state, { recursive: true })
From 3cfe63a18282d3d252800099be8cde027fd80fab Mon Sep 17 00:00:00 2001
From: James Long
Date: Thu, 12 Nov 2026 12:34:17 -0600
Subject: [PATCH 03/42] fix(tui): restore pasted text when undo brings back its
placeholder (#63265)
---
packages/tui/src/component/prompt/index.tsx | 24 ++++++++-----
packages/tui/test/prompt-paste.test.tsx | 37 +++++++++++++++++++++
2 files changed, 52 insertions(+), 9 deletions(-)
diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx
index ca5ddbe41b90..f89ff5d63097 100644
--- a/packages/tui/src/component/prompt/index.tsx
+++ b/packages/tui/src/component/prompt/index.tsx
@@ -799,6 +799,7 @@ export function Prompt(props: PromptProps) {
virtual: true,
styleId,
typeId: promptPartTypeId,
+ data: ref.type === "pasted" ? { pasted: prompt.pasted[ref.index].text, label: mention.text } : undefined,
})
setStore("extmarkToPart", (map: Map) => {
const newMap = new Map(map)
@@ -821,6 +822,19 @@ export function Prompt(props: PromptProps) {
const pasted: PromptInfo["pasted"] = []
for (const extmark of allExtmarks) {
+ // Undo restores the extmark after its entry in the live prompt has been removed.
+ if (typeof extmark.data?.pasted === "string" && typeof extmark.data?.label === "string") {
+ if (input.getTextRange(extmark.start, extmark.end) !== extmark.data.label) {
+ input.extmarks.delete(extmark.id)
+ continue
+ }
+ newMap.set(extmark.id, { type: "pasted", index: pasted.length })
+ pasted.push({
+ text: extmark.data.pasted,
+ source: { start: extmark.start, end: extmark.end, text: extmark.data.label },
+ })
+ continue
+ }
const ref = draft.extmarkToPart.get(extmark.id)
if (!ref) continue
if (ref.type === "file") {
@@ -850,15 +864,7 @@ export function Prompt(props: PromptProps) {
const index = skills.length
skills.push(part)
newMap.set(extmark.id, { type: "skill", index })
- continue
}
- const part = draft.prompt.pasted[ref.index]
- if (!part) continue
- part.source.start = extmark.start
- part.source.end = extmark.end
- const index = pasted.length
- pasted.push(part)
- newMap.set(extmark.id, { type: "pasted", index })
}
const nextFiles = preserveMentionlessPromptAttachments(draft.prompt.files, files)
@@ -1405,6 +1411,7 @@ export function Prompt(props: PromptProps) {
virtual: true,
styleId: pasteStyleId,
typeId: promptPartTypeId,
+ data: { pasted: text, label: virtualText },
})
setStore(
@@ -1426,7 +1433,6 @@ export function Prompt(props: PromptProps) {
const part = store.prompt.pasted[ref.index]
if (!part) return false
- input.extmarks.delete(extmarkId)
input.setSelection(extmark.start, extmark.end)
input.insertText(part.text)
return true
diff --git a/packages/tui/test/prompt-paste.test.tsx b/packages/tui/test/prompt-paste.test.tsx
index be8abf062f08..60233ca41edc 100644
--- a/packages/tui/test/prompt-paste.test.tsx
+++ b/packages/tui/test/prompt-paste.test.tsx
@@ -1,6 +1,8 @@
import { expect, test } from "bun:test"
import { takeDraft } from "../src/component/prompt/draft-stash"
import { createAppFixture } from "./fixture/app"
+import { agent, model, session } from "./fixture/local"
+import { directory, json } from "./fixture/tui-client"
test("the prompt keeps pasted control characters and drops escape sequences", async () => {
// Other app tests can leave a home draft in the process-wide stash.
@@ -14,3 +16,38 @@ test("the prompt keeps pasted control characters and drops escape sequences", as
await setup.waitForFrame((frame) => frame.includes("xa^Lbc^@d"))
expect(setup.renderer.currentFocusedEditor?.plainText).toBe("xa\fbc\0d")
})
+
+test.each(["whole", "fragment"])("undo submits the restored %s paste chip", async (kind) => {
+ const sessionID = `ses_paste_${crypto.randomUUID()}`
+ const prompted = Promise.withResolvers()
+ await using setup = await createAppFixture({
+ args: { sessionID },
+ fetch: async (url, request) => {
+ const location = { directory }
+ if (url.pathname === "/api/agent") return json({ location, data: [agent("build")] })
+ if (url.pathname === "/api/model") return json({ location, data: [model("Paste Model")] })
+ if (url.pathname === `/api/session/${sessionID}`) return json({ data: session(sessionID) })
+ if (url.pathname.endsWith("/message") || url.pathname.endsWith("/inbox")) return json({ data: [], cursor: {} })
+ if (url.pathname.endsWith("/prompt")) {
+ prompted.resolve((await request.json()).text)
+ return json({ data: {} })
+ }
+ },
+ })
+ await setup.ready
+ await setup.waitForFrame((frame) => frame.includes("Paste Model"))
+ const pasted = "one\ntwo\nthree\nfour"
+ const text = () => setup.renderer.currentFocusedEditor?.plainText
+ await setup.mockInput.pasteBracketedText(pasted)
+ await setup.waitFor(() => text() === "[Pasted ~4 lines] ")
+ if (kind === "fragment") {
+ setup.mockInput.pressBackspace() // Remove the space after the chip.
+ setup.mockInput.pressKey("w", { ctrl: true }) // Leave a fragment of the chip.
+ }
+ setup.mockInput.pressKey("u", { ctrl: true })
+ await setup.waitFor(() => text() === "")
+ setup.mockInput.pressKey("z", { super: true })
+ await setup.waitFor(() => text() === (kind === "whole" ? "[Pasted ~4 lines] " : "[Pasted ~4 "))
+ setup.mockInput.pressEnter()
+ expect(await prompted.promise).toBe(kind === "whole" ? `${pasted} ` : "[Pasted ~4 ")
+})
From a73657f3f96dbba6cc4c266015d47cde84a290ad Mon Sep 17 00:00:00 2001
From: James Long
Date: Thu, 12 Nov 2026 12:39:15 -0600
Subject: [PATCH 04/42] refactor(codemode): flatten the VM into src and remove
two-engine leftovers (#63377)
---
packages/codemode/AGENTS.md | 3 +-
packages/codemode/README.md | 2 +-
packages/codemode/script/bench.ts | 2 +-
packages/codemode/script/disasm.ts | 10 +-
packages/codemode/script/prelude.ts | 18 +--
packages/codemode/script/setup.ts | 4 +-
packages/codemode/src/{vm => }/async.ts | 2 +-
packages/codemode/src/{vm => }/code.ts | 0
packages/codemode/src/codemode.ts | 12 +-
.../codemode/src/{vm => }/compiler/compile.ts | 0
.../codemode/src/{vm => }/compiler/scope.ts | 0
packages/codemode/src/{vm => }/data.ts | 2 -
packages/codemode/src/extension.ts | 2 +-
packages/codemode/src/{vm => }/generators.ts | 0
packages/codemode/src/{vm => }/host.ts | 4 +-
.../codemode/src/{vm => }/internal-prelude.ts | 0
packages/codemode/src/{vm => }/opcodes.ts | 2 +-
.../src/{vm => }/prelude/bytecode.json | 0
.../codemode/src/{vm => }/prelude/bytecode.ts | 0
.../codemode/src/{vm => }/prelude/helpers.ts | 2 +-
.../codemode/src/{vm => }/prelude/prelude.ts | 0
.../codemode/src/{vm => }/prelude/source.ts | 0
.../codemode/src/{vm => }/runtime/callback.ts | 0
.../codemode/src/{vm => }/runtime/driver.ts | 2 +-
.../codemode/src/{vm => }/runtime/errors.ts | 6 +-
.../codemode/src/{vm => }/runtime/execute.ts | 15 +--
.../src/{vm => }/runtime/extensions.ts | 4 +-
.../src/{vm => }/runtime/generators.ts | 0
.../codemode/src/{vm => }/runtime/globals.ts | 2 +-
.../src/{vm => }/runtime/interpreter.ts | 2 +-
.../src/{vm => }/runtime/intrinsic-names.ts | 0
.../src/{vm => }/runtime/intrinsics.ts | 0
.../codemode/src/{vm => }/runtime/limits.ts | 0
.../codemode/src/{vm => }/runtime/model.ts | 2 +-
.../codemode/src/{vm => }/runtime/modules.ts | 0
.../codemode/src/{vm => }/runtime/native.ts | 0
.../codemode/src/{vm => }/runtime/objects.ts | 2 +-
.../src/{vm => }/runtime/operations.ts | 2 +-
.../codemode/src/{vm => }/runtime/promises.ts | 0
.../src/{vm => }/runtime/references.ts | 2 +-
.../codemode/src/{vm => }/runtime/signals.ts | 0
.../codemode/src/{vm => }/runtime/source.ts | 0
.../codemode/src/{vm => }/runtime/table.ts | 0
packages/codemode/src/scan.ts | 4 +-
packages/codemode/src/{vm => }/scheduler.ts | 2 +-
packages/codemode/src/{vm => }/snapshot.ts | 2 +-
.../codemode/src/{vm => }/snapshot/codec.ts | 10 +-
.../src/{vm => }/snapshot/snapshot.ts | 4 +-
.../codemode/src/{vm => }/stdlib/array.ts | 2 +-
.../codemode/src/{vm => }/stdlib/bytes.ts | 0
.../src/{vm => }/stdlib/collections.ts | 0
.../codemode/src/{vm => }/stdlib/console.ts | 2 +-
packages/codemode/src/{vm => }/stdlib/date.ts | 0
.../codemode/src/{vm => }/stdlib/headers.ts | 0
.../codemode/src/{vm => }/stdlib/iterator.ts | 0
packages/codemode/src/{vm => }/stdlib/json.ts | 0
packages/codemode/src/{vm => }/stdlib/math.ts | 0
.../codemode/src/{vm => }/stdlib/number.ts | 0
.../codemode/src/{vm => }/stdlib/object.ts | 2 +-
.../codemode/src/{vm => }/stdlib/regexp.ts | 0
.../codemode/src/{vm => }/stdlib/string.ts | 0
packages/codemode/src/{vm => }/stdlib/url.ts | 0
.../codemode/src/{vm => }/stdlib/value.ts | 0
packages/codemode/src/{vm => }/stdlib/web.ts | 2 +-
packages/codemode/src/tool-runtime.ts | 2 +-
packages/codemode/src/{vm => }/vm.ts | 4 +-
.../test/array-callbacks-test262.test.ts | 2 +-
.../codemode/test/array-core-test262.test.ts | 2 +-
.../codemode/test/{vm => }/build-id.test.ts | 6 +-
...limits.test.ts => bytecode-limits.test.ts} | 23 ++--
packages/codemode/test/callbacks.test.ts | 2 +-
packages/codemode/test/codemode.test.ts | 2 +-
.../codemode/test/constructor-test262.test.ts | 2 +-
packages/codemode/test/date-test262.test.ts | 2 +-
packages/codemode/test/enumeration.test.ts | 2 +-
packages/codemode/test/errors.test.ts | 2 +-
packages/codemode/test/extensions.test.ts | 2 +-
packages/codemode/test/fixtures/build-id.ts | 6 +-
.../test/fixtures/prelude-roundtrip.ts | 6 +-
.../codemode/test/for-await-test262.test.ts | 2 +-
.../codemode/test/generator-test262.test.ts | 2 +-
.../codemode/test/groupby-test262.test.ts | 2 +-
.../test/json-callbacks-test262.test.ts | 2 +-
.../test/labeled-control-test262.test.ts | 2 +-
.../codemode/test/lexical-test262.test.ts | 2 +-
packages/codemode/test/lib/index.ts | 1 -
packages/codemode/test/limits.test.ts | 8 +-
packages/codemode/test/new-expression.test.ts | 2 +-
.../test/object-coercion-test262.test.ts | 2 +-
packages/codemode/test/openapi.test.ts | 2 +-
packages/codemode/test/parity.test.ts | 2 +-
packages/codemode/test/preload.ts | 4 +-
.../test/{vm => }/prelude-bytecode.test.ts | 16 +--
.../codemode/test/promise-test262.test.ts | 2 +-
packages/codemode/test/promise.test.ts | 2 +-
.../codemode/test/regexp-math-test262.test.ts | 2 +-
.../codemode/test/{vm => }/resumable.test.ts | 24 ++--
.../test/{vm/run.ts => run-program.ts} | 104 +++---------------
packages/codemode/test/scan.test.ts | 2 +-
.../codemode/test/set-methods-test262.test.ts | 2 +-
packages/codemode/test/signature.test.ts | 2 +-
.../codemode/test/{vm => }/snapshot.test.ts | 32 +++---
packages/codemode/test/{vm => }/state.test.ts | 52 +++++----
packages/codemode/test/stdlib.test.ts | 2 +-
.../codemode/test/string-core-test262.test.ts | 2 +-
.../test/string-date-methods-test262.test.ts | 2 +-
.../test/string-regexp-test262.test.ts | 2 +-
.../test/string-search-test262.test.ts | 2 +-
.../codemode/test/{vm => }/suspend.test.ts | 6 +-
packages/codemode/test/test262/run.ts | 36 +++---
packages/codemode/test/tool-paths.test.ts | 2 +-
.../test/var-hoisting-test262.test.ts | 2 +-
.../test/{vm/verify.ts => verify-bytecode.ts} | 4 +-
packages/codemode/test/{vm => }/vm.test.ts | 11 +-
packages/codemode/test/web-wpt.test.ts | 2 +-
115 files changed, 239 insertions(+), 306 deletions(-)
rename packages/codemode/src/{vm => }/async.ts (99%)
rename packages/codemode/src/{vm => }/code.ts (100%)
rename packages/codemode/src/{vm => }/compiler/compile.ts (100%)
rename packages/codemode/src/{vm => }/compiler/scope.ts (100%)
rename packages/codemode/src/{vm => }/data.ts (95%)
rename packages/codemode/src/{vm => }/generators.ts (100%)
rename packages/codemode/src/{vm => }/host.ts (99%)
rename packages/codemode/src/{vm => }/internal-prelude.ts (100%)
rename packages/codemode/src/{vm => }/opcodes.ts (99%)
rename packages/codemode/src/{vm => }/prelude/bytecode.json (100%)
rename packages/codemode/src/{vm => }/prelude/bytecode.ts (100%)
rename packages/codemode/src/{vm => }/prelude/helpers.ts (99%)
rename packages/codemode/src/{vm => }/prelude/prelude.ts (100%)
rename packages/codemode/src/{vm => }/prelude/source.ts (100%)
rename packages/codemode/src/{vm => }/runtime/callback.ts (100%)
rename packages/codemode/src/{vm => }/runtime/driver.ts (99%)
rename packages/codemode/src/{vm => }/runtime/errors.ts (97%)
rename packages/codemode/src/{vm => }/runtime/execute.ts (97%)
rename packages/codemode/src/{vm => }/runtime/extensions.ts (99%)
rename packages/codemode/src/{vm => }/runtime/generators.ts (100%)
rename packages/codemode/src/{vm => }/runtime/globals.ts (99%)
rename packages/codemode/src/{vm => }/runtime/interpreter.ts (98%)
rename packages/codemode/src/{vm => }/runtime/intrinsic-names.ts (100%)
rename packages/codemode/src/{vm => }/runtime/intrinsics.ts (100%)
rename packages/codemode/src/{vm => }/runtime/limits.ts (100%)
rename packages/codemode/src/{vm => }/runtime/model.ts (98%)
rename packages/codemode/src/{vm => }/runtime/modules.ts (100%)
rename packages/codemode/src/{vm => }/runtime/native.ts (100%)
rename packages/codemode/src/{vm => }/runtime/objects.ts (99%)
rename packages/codemode/src/{vm => }/runtime/operations.ts (99%)
rename packages/codemode/src/{vm => }/runtime/promises.ts (100%)
rename packages/codemode/src/{vm => }/runtime/references.ts (97%)
rename packages/codemode/src/{vm => }/runtime/signals.ts (100%)
rename packages/codemode/src/{vm => }/runtime/source.ts (100%)
rename packages/codemode/src/{vm => }/runtime/table.ts (100%)
rename packages/codemode/src/{vm => }/scheduler.ts (99%)
rename packages/codemode/src/{vm => }/snapshot.ts (99%)
rename packages/codemode/src/{vm => }/snapshot/codec.ts (98%)
rename packages/codemode/src/{vm => }/snapshot/snapshot.ts (97%)
rename packages/codemode/src/{vm => }/stdlib/array.ts (99%)
rename packages/codemode/src/{vm => }/stdlib/bytes.ts (100%)
rename packages/codemode/src/{vm => }/stdlib/collections.ts (100%)
rename packages/codemode/src/{vm => }/stdlib/console.ts (98%)
rename packages/codemode/src/{vm => }/stdlib/date.ts (100%)
rename packages/codemode/src/{vm => }/stdlib/headers.ts (100%)
rename packages/codemode/src/{vm => }/stdlib/iterator.ts (100%)
rename packages/codemode/src/{vm => }/stdlib/json.ts (100%)
rename packages/codemode/src/{vm => }/stdlib/math.ts (100%)
rename packages/codemode/src/{vm => }/stdlib/number.ts (100%)
rename packages/codemode/src/{vm => }/stdlib/object.ts (99%)
rename packages/codemode/src/{vm => }/stdlib/regexp.ts (100%)
rename packages/codemode/src/{vm => }/stdlib/string.ts (100%)
rename packages/codemode/src/{vm => }/stdlib/url.ts (100%)
rename packages/codemode/src/{vm => }/stdlib/value.ts (100%)
rename packages/codemode/src/{vm => }/stdlib/web.ts (98%)
rename packages/codemode/src/{vm => }/vm.ts (99%)
rename packages/codemode/test/{vm => }/build-id.test.ts (87%)
rename packages/codemode/test/{vm/limits.test.ts => bytecode-limits.test.ts} (97%)
delete mode 100644 packages/codemode/test/lib/index.ts
rename packages/codemode/test/{vm => }/prelude-bytecode.test.ts (77%)
rename packages/codemode/test/{vm => }/resumable.test.ts (95%)
rename packages/codemode/test/{vm/run.ts => run-program.ts} (54%)
rename packages/codemode/test/{vm => }/snapshot.test.ts (91%)
rename packages/codemode/test/{vm => }/state.test.ts (92%)
rename packages/codemode/test/{vm => }/suspend.test.ts (99%)
rename packages/codemode/test/{vm/verify.ts => verify-bytecode.ts} (99%)
rename packages/codemode/test/{vm => }/vm.test.ts (98%)
diff --git a/packages/codemode/AGENTS.md b/packages/codemode/AGENTS.md
index 47228beb77c6..66f962e081ee 100644
--- a/packages/codemode/AGENTS.md
+++ b/packages/codemode/AGENTS.md
@@ -1,5 +1,6 @@
# @opencode/codemode
- `interpreter-support.md` is a checklist, not a changelog: check off newly added support and add unchecked items for significant gaps. Leave it alone for fixes and refactors.
-- Program values are `Value` (`src/vm/runtime/objects.ts`). Host values are `unknown` and enter only through `fromHost` and `fromJson`; do not widen program-facing signatures to `unknown`.
+- Program values are `Value` (`src/runtime/objects.ts`). Host values are `unknown` and enter only through `fromHost` and `fromJson`; do not widen program-facing signatures to `unknown`.
- Each built-in object kind is one `Obj` subclass (`Wrapper` or `Opaque`) that overrides the hooks it needs. Ask the object instead of adding `instanceof` ladders.
+- The core VM, compiler, prelude, snapshot, and stdlib modules must not import `effect`; Effect lives only in the host boundary and driver (`src/runtime/`, `src/openapi/`, and the top-level tool/runtime entrypoints).
diff --git a/packages/codemode/README.md b/packages/codemode/README.md
index 8b429a54edfe..f5a2730f67fc 100644
--- a/packages/codemode/README.md
+++ b/packages/codemode/README.md
@@ -246,7 +246,7 @@ Every value crossing in either direction is converted, never shared: arguments c
copies, and a function inside a result is callable the same way. A global that shadows a built-in or another
extension throws at `CodeMode.make`.
-Functions inside a result have no data form, so a suspended VM run loses them by default: after a resume, calling one
+Functions inside a result have no data form, so a suspended run loses them by default: after a resume, calling one
throws a `TypeError`. An extension can preserve them across suspend and resume with `snapshot` hooks. `encode` receives
a value one of the extension's functions returned, as the host function returned it, and returns plain data (JSON
values and `Uint8Array`s); on resume, `decode` receives that data once per value and returns a host value of the same
diff --git a/packages/codemode/script/bench.ts b/packages/codemode/script/bench.ts
index 1940316ee73c..0d9027846b6e 100644
--- a/packages/codemode/script/bench.ts
+++ b/packages/codemode/script/bench.ts
@@ -6,7 +6,7 @@
import { numberOfDFGCompiles, reoptimizationRetryCount } from "bun:jsc"
import { Effect, Schema } from "effect"
import { CodeMode, Tool } from "../src/index.js"
-import { Vm } from "../src/vm/vm.js"
+import { Vm } from "../src/vm.js"
const cases: ReadonlyArray = [
[
diff --git a/packages/codemode/script/disasm.ts b/packages/codemode/script/disasm.ts
index 1d0317900425..d3e114270ff5 100644
--- a/packages/codemode/script/disasm.ts
+++ b/packages/codemode/script/disasm.ts
@@ -1,9 +1,9 @@
#!/usr/bin/env bun
// The bytecode disassembler: pcs, ops, constants, handler and finally tables, local names, source lines.
-import { sourceLocation } from "../src/vm/runtime/model.js"
-import type { Code } from "../src/vm/code.js"
-import { compileSource } from "../src/vm/compiler/compile.js"
+import { sourceLocation } from "../src/runtime/model.js"
+import type { Code } from "../src/code.js"
+import { compileSource } from "../src/compiler/compile.js"
import {
BinOpSymbols,
CheckBaseKind,
@@ -13,8 +13,8 @@ import {
OpNames,
PutKind,
UnaryOpSymbols,
-} from "../src/vm/opcodes.js"
-import { parseProgram } from "../src/vm/runtime/execute.js"
+} from "../src/opcodes.js"
+import { parseProgram } from "../src/runtime/execute.js"
const formatFlags = (flags: number): string => {
const names: Array = []
diff --git a/packages/codemode/script/prelude.ts b/packages/codemode/script/prelude.ts
index ca4c5c925873..b57e1ff0783d 100644
--- a/packages/codemode/script/prelude.ts
+++ b/packages/codemode/script/prelude.ts
@@ -1,15 +1,15 @@
#!/usr/bin/env bun
-// Compiles the built-in sources (the prelude, the VM's internal helpers) ahead of time into src/vm/prelude/bytecode.json,
-// which a process loads instead of parsing and compiling them (see src/vm/prelude/bytecode.ts). Run it after changing
-// either source or the compiler; test/vm/prelude-bytecode.test.ts fails until then.
+// Compiles the built-in sources (the prelude, the VM's internal helpers) ahead of time into src/prelude/bytecode.json,
+// which a process loads instead of parsing and compiling them (see src/prelude/bytecode.ts). Run it after changing
+// either source or the compiler; test/prelude-bytecode.test.ts fails until then.
import { parse } from "acorn"
-import { Source } from "../src/vm/runtime/source.js"
-import { saveCodes } from "../src/vm/prelude/bytecode.js"
-import { code } from "../src/vm/prelude/source.js"
-import { compileSource } from "../src/vm/compiler/compile.js"
-import { INTERNAL_SOURCE } from "../src/vm/internal-prelude.js"
+import { Source } from "../src/runtime/source.js"
+import { saveCodes } from "../src/prelude/bytecode.js"
+import { code } from "../src/prelude/source.js"
+import { compileSource } from "../src/compiler/compile.js"
+import { INTERNAL_SOURCE } from "../src/internal-prelude.js"
export const compileBuiltins = () =>
Object.fromEntries(
@@ -23,5 +23,5 @@ export const compileBuiltins = () =>
)
if (import.meta.main) {
- await Bun.write(new URL("../src/vm/prelude/bytecode.json", import.meta.url), `${JSON.stringify(compileBuiltins())}\n`)
+ await Bun.write(new URL("../src/prelude/bytecode.json", import.meta.url), `${JSON.stringify(compileBuiltins())}\n`)
}
diff --git a/packages/codemode/script/setup.ts b/packages/codemode/script/setup.ts
index 03459c5140a0..49603b79586d 100644
--- a/packages/codemode/script/setup.ts
+++ b/packages/codemode/script/setup.ts
@@ -5,8 +5,8 @@
import { Effect } from "effect"
import { CodeMode } from "../src/index.js"
-import { Interpreter } from "../src/vm/runtime/interpreter.js"
-import { createBuiltins } from "../src/vm/runtime/intrinsics.js"
+import { Interpreter } from "../src/runtime/interpreter.js"
+import { createBuiltins } from "../src/runtime/intrinsics.js"
import { ToolRuntime } from "../src/tool-runtime.js"
const index = process.argv.indexOf("--iterations")
diff --git a/packages/codemode/src/vm/async.ts b/packages/codemode/src/async.ts
similarity index 99%
rename from packages/codemode/src/vm/async.ts
rename to packages/codemode/src/async.ts
index 9a323ee02f4a..3eae192d5bea 100644
--- a/packages/codemode/src/vm/async.ts
+++ b/packages/codemode/src/async.ts
@@ -1,4 +1,4 @@
-import type { Diagnostic } from "../codemode.js"
+import type { Diagnostic } from "./codemode.js"
import { normalizeError, locate } from "./runtime/errors.js"
import { MAX_PENDING_PROMISES } from "./runtime/limits.js"
import { type AstNode, IteratorSymbol, rangeError, typeError } from "./runtime/model.js"
diff --git a/packages/codemode/src/vm/code.ts b/packages/codemode/src/code.ts
similarity index 100%
rename from packages/codemode/src/vm/code.ts
rename to packages/codemode/src/code.ts
diff --git a/packages/codemode/src/codemode.ts b/packages/codemode/src/codemode.ts
index 219808df1703..3e64f89b2fcd 100644
--- a/packages/codemode/src/codemode.ts
+++ b/packages/codemode/src/codemode.ts
@@ -3,11 +3,11 @@ import type { Extension } from "./extension.js"
import { scanTools } from "./scan.js"
import { type Services, type ToolDescription, ToolRuntime } from "./tool-runtime.js"
import type { Tools } from "./tools.js"
-import { fromJson } from "./vm/data.js"
-import { finishExecution, resumeProgram, type Running, type Setup, startProgram, SuspendError } from "./vm/runtime/execute.js"
-import { extensionGlobals } from "./vm/runtime/extensions.js"
-import { globalNames } from "./vm/runtime/globals.js"
-import { fromBytes, type Snapshot, SnapshotError, type SnapshotHeader, toBytes } from "./vm/snapshot/snapshot.js"
+import { fromJson } from "./data.js"
+import { finishExecution, resumeProgram, type Running, type Setup, startProgram, SuspendError } from "./runtime/execute.js"
+import { extensionGlobals } from "./runtime/extensions.js"
+import { globalNames } from "./runtime/globals.js"
+import { fromBytes, type Snapshot, SnapshotError, type SnapshotHeader, toBytes } from "./snapshot/snapshot.js"
export { fromBytes, scanTools, SnapshotError, SuspendError, toBytes }
export type { Snapshot, SnapshotHeader }
@@ -173,7 +173,7 @@ export type Runtime = {
}
/**
- * One run of a program on the VM. `run()` runs it in the current fiber until it ends or is suspended, and owns its host
+ * One run of a program. `run()` runs it in the current fiber until it ends or is suspended, and owns its host
* calls: interrupting `run()` interrupts them. A program runs once: running it again is a defect.
*/
export type Program = {
diff --git a/packages/codemode/src/vm/compiler/compile.ts b/packages/codemode/src/compiler/compile.ts
similarity index 100%
rename from packages/codemode/src/vm/compiler/compile.ts
rename to packages/codemode/src/compiler/compile.ts
diff --git a/packages/codemode/src/vm/compiler/scope.ts b/packages/codemode/src/compiler/scope.ts
similarity index 100%
rename from packages/codemode/src/vm/compiler/scope.ts
rename to packages/codemode/src/compiler/scope.ts
diff --git a/packages/codemode/src/vm/data.ts b/packages/codemode/src/data.ts
similarity index 95%
rename from packages/codemode/src/vm/data.ts
rename to packages/codemode/src/data.ts
index 8fabac36cc66..8a3dd2f1d32c 100644
--- a/packages/codemode/src/vm/data.ts
+++ b/packages/codemode/src/data.ts
@@ -1,5 +1,3 @@
-export * as Data from "./data.js"
-
import type { Json } from "./snapshot/codec.js"
import type { Interpreter } from "./runtime/interpreter.js"
import { Arr, define, Obj, type Value } from "./runtime/objects.js"
diff --git a/packages/codemode/src/extension.ts b/packages/codemode/src/extension.ts
index 3c65a77afcee..8ca6b9b8332f 100644
--- a/packages/codemode/src/extension.ts
+++ b/packages/codemode/src/extension.ts
@@ -13,7 +13,7 @@ import type { Effect } from "effect"
* promise of an asynchronous global and by throwing from a synchronous one. Functions inside a global object are
* called the same way, named by their path (`fs.readFile`).
*
- * Programs can also `import` or `require` a global by its Node module name; see `interpreter/modules.ts`.
+ * Programs can also `import` or `require` a global by its Node module name; see `runtime/modules.ts`.
*/
export type Extension> = Readonly>> = {
readonly name: string
diff --git a/packages/codemode/src/vm/generators.ts b/packages/codemode/src/generators.ts
similarity index 100%
rename from packages/codemode/src/vm/generators.ts
rename to packages/codemode/src/generators.ts
diff --git a/packages/codemode/src/vm/host.ts b/packages/codemode/src/host.ts
similarity index 99%
rename from packages/codemode/src/vm/host.ts
rename to packages/codemode/src/host.ts
index 67b4fe737d73..d1fdc3fd5949 100644
--- a/packages/codemode/src/vm/host.ts
+++ b/packages/codemode/src/host.ts
@@ -1,4 +1,4 @@
-import type { Diagnostic } from "../codemode.js"
+import type { Diagnostic } from "./codemode.js"
import { fromJson, type Json } from "./data.js"
import { startExtensionCall } from "./runtime/extensions.js"
import type { Interpreter } from "./runtime/interpreter.js"
@@ -7,7 +7,7 @@ import { Arr, PromiseObj, type Value } from "./runtime/objects.js"
import { promiseLike } from "./runtime/promises.js"
import type { Completion } from "./runtime/signals.js"
import { type ExtensionRequest, HostCall, type HostRequest, Resolving } from "./scheduler.js"
-import type { ExtensionInvocation } from "../tool-runtime.js"
+import type { ExtensionInvocation } from "./tool-runtime.js"
import type { Code } from "./code.js"
import { internalCode, tryFastBoundaryOrJson, VmIntrinsic } from "./internal-prelude.js"
import { type FrameMode, Mode, type Vm } from "./vm.js"
diff --git a/packages/codemode/src/vm/internal-prelude.ts b/packages/codemode/src/internal-prelude.ts
similarity index 100%
rename from packages/codemode/src/vm/internal-prelude.ts
rename to packages/codemode/src/internal-prelude.ts
diff --git a/packages/codemode/src/vm/opcodes.ts b/packages/codemode/src/opcodes.ts
similarity index 99%
rename from packages/codemode/src/vm/opcodes.ts
rename to packages/codemode/src/opcodes.ts
index 0f84a541fe9a..d81ef7a6f9fc 100644
--- a/packages/codemode/src/vm/opcodes.ts
+++ b/packages/codemode/src/opcodes.ts
@@ -1,4 +1,4 @@
-import type { DiagnosticKind } from "../codemode.js"
+import type { DiagnosticKind } from "./codemode.js"
import type { ErrorType } from "./runtime/intrinsics.js"
/** Uninitialized lexical binding sentinel (temporal dead zone). */
diff --git a/packages/codemode/src/vm/prelude/bytecode.json b/packages/codemode/src/prelude/bytecode.json
similarity index 100%
rename from packages/codemode/src/vm/prelude/bytecode.json
rename to packages/codemode/src/prelude/bytecode.json
diff --git a/packages/codemode/src/vm/prelude/bytecode.ts b/packages/codemode/src/prelude/bytecode.ts
similarity index 100%
rename from packages/codemode/src/vm/prelude/bytecode.ts
rename to packages/codemode/src/prelude/bytecode.ts
diff --git a/packages/codemode/src/vm/prelude/helpers.ts b/packages/codemode/src/prelude/helpers.ts
similarity index 99%
rename from packages/codemode/src/vm/prelude/helpers.ts
rename to packages/codemode/src/prelude/helpers.ts
index f213fade8a9a..1d02f065d84a 100644
--- a/packages/codemode/src/vm/prelude/helpers.ts
+++ b/packages/codemode/src/prelude/helpers.ts
@@ -33,7 +33,7 @@ import {
} from "../runtime/objects.js"
import { builtinCursor, requireIteratorObject } from "../runtime/operations.js"
import { containsOpaqueReference, describeValue, isOpaque } from "../runtime/references.js"
-import { compareText } from "../../tool-runtime.js"
+import { compareText } from "../tool-runtime.js"
import { Invoke } from "../runtime/signals.js"
// The prelude's privileged helpers: leaf built-ins (they never call program code) bound only in the prelude's scope.
diff --git a/packages/codemode/src/vm/prelude/prelude.ts b/packages/codemode/src/prelude/prelude.ts
similarity index 100%
rename from packages/codemode/src/vm/prelude/prelude.ts
rename to packages/codemode/src/prelude/prelude.ts
diff --git a/packages/codemode/src/vm/prelude/source.ts b/packages/codemode/src/prelude/source.ts
similarity index 100%
rename from packages/codemode/src/vm/prelude/source.ts
rename to packages/codemode/src/prelude/source.ts
diff --git a/packages/codemode/src/vm/runtime/callback.ts b/packages/codemode/src/runtime/callback.ts
similarity index 100%
rename from packages/codemode/src/vm/runtime/callback.ts
rename to packages/codemode/src/runtime/callback.ts
diff --git a/packages/codemode/src/vm/runtime/driver.ts b/packages/codemode/src/runtime/driver.ts
similarity index 99%
rename from packages/codemode/src/vm/runtime/driver.ts
rename to packages/codemode/src/runtime/driver.ts
index f5e77e0e2d56..e9039c1d43f0 100644
--- a/packages/codemode/src/vm/runtime/driver.ts
+++ b/packages/codemode/src/runtime/driver.ts
@@ -1,7 +1,7 @@
import { Cause, type Context, Effect, Exit, Fiber } from "effect"
import type { Json } from "../data.js"
import type { HostCall } from "../scheduler.js"
-import { type ToolRuntime, toolExpression } from "../../tool-runtime.js"
+import { type ToolRuntime, toolExpression } from "../tool-runtime.js"
import { locate } from "./errors.js"
import { PendingThrow } from "./model.js"
import type { Vm } from "../vm.js"
diff --git a/packages/codemode/src/vm/runtime/errors.ts b/packages/codemode/src/runtime/errors.ts
similarity index 97%
rename from packages/codemode/src/vm/runtime/errors.ts
rename to packages/codemode/src/runtime/errors.ts
index 83748ec9a1b4..4e9ce352fc26 100644
--- a/packages/codemode/src/vm/runtime/errors.ts
+++ b/packages/codemode/src/runtime/errors.ts
@@ -1,6 +1,6 @@
-import type { Diagnostic } from "../../codemode.js"
-import { ToolError } from "../../tool-error.js"
-import { ToolRuntimeError } from "../../tool-runtime.js"
+import type { Diagnostic } from "../codemode.js"
+import { ToolError } from "../tool-error.js"
+import { ToolRuntimeError } from "../tool-runtime.js"
import { type AstNode, formatLocation, PendingThrow, Throw, sourceLocation } from "./model.js"
import { containsRuntimeReference } from "./references.js"
import { createErrorValue, type ErrorType, isErrorType } from "./intrinsics.js"
diff --git a/packages/codemode/src/vm/runtime/execute.ts b/packages/codemode/src/runtime/execute.ts
similarity index 97%
rename from packages/codemode/src/vm/runtime/execute.ts
rename to packages/codemode/src/runtime/execute.ts
index f4e5c1c9af82..20bb53d92622 100644
--- a/packages/codemode/src/vm/runtime/execute.ts
+++ b/packages/codemode/src/runtime/execute.ts
@@ -1,8 +1,8 @@
import { parse, type Program } from "acorn"
import { Cause, Deferred, Effect, Option, Schema } from "effect"
-import type { DataValue, Diagnostic, Outcome, ResolvedExecutionLimits, Result, Suspended } from "../../codemode.js"
+import type { DataValue, Diagnostic, Outcome, ResolvedExecutionLimits, Result, Suspended } from "../codemode.js"
import { fromBytes, header, type Snapshot, SnapshotError, toBytes } from "../snapshot/snapshot.js"
-import { ToolRuntime } from "../../tool-runtime.js"
+import { ToolRuntime } from "../tool-runtime.js"
import { normalizeError } from "./errors.js"
import { createBuiltins } from "./intrinsics.js"
import { Interpreter } from "./interpreter.js"
@@ -47,17 +47,6 @@ export const finishExecution = (outcome: Effect.Effect): Ef
}
})
-export const executeProgram = (
- code: string,
- prepared: ToolRuntime.Prepared,
- limits: ResolvedExecutionLimits,
- hooks: ToolRuntime.Hooks,
- globals?: Globals,
- bindings?: Globals,
- lossy = false,
-): Effect.Effect =>
- finishExecution(startProgram({ prepared, limits, hooks, globals, lossy }, code, bindings).run())
-
/** A program ready to run on the VM: nothing runs until `run`. */
export const startProgram = (
setup: Setup,
diff --git a/packages/codemode/src/vm/runtime/extensions.ts b/packages/codemode/src/runtime/extensions.ts
similarity index 99%
rename from packages/codemode/src/vm/runtime/extensions.ts
rename to packages/codemode/src/runtime/extensions.ts
index 1d335deba864..dc6f776f203d 100644
--- a/packages/codemode/src/vm/runtime/extensions.ts
+++ b/packages/codemode/src/runtime/extensions.ts
@@ -1,6 +1,6 @@
import { Effect } from "effect"
-import { type Extension, isAsync } from "../../extension.js"
-import { hooked } from "../../tool-runtime.js"
+import { type Extension, isAsync } from "../extension.js"
+import { hooked } from "../tool-runtime.js"
import { errorMessage, errorType } from "./errors.js"
import type { Interpreter } from "./interpreter.js"
import { createErrorValue } from "./intrinsics.js"
diff --git a/packages/codemode/src/vm/runtime/generators.ts b/packages/codemode/src/runtime/generators.ts
similarity index 100%
rename from packages/codemode/src/vm/runtime/generators.ts
rename to packages/codemode/src/runtime/generators.ts
diff --git a/packages/codemode/src/vm/runtime/globals.ts b/packages/codemode/src/runtime/globals.ts
similarity index 99%
rename from packages/codemode/src/vm/runtime/globals.ts
rename to packages/codemode/src/runtime/globals.ts
index 6e5c3a31893c..6909da9d0a11 100644
--- a/packages/codemode/src/vm/runtime/globals.ts
+++ b/packages/codemode/src/runtime/globals.ts
@@ -15,7 +15,7 @@ import { headersGlobal } from "../stdlib/headers.js"
import { iteratorGlobals } from "../stdlib/iterator.js"
import { coercion } from "../stdlib/value.js"
import { base64Global, cryptoGlobal, structuredCloneGlobal } from "../stdlib/web.js"
-import { ToolReference } from "../../tool-runtime.js"
+import { ToolReference } from "../tool-runtime.js"
import { errorGlobal } from "./errors.js"
import { errorTypes } from "./intrinsics.js"
import { constants, constructor, methods, native, receiver } from "./native.js"
diff --git a/packages/codemode/src/vm/runtime/interpreter.ts b/packages/codemode/src/runtime/interpreter.ts
similarity index 98%
rename from packages/codemode/src/vm/runtime/interpreter.ts
rename to packages/codemode/src/runtime/interpreter.ts
index 8522a6e2b819..f546d804600a 100644
--- a/packages/codemode/src/vm/runtime/interpreter.ts
+++ b/packages/codemode/src/runtime/interpreter.ts
@@ -1,4 +1,4 @@
-import type { ToolRuntime } from "../../tool-runtime.js"
+import type { ToolRuntime } from "../tool-runtime.js"
import type { ExtensionRequest } from "../scheduler.js"
import type { HostBridge } from "../snapshot/codec.js"
import { Vm } from "../vm.js"
diff --git a/packages/codemode/src/vm/runtime/intrinsic-names.ts b/packages/codemode/src/runtime/intrinsic-names.ts
similarity index 100%
rename from packages/codemode/src/vm/runtime/intrinsic-names.ts
rename to packages/codemode/src/runtime/intrinsic-names.ts
diff --git a/packages/codemode/src/vm/runtime/intrinsics.ts b/packages/codemode/src/runtime/intrinsics.ts
similarity index 100%
rename from packages/codemode/src/vm/runtime/intrinsics.ts
rename to packages/codemode/src/runtime/intrinsics.ts
diff --git a/packages/codemode/src/vm/runtime/limits.ts b/packages/codemode/src/runtime/limits.ts
similarity index 100%
rename from packages/codemode/src/vm/runtime/limits.ts
rename to packages/codemode/src/runtime/limits.ts
diff --git a/packages/codemode/src/vm/runtime/model.ts b/packages/codemode/src/runtime/model.ts
similarity index 98%
rename from packages/codemode/src/vm/runtime/model.ts
rename to packages/codemode/src/runtime/model.ts
index bbdccc41ccf7..e40187d78cbf 100644
--- a/packages/codemode/src/vm/runtime/model.ts
+++ b/packages/codemode/src/runtime/model.ts
@@ -1,6 +1,6 @@
import type { Node } from "acorn"
import type { ErrorType } from "./intrinsics.js"
-import type { DiagnosticKind } from "../../codemode.js"
+import type { DiagnosticKind } from "../codemode.js"
import type { ErrorObj, Value } from "./objects.js"
/** Any parsed node; the compiler narrows on `type`, and diagnostics read `loc`. */
diff --git a/packages/codemode/src/vm/runtime/modules.ts b/packages/codemode/src/runtime/modules.ts
similarity index 100%
rename from packages/codemode/src/vm/runtime/modules.ts
rename to packages/codemode/src/runtime/modules.ts
diff --git a/packages/codemode/src/vm/runtime/native.ts b/packages/codemode/src/runtime/native.ts
similarity index 100%
rename from packages/codemode/src/vm/runtime/native.ts
rename to packages/codemode/src/runtime/native.ts
diff --git a/packages/codemode/src/vm/runtime/objects.ts b/packages/codemode/src/runtime/objects.ts
similarity index 99%
rename from packages/codemode/src/vm/runtime/objects.ts
rename to packages/codemode/src/runtime/objects.ts
index cef4d7ae3af9..ad09b37256bd 100644
--- a/packages/codemode/src/vm/runtime/objects.ts
+++ b/packages/codemode/src/runtime/objects.ts
@@ -1,4 +1,4 @@
-import { ToolReference } from "../../tool-runtime.js"
+import { ToolReference } from "../tool-runtime.js"
import type { Builtins } from "./intrinsics.js"
import { checkArrayLength } from "./limits.js"
import {
diff --git a/packages/codemode/src/vm/runtime/operations.ts b/packages/codemode/src/runtime/operations.ts
similarity index 99%
rename from packages/codemode/src/vm/runtime/operations.ts
rename to packages/codemode/src/runtime/operations.ts
index 01cf75ca0394..93d772b72e84 100644
--- a/packages/codemode/src/vm/runtime/operations.ts
+++ b/packages/codemode/src/runtime/operations.ts
@@ -1,5 +1,5 @@
import type { Expression, MemberExpression, NewExpression, Super } from "acorn"
-import { ToolReference } from "../../tool-runtime.js"
+import { ToolReference } from "../tool-runtime.js"
import { type AstNode, invalidData, typeError } from "./model.js"
import { checkStringLength } from "./limits.js"
import { locate } from "./errors.js"
diff --git a/packages/codemode/src/vm/runtime/promises.ts b/packages/codemode/src/runtime/promises.ts
similarity index 100%
rename from packages/codemode/src/vm/runtime/promises.ts
rename to packages/codemode/src/runtime/promises.ts
diff --git a/packages/codemode/src/vm/runtime/references.ts b/packages/codemode/src/runtime/references.ts
similarity index 97%
rename from packages/codemode/src/vm/runtime/references.ts
rename to packages/codemode/src/runtime/references.ts
index 05cf8427f6e9..c2c4a25bcd5c 100644
--- a/packages/codemode/src/vm/runtime/references.ts
+++ b/packages/codemode/src/runtime/references.ts
@@ -1,4 +1,4 @@
-import { ToolReference } from "../../tool-runtime.js"
+import { ToolReference } from "../tool-runtime.js"
import { invalidData } from "./model.js"
import { Callable, getOwn, isRuntimeReference, Obj, Opaque, ownKeys, type Value } from "./objects.js"
diff --git a/packages/codemode/src/vm/runtime/signals.ts b/packages/codemode/src/runtime/signals.ts
similarity index 100%
rename from packages/codemode/src/vm/runtime/signals.ts
rename to packages/codemode/src/runtime/signals.ts
diff --git a/packages/codemode/src/vm/runtime/source.ts b/packages/codemode/src/runtime/source.ts
similarity index 100%
rename from packages/codemode/src/vm/runtime/source.ts
rename to packages/codemode/src/runtime/source.ts
diff --git a/packages/codemode/src/vm/runtime/table.ts b/packages/codemode/src/runtime/table.ts
similarity index 100%
rename from packages/codemode/src/vm/runtime/table.ts
rename to packages/codemode/src/runtime/table.ts
diff --git a/packages/codemode/src/scan.ts b/packages/codemode/src/scan.ts
index 4313acb11c40..3e6d499e331f 100644
--- a/packages/codemode/src/scan.ts
+++ b/packages/codemode/src/scan.ts
@@ -1,8 +1,8 @@
import type { AnyNode, BlockStatement, ModuleDeclaration, Pattern, Program, Statement } from "acorn"
import { Result } from "effect"
import type { Diagnostic } from "./codemode.js"
-import { parseProgram } from "./vm/runtime/execute.js"
-import { formatLocation } from "./vm/runtime/model.js"
+import { parseProgram } from "./runtime/execute.js"
+import { formatLocation } from "./runtime/model.js"
/**
* Extracts every `tools.` referenced by a Code Mode program, in first-seen order. Fails on syntax errors,
diff --git a/packages/codemode/src/vm/scheduler.ts b/packages/codemode/src/scheduler.ts
similarity index 99%
rename from packages/codemode/src/vm/scheduler.ts
rename to packages/codemode/src/scheduler.ts
index 9de0cddd576f..3d372013db8a 100644
--- a/packages/codemode/src/vm/scheduler.ts
+++ b/packages/codemode/src/scheduler.ts
@@ -1,5 +1,5 @@
import type { Json } from "./data.js"
-import type { ExtensionInvocation } from "../tool-runtime.js"
+import type { ExtensionInvocation } from "./tool-runtime.js"
import { locate } from "./runtime/errors.js"
import type { AstNode } from "./runtime/model.js"
import type { Callable, Cursor, GeneratorObj, Obj, PromiseObj, Value } from "./runtime/objects.js"
diff --git a/packages/codemode/src/vm/snapshot.ts b/packages/codemode/src/snapshot.ts
similarity index 99%
rename from packages/codemode/src/vm/snapshot.ts
rename to packages/codemode/src/snapshot.ts
index a61d0e920eb3..cc8c5b7835e6 100644
--- a/packages/codemode/src/vm/snapshot.ts
+++ b/packages/codemode/src/snapshot.ts
@@ -1,4 +1,4 @@
-import packageJson from "../../package.json" with { type: "json" }
+import packageJson from "../package.json" with { type: "json" }
import type { Interruption } from "./runtime/signals.js"
import { staticNames, unchanged } from "./runtime/intrinsic-names.js"
import { Fn, Obj } from "./runtime/objects.js"
diff --git a/packages/codemode/src/vm/snapshot/codec.ts b/packages/codemode/src/snapshot/codec.ts
similarity index 98%
rename from packages/codemode/src/vm/snapshot/codec.ts
rename to packages/codemode/src/snapshot/codec.ts
index f48a02918796..4345a199dfa9 100644
--- a/packages/codemode/src/vm/snapshot/codec.ts
+++ b/packages/codemode/src/snapshot/codec.ts
@@ -39,8 +39,8 @@ import { deleted, OrderedTable } from "../runtime/table.js"
import { AsyncFromSyncIterator } from "../generators.js"
import { HostCall, Resolving } from "../scheduler.js"
import { TextDecoderObj } from "../stdlib/bytes.js"
-import { ToolError, toolError } from "../../tool-error.js"
-import { ToolReference, ToolRuntimeError } from "../../tool-runtime.js"
+import { ToolError, toolError } from "../tool-error.js"
+import { ToolReference, ToolRuntimeError } from "../tool-runtime.js"
// A graph codec for a run's state: every object reachable from the roots becomes one record, so identity, sharing,
// and cycles survive, and every value inside a record is tagged JSON. Built-ins, AST nodes, bytecode, and the VM's
@@ -57,7 +57,7 @@ export type Json = null | boolean | number | string | ReadonlyArray | { re
* - `["s", name]` an interpreter symbol;
* - `["i", name]` a built-in or host global, unchanged since the runtime was made;
* - `["a", source, index]` an AST node (a call site, an error's location);
- * - `["x", data]` something the engine names itself (the VM's compiled code, by source and function index);
+ * - `["x", data]` something the VM names itself (compiled code, by source and function index);
* - `["r", id]` another record.
*/
export type Encoded = string | number | boolean | null | ReadonlyArray
@@ -110,9 +110,9 @@ export type EncodeEnv = {
readonly lost: Array
readonly strict: boolean
readonly hosts?: HostBridge | undefined
- /** More classes to save, an engine's own (the VM's frames and closures), after the built-in ones. */
+ /** More classes to save (the VM's frames and closures), after the built-in ones. */
readonly specs?: ReadonlyArray | undefined
- /** The data an engine names an object or symbol by, saved as `["x", data]`, instead of copying it. */
+ /** The data the VM names an object or symbol by, saved as `["x", data]`, instead of copying it. */
readonly external?: ((value: object | symbol) => Json | undefined) | undefined
}
diff --git a/packages/codemode/src/vm/snapshot/snapshot.ts b/packages/codemode/src/snapshot/snapshot.ts
similarity index 97%
rename from packages/codemode/src/vm/snapshot/snapshot.ts
rename to packages/codemode/src/snapshot/snapshot.ts
index 238bafdff4f6..c911ac61f79f 100644
--- a/packages/codemode/src/vm/snapshot/snapshot.ts
+++ b/packages/codemode/src/snapshot/snapshot.ts
@@ -1,5 +1,5 @@
import type { Interpreter } from "../runtime/interpreter.js"
-import type { ToolCall } from "../../tool-runtime.js"
+import type { ToolCall } from "../tool-runtime.js"
import { type Encoded, type Record, SnapshotError } from "./codec.js"
export { SnapshotError }
@@ -16,7 +16,7 @@ export const fromBytes = (bytes: Uint8Array): unknown => {
}
}
-/** The snapshot format this build writes and reads: the bytecode VM's (see `src/vm/snapshot.ts`). */
+/** The snapshot format this build writes and reads (see `src/snapshot.ts`). */
export const FORMAT = 2
/**
diff --git a/packages/codemode/src/vm/stdlib/array.ts b/packages/codemode/src/stdlib/array.ts
similarity index 99%
rename from packages/codemode/src/vm/stdlib/array.ts
rename to packages/codemode/src/stdlib/array.ts
index 1799066113fc..fbd300a82e48 100644
--- a/packages/codemode/src/vm/stdlib/array.ts
+++ b/packages/codemode/src/stdlib/array.ts
@@ -23,7 +23,7 @@ import {
import { describeValue, rejectCircularInsertion } from "../runtime/references.js"
import { requireCallback, withPrimitives } from "../runtime/callback.js"
import type { Interpreter } from "../runtime/interpreter.js"
-import { compareText } from "../../tool-runtime.js"
+import { compareText } from "../tool-runtime.js"
const arrayLikeSource = (source: Value): { readonly length: number; readonly source: Obj } => {
// JS would treat a promise as an empty array-like; that would hide a missing `await`.
diff --git a/packages/codemode/src/vm/stdlib/bytes.ts b/packages/codemode/src/stdlib/bytes.ts
similarity index 100%
rename from packages/codemode/src/vm/stdlib/bytes.ts
rename to packages/codemode/src/stdlib/bytes.ts
diff --git a/packages/codemode/src/vm/stdlib/collections.ts b/packages/codemode/src/stdlib/collections.ts
similarity index 100%
rename from packages/codemode/src/vm/stdlib/collections.ts
rename to packages/codemode/src/stdlib/collections.ts
diff --git a/packages/codemode/src/vm/stdlib/console.ts b/packages/codemode/src/stdlib/console.ts
similarity index 98%
rename from packages/codemode/src/vm/stdlib/console.ts
rename to packages/codemode/src/stdlib/console.ts
index c4e4f7fd68c8..34ff060368e4 100644
--- a/packages/codemode/src/vm/stdlib/console.ts
+++ b/packages/codemode/src/stdlib/console.ts
@@ -1,6 +1,6 @@
import { type Method, methods } from "../runtime/native.js"
import { entries, get, Arr, Obj, type Value } from "../runtime/objects.js"
-import { ToolReference } from "../../tool-runtime.js"
+import { ToolReference } from "../tool-runtime.js"
import { containsOpaqueReference } from "../runtime/references.js"
import type { Interpreter } from "../runtime/interpreter.js"
diff --git a/packages/codemode/src/vm/stdlib/date.ts b/packages/codemode/src/stdlib/date.ts
similarity index 100%
rename from packages/codemode/src/vm/stdlib/date.ts
rename to packages/codemode/src/stdlib/date.ts
diff --git a/packages/codemode/src/vm/stdlib/headers.ts b/packages/codemode/src/stdlib/headers.ts
similarity index 100%
rename from packages/codemode/src/vm/stdlib/headers.ts
rename to packages/codemode/src/stdlib/headers.ts
diff --git a/packages/codemode/src/vm/stdlib/iterator.ts b/packages/codemode/src/stdlib/iterator.ts
similarity index 100%
rename from packages/codemode/src/vm/stdlib/iterator.ts
rename to packages/codemode/src/stdlib/iterator.ts
diff --git a/packages/codemode/src/vm/stdlib/json.ts b/packages/codemode/src/stdlib/json.ts
similarity index 100%
rename from packages/codemode/src/vm/stdlib/json.ts
rename to packages/codemode/src/stdlib/json.ts
diff --git a/packages/codemode/src/vm/stdlib/math.ts b/packages/codemode/src/stdlib/math.ts
similarity index 100%
rename from packages/codemode/src/vm/stdlib/math.ts
rename to packages/codemode/src/stdlib/math.ts
diff --git a/packages/codemode/src/vm/stdlib/number.ts b/packages/codemode/src/stdlib/number.ts
similarity index 100%
rename from packages/codemode/src/vm/stdlib/number.ts
rename to packages/codemode/src/stdlib/number.ts
diff --git a/packages/codemode/src/vm/stdlib/object.ts b/packages/codemode/src/stdlib/object.ts
similarity index 99%
rename from packages/codemode/src/vm/stdlib/object.ts
rename to packages/codemode/src/stdlib/object.ts
index 09e8482a6a19..60886115eaa5 100644
--- a/packages/codemode/src/vm/stdlib/object.ts
+++ b/packages/codemode/src/stdlib/object.ts
@@ -22,7 +22,7 @@ import { primitivePrototype } from "../runtime/intrinsics.js"
import { describeValue, rejectCircularInsertion } from "../runtime/references.js"
import { invokeMethod } from "../runtime/callback.js"
import type { Interpreter } from "../runtime/interpreter.js"
-import { ToolReference } from "../../tool-runtime.js"
+import { ToolReference } from "../tool-runtime.js"
// ToObject for enumeration.
export const enumerableSource = (ctx: Interpreter, label: string, value: Value, node?: AstNode): Obj => {
diff --git a/packages/codemode/src/vm/stdlib/regexp.ts b/packages/codemode/src/stdlib/regexp.ts
similarity index 100%
rename from packages/codemode/src/vm/stdlib/regexp.ts
rename to packages/codemode/src/stdlib/regexp.ts
diff --git a/packages/codemode/src/vm/stdlib/string.ts b/packages/codemode/src/stdlib/string.ts
similarity index 100%
rename from packages/codemode/src/vm/stdlib/string.ts
rename to packages/codemode/src/stdlib/string.ts
diff --git a/packages/codemode/src/vm/stdlib/url.ts b/packages/codemode/src/stdlib/url.ts
similarity index 100%
rename from packages/codemode/src/vm/stdlib/url.ts
rename to packages/codemode/src/stdlib/url.ts
diff --git a/packages/codemode/src/vm/stdlib/value.ts b/packages/codemode/src/stdlib/value.ts
similarity index 100%
rename from packages/codemode/src/vm/stdlib/value.ts
rename to packages/codemode/src/stdlib/value.ts
diff --git a/packages/codemode/src/vm/stdlib/web.ts b/packages/codemode/src/stdlib/web.ts
similarity index 98%
rename from packages/codemode/src/vm/stdlib/web.ts
rename to packages/codemode/src/stdlib/web.ts
index 4c18668d9739..75b62f8c7722 100644
--- a/packages/codemode/src/vm/stdlib/web.ts
+++ b/packages/codemode/src/stdlib/web.ts
@@ -24,7 +24,7 @@ import {
import { createErrorValue, isErrorType } from "../runtime/intrinsics.js"
import { describeValue } from "../runtime/references.js"
import type { Interpreter } from "../runtime/interpreter.js"
-import { ToolReference } from "../../tool-runtime.js"
+import { ToolReference } from "../tool-runtime.js"
// WebIDL DOMString conversion: a missing argument is a TypeError, anything else stringifies. Invalid input is a
// TypeError as well; browsers throw a DOMException named InvalidCharacterError, which CodeMode does not have.
diff --git a/packages/codemode/src/tool-runtime.ts b/packages/codemode/src/tool-runtime.ts
index 26823b10c53e..8910a44c6b83 100644
--- a/packages/codemode/src/tool-runtime.ts
+++ b/packages/codemode/src/tool-runtime.ts
@@ -1,5 +1,5 @@
import { Cause, Effect, Exit, Formatter, Schema } from "effect"
-import type { Json } from "./vm/data.js"
+import type { Json } from "./data.js"
import type { DiagnosticKind } from "./codemode.js"
import { toolError } from "./tool-error.js"
import {
diff --git a/packages/codemode/src/vm/vm.ts b/packages/codemode/src/vm.ts
similarity index 99%
rename from packages/codemode/src/vm/vm.ts
rename to packages/codemode/src/vm.ts
index de0842903b77..fc6003ed8d12 100644
--- a/packages/codemode/src/vm/vm.ts
+++ b/packages/codemode/src/vm.ts
@@ -1,5 +1,5 @@
import { parse, type Expression, type MemberExpression, type NewExpression } from "acorn"
-import type { Diagnostic } from "../codemode.js"
+import type { Diagnostic } from "./codemode.js"
import { conversions } from "./runtime/callback.js"
import { locate, materialize } from "./runtime/errors.js"
import type { Interpreter } from "./runtime/interpreter.js"
@@ -81,7 +81,7 @@ import type { HostCall, Stop } from "./scheduler.js"
import { compiledPrelude } from "./prelude/prelude.js"
import { constructRegExp } from "./stdlib/regexp.js"
import { enumerableSource } from "./stdlib/object.js"
-import { ToolReference } from "../tool-runtime.js"
+import { ToolReference } from "./tool-runtime.js"
import { registerAsyncIntrinsics, type SettlingTarget, VmScheduler } from "./async.js"
import type { Code } from "./code.js"
import { type CaptureOptions, captureVm, type RestoreOptions, restoreVm } from "./snapshot.js"
diff --git a/packages/codemode/test/array-callbacks-test262.test.ts b/packages/codemode/test/array-callbacks-test262.test.ts
index a538072bfe6f..4dd980095165 100644
--- a/packages/codemode/test/array-callbacks-test262.test.ts
+++ b/packages/codemode/test/array-callbacks-test262.test.ts
@@ -56,7 +56,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/array-core-test262.test.ts b/packages/codemode/test/array-core-test262.test.ts
index 1b436b5f3dac..b1c3d67447a6 100644
--- a/packages/codemode/test/array-core-test262.test.ts
+++ b/packages/codemode/test/array-core-test262.test.ts
@@ -69,7 +69,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/vm/build-id.test.ts b/packages/codemode/test/build-id.test.ts
similarity index 87%
rename from packages/codemode/test/vm/build-id.test.ts
rename to packages/codemode/test/build-id.test.ts
index cac3e5ad9b31..27c84b726e74 100644
--- a/packages/codemode/test/vm/build-id.test.ts
+++ b/packages/codemode/test/build-id.test.ts
@@ -4,7 +4,7 @@ import path from "node:path"
// The snapshot build id hashes only the package's own bytecode, codecs, and built-ins, so it is the same in every
// process, whatever it imported first.
-const root = path.join(import.meta.dir, "../..")
+const root = path.join(import.meta.dir, "..")
const output = async (command: Array) => {
const child = Bun.spawn(command, { cwd: root, stdout: "pipe", stderr: "pipe" })
@@ -15,7 +15,7 @@ const output = async (command: Array) => {
describe("build id", () => {
test("the build id is the same whatever a process imported first", async () => {
- const fixture = path.join(import.meta.dir, "../fixtures/build-id.ts")
+ const fixture = path.join(import.meta.dir, "fixtures/build-id.ts")
const ids = await Promise.all(
[[], ["--preload", "./test/test262/run.ts"], ["--preload", "./src/index.ts"]].map((preload) =>
output(["bun", ...preload, fixture]),
@@ -28,6 +28,6 @@ describe("build id", () => {
// A process with the test262 harness loaded saves the run; the child that resumes it has not loaded it.
test("a run saved with the test262 harness loaded resumes in another process", async () => {
- await output(["bun", "test", "--preload", "./test/test262/run.ts", "test/vm/suspend.test.ts", "-t", "another process"])
+ await output(["bun", "test", "--preload", "./test/test262/run.ts", "test/suspend.test.ts", "-t", "another process"])
}, 15_000)
})
diff --git a/packages/codemode/test/vm/limits.test.ts b/packages/codemode/test/bytecode-limits.test.ts
similarity index 97%
rename from packages/codemode/test/vm/limits.test.ts
rename to packages/codemode/test/bytecode-limits.test.ts
index bcb129767b22..7834457af059 100644
--- a/packages/codemode/test/vm/limits.test.ts
+++ b/packages/codemode/test/bytecode-limits.test.ts
@@ -1,13 +1,13 @@
import { describe, expect, test } from "bun:test"
-import { createBuiltins } from "../../src/vm/runtime/intrinsics.js"
-import { Interpreter } from "../../src/vm/runtime/interpreter.js"
-import type { ToolRuntime } from "../../src/tool-runtime.js"
-import { CodeBuilder, CodeSizeOverflow, hashOf } from "../../src/vm/code.js"
-import { compileSource } from "../../src/vm/compiler/compile.js"
-import { CodeFlags, EMPTY_CELLS, Op, packWord, PutKind } from "../../src/vm/opcodes.js"
-import { Mode } from "../../src/vm/vm.js"
-import { parseVmSource, type RunOptions, runProgram } from "./run.js"
-import { verifyAll, verifyCode } from "./verify.js"
+import { createBuiltins } from "../src/runtime/intrinsics.js"
+import { Interpreter } from "../src/runtime/interpreter.js"
+import type { ToolRuntime } from "../src/tool-runtime.js"
+import { CodeBuilder, CodeSizeOverflow, hashOf } from "../src/code.js"
+import { compileSource } from "../src/compiler/compile.js"
+import { CodeFlags, EMPTY_CELLS, Op, packWord, PutKind } from "../src/opcodes.js"
+import { Mode } from "../src/vm.js"
+import { parseVmSource, type RunOptions, runProgram } from "./run-program.js"
+import { verifyAll, verifyCode } from "./verify-bytecode.js"
const emptyTools = {
calls: [],
@@ -534,8 +534,9 @@ describe("per-function wide jumps past 65,535 words and snapshot round-trips", (
mainRes: [21, 10, expectedPadA * 2, 378, 13, 7, "late-reject", "ok"],
gSteps: [1, 10, 20, expectedGenPad + 4, 18],
})
- })
+ }, 15_000)
+ // Compiling a >65,535-word program and round-tripping 8 full snapshots takes ~8-9s on loaded Windows runners.
test("top-level script >65,535 words runs correctly and survives snapshot round-trips at pc > 65,535", () => {
const src = `
function hoistedTop(n) { return n + 42 }
@@ -602,5 +603,5 @@ describe("per-function wide jumps past 65,535 words and snapshot round-trips", (
expect(roundTripped).toEqual({ ok: true, value: expected, toolCalls: [] })
expect(trips).toBeGreaterThan(2)
expect(sawHighPc).toBe(true)
- })
+ }, 15_000)
})
diff --git a/packages/codemode/test/callbacks.test.ts b/packages/codemode/test/callbacks.test.ts
index 5b736205f8f2..9722ae19a1a7 100644
--- a/packages/codemode/test/callbacks.test.ts
+++ b/packages/codemode/test/callbacks.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Effect, Schema } from "effect"
-import { CodeMode, Tool } from "./lib/index.js"
+import { CodeMode, Tool } from "../src/index.js"
// Callback acceptance is one gate shared by array methods, sort, string replacers,
// Array.from mappers, Map/Set/URLSearchParams forEach, and promise reactions:
diff --git a/packages/codemode/test/codemode.test.ts b/packages/codemode/test/codemode.test.ts
index 4258ffa9c839..c9f4cd10015b 100644
--- a/packages/codemode/test/codemode.test.ts
+++ b/packages/codemode/test/codemode.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Cause, Effect, Schema } from "effect"
-import { CodeMode, Extension, Tool, toolError } from "./lib/index.js"
+import { CodeMode, Extension, Tool, toolError } from "../src/index.js"
const run = (tool: Tool.Tool) =>
Effect.runPromise(CodeMode.make({ tools: { host: { call: tool } } }).execute("return await tools.host.call({})"))
diff --git a/packages/codemode/test/constructor-test262.test.ts b/packages/codemode/test/constructor-test262.test.ts
index 368e71a883dc..c038f3f21c32 100644
--- a/packages/codemode/test/constructor-test262.test.ts
+++ b/packages/codemode/test/constructor-test262.test.ts
@@ -14,7 +14,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/date-test262.test.ts b/packages/codemode/test/date-test262.test.ts
index 04c5256c417d..ffda8cef4bf4 100644
--- a/packages/codemode/test/date-test262.test.ts
+++ b/packages/codemode/test/date-test262.test.ts
@@ -44,7 +44,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/enumeration.test.ts b/packages/codemode/test/enumeration.test.ts
index e5feef46d5c2..c46b6048d5be 100644
--- a/packages/codemode/test/enumeration.test.ts
+++ b/packages/codemode/test/enumeration.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Effect, Schema } from "effect"
-import { CodeMode, Tool } from "./lib/index.js"
+import { CodeMode, Tool } from "../src/index.js"
// Key enumeration: Object.keys and for...in share one surface over plain objects, arrays
// (index strings), and tool references (namespace/tool names from the supplied tools), so a
diff --git a/packages/codemode/test/errors.test.ts b/packages/codemode/test/errors.test.ts
index 4aa1636c288f..8cbb483c247a 100644
--- a/packages/codemode/test/errors.test.ts
+++ b/packages/codemode/test/errors.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
// One failure is one program error object, and rethrowing it keeps the diagnostic it started with.
const run = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/extensions.test.ts b/packages/codemode/test/extensions.test.ts
index 1dda15014319..5e66727559e0 100644
--- a/packages/codemode/test/extensions.test.ts
+++ b/packages/codemode/test/extensions.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Context, Effect, Schema } from "effect"
-import { CodeMode, Extension, Tool } from "./lib/index.js"
+import { CodeMode, Extension, Tool } from "../src/index.js"
const held: Array = []
const config = { retries: 3, nested: { deep: true } }
diff --git a/packages/codemode/test/fixtures/build-id.ts b/packages/codemode/test/fixtures/build-id.ts
index 47a2a0f4a35d..22b5b1018d6d 100644
--- a/packages/codemode/test/fixtures/build-id.ts
+++ b/packages/codemode/test/fixtures/build-id.ts
@@ -1,8 +1,8 @@
// Prints this process's snapshot build id, from a runtime made with as few of the package's modules as it takes, so
// the id can be compared across entry points (`bun --preload build-id.ts`).
-import { Interpreter } from "../../src/vm/runtime/interpreter.js"
-import { createBuiltins } from "../../src/vm/runtime/intrinsics.js"
-import { buildId } from "../../src/vm/snapshot.js"
+import { Interpreter } from "../../src/runtime/interpreter.js"
+import { createBuiltins } from "../../src/runtime/intrinsics.js"
+import { buildId } from "../../src/snapshot.js"
import { ToolRuntime } from "../../src/tool-runtime.js"
new Interpreter({ tools: ToolRuntime.make(ToolRuntime.prepare({}), undefined, {}), builtins: createBuiltins() })
diff --git a/packages/codemode/test/fixtures/prelude-roundtrip.ts b/packages/codemode/test/fixtures/prelude-roundtrip.ts
index 026c320919d3..e3f52f35f73a 100644
--- a/packages/codemode/test/fixtures/prelude-roundtrip.ts
+++ b/packages/codemode/test/fixtures/prelude-roundtrip.ts
@@ -2,9 +2,9 @@
// prelude frame was on the stack.
import { Effect } from "effect"
import { CodeMode } from "../../src/index.js"
-import { CodeFlags } from "../../src/vm/opcodes.js"
-import { setRoundTrip } from "../../src/vm/runtime/execute.js"
-import { Vm } from "../../src/vm/vm.js"
+import { CodeFlags } from "../../src/opcodes.js"
+import { setRoundTrip } from "../../src/runtime/execute.js"
+import { Vm } from "../../src/vm.js"
setRoundTrip(true)
diff --git a/packages/codemode/test/for-await-test262.test.ts b/packages/codemode/test/for-await-test262.test.ts
index 0863b1827c71..fcbbcb85ccb9 100644
--- a/packages/codemode/test/for-await-test262.test.ts
+++ b/packages/codemode/test/for-await-test262.test.ts
@@ -14,7 +14,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const execute = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/generator-test262.test.ts b/packages/codemode/test/generator-test262.test.ts
index b8569713ddbb..9afa501c215e 100644
--- a/packages/codemode/test/generator-test262.test.ts
+++ b/packages/codemode/test/generator-test262.test.ts
@@ -12,7 +12,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const execute = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/groupby-test262.test.ts b/packages/codemode/test/groupby-test262.test.ts
index 152ec86bede7..bf27ad846e94 100644
--- a/packages/codemode/test/groupby-test262.test.ts
+++ b/packages/codemode/test/groupby-test262.test.ts
@@ -30,7 +30,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const execute = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/json-callbacks-test262.test.ts b/packages/codemode/test/json-callbacks-test262.test.ts
index 8a0e16efa346..384ec6ece4b8 100644
--- a/packages/codemode/test/json-callbacks-test262.test.ts
+++ b/packages/codemode/test/json-callbacks-test262.test.ts
@@ -28,7 +28,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/labeled-control-test262.test.ts b/packages/codemode/test/labeled-control-test262.test.ts
index 8d7196ca06e4..37866b17cb4b 100644
--- a/packages/codemode/test/labeled-control-test262.test.ts
+++ b/packages/codemode/test/labeled-control-test262.test.ts
@@ -12,7 +12,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const execute = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/lexical-test262.test.ts b/packages/codemode/test/lexical-test262.test.ts
index 0666e6da6501..6f67a9acb9b1 100644
--- a/packages/codemode/test/lexical-test262.test.ts
+++ b/packages/codemode/test/lexical-test262.test.ts
@@ -26,7 +26,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/lib/index.ts b/packages/codemode/test/lib/index.ts
deleted file mode 100644
index 53fe6d36e96f..000000000000
--- a/packages/codemode/test/lib/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "../../src/index.js"
diff --git a/packages/codemode/test/limits.test.ts b/packages/codemode/test/limits.test.ts
index 7cc035b31108..781089e398cc 100644
--- a/packages/codemode/test/limits.test.ts
+++ b/packages/codemode/test/limits.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test"
import { Cause, Deferred, Effect, Exit, Fiber, Schema } from "effect"
-import { CodeMode, Tool } from "./lib/index.js"
-import { MAX_ARRAY_LENGTH, MAX_PENDING_PROMISES, MAX_STRING_LENGTH } from "../src/vm/runtime/limits.js"
+import { CodeMode, Tool } from "../src/index.js"
+import { MAX_ARRAY_LENGTH, MAX_PENDING_PROMISES, MAX_STRING_LENGTH } from "../src/runtime/limits.js"
const runtime = CodeMode.make({ tools: {} })
@@ -40,7 +40,7 @@ describe("one built-in cannot build an unbounded value", () => {
})
// split and matchAll share the same result check but must build ten million items first to reach it,
- // which is too slow for CI.
+ // which is too slow for CI; flat() over MAX_ARRAY_LENGTH (10M) elements still needs a 15s budget on Windows.
test("arrays: constructor, length, Array.from, concat, flat", async () => {
expect(await value(`return Array(${A}).length`)).toBe(A)
for (const code of [
@@ -54,7 +54,7 @@ describe("one built-in cannot build an unbounded value", () => {
"RangeError: Invalid array length",
)
}
- })
+ }, 15_000)
test("promises: too many pending at once, while settled ones do not count", async () => {
const n = MAX_PENDING_PROMISES
diff --git a/packages/codemode/test/new-expression.test.ts b/packages/codemode/test/new-expression.test.ts
index 1be0c5cd3372..0beafad48fba 100644
--- a/packages/codemode/test/new-expression.test.ts
+++ b/packages/codemode/test/new-expression.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Effect, Schema } from "effect"
-import { CodeMode, Tool } from "./lib/index.js"
+import { CodeMode, Tool } from "../src/index.js"
// `new` is supported syntax; only the callee decides whether construction succeeds. A callee without
// construction support is a TypeError naming it, like JS, rather than an unsupported-syntax diagnostic
diff --git a/packages/codemode/test/object-coercion-test262.test.ts b/packages/codemode/test/object-coercion-test262.test.ts
index d89133ae5a56..adba9e8bd624 100644
--- a/packages/codemode/test/object-coercion-test262.test.ts
+++ b/packages/codemode/test/object-coercion-test262.test.ts
@@ -37,7 +37,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/openapi.test.ts b/packages/codemode/test/openapi.test.ts
index 3a3203853290..e82484ea6c9a 100644
--- a/packages/codemode/test/openapi.test.ts
+++ b/packages/codemode/test/openapi.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test"
import { Effect, Layer, Option } from "effect"
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"
-import { CodeMode, OpenAPI, Tool } from "./lib/index.js"
+import { CodeMode, OpenAPI, Tool } from "../src/index.js"
import { inputTypeScript, outputTypeScript } from "../src/tool-schema.js"
const baseUrl = "http://localhost:4096"
diff --git a/packages/codemode/test/parity.test.ts b/packages/codemode/test/parity.test.ts
index 4d7bd129f268..72b00a447a53 100644
--- a/packages/codemode/test/parity.test.ts
+++ b/packages/codemode/test/parity.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
// Runs a CodeMode program with no host tools and returns the CodeMode.Result. These tests pin the
// JS-parity behaviors for the "99% of ordinary defensive JavaScript just works" goal: cases where
diff --git a/packages/codemode/test/preload.ts b/packages/codemode/test/preload.ts
index aa8ac22ade79..2f0994917152 100644
--- a/packages/codemode/test/preload.ts
+++ b/packages/codemode/test/preload.ts
@@ -1,5 +1,5 @@
-import { setRoundTrip } from "../src/vm/runtime/execute.js"
-import { nativeRule } from "../src/vm/runtime/objects.js"
+import { setRoundTrip } from "../src/runtime/execute.js"
+import { nativeRule } from "../src/runtime/objects.js"
// Every test run checks that natives are made only with the intrinsics.
nativeRule.check = true
diff --git a/packages/codemode/test/vm/prelude-bytecode.test.ts b/packages/codemode/test/prelude-bytecode.test.ts
similarity index 77%
rename from packages/codemode/test/vm/prelude-bytecode.test.ts
rename to packages/codemode/test/prelude-bytecode.test.ts
index 04d466f1588c..1f8ea7daa9c2 100644
--- a/packages/codemode/test/vm/prelude-bytecode.test.ts
+++ b/packages/codemode/test/prelude-bytecode.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, test } from "bun:test"
-import { compileBuiltins } from "../../script/prelude.js"
-import saved from "../../src/vm/prelude/bytecode.json" with { type: "json" }
-import { compiledPrelude } from "../../src/vm/prelude/prelude.js"
-import { hashOf } from "../../src/vm/code.js"
-import { getInternalPrelude } from "../../src/vm/internal-prelude.js"
-import { moduleUrl, runProgram } from "./run.js"
+import { compileBuiltins } from "../script/prelude.js"
+import saved from "../src/prelude/bytecode.json" with { type: "json" }
+import { compiledPrelude } from "../src/prelude/prelude.js"
+import { hashOf } from "../src/code.js"
+import { getInternalPrelude } from "../src/internal-prelude.js"
+import { moduleUrl, runProgram } from "./run-program.js"
// The built-in sources are compiled ahead of time (script/prelude.ts); a process loads that bytecode instead.
@@ -25,8 +25,8 @@ describe("precompiled built-ins", () => {
}
// A fresh process runs a program that calls into the prelude, and its source is still unparsed.
const script = `
- import { runProgram } from ${moduleUrl("run.js")}
- import { compiledPrelude } from ${moduleUrl("../../src/vm/prelude/prelude.js")}
+ import { runProgram } from ${moduleUrl("run-program.js")}
+ import { compiledPrelude } from ${moduleUrl("../src/prelude/prelude.js")}
const result = runProgram("return [3, 1, 2].map((x) => x * 2).sort((a, b) => a - b)")
console.log(JSON.stringify([result.ok && result.value, typeof compiledPrelude().codes[0].sourceObj.tree]))`
const child = Bun.spawn(["bun", "-e", script], { stdout: "pipe", stderr: "inherit" })
diff --git a/packages/codemode/test/promise-test262.test.ts b/packages/codemode/test/promise-test262.test.ts
index 130c85770bfe..d2b60659b2de 100644
--- a/packages/codemode/test/promise-test262.test.ts
+++ b/packages/codemode/test/promise-test262.test.ts
@@ -14,7 +14,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const execute = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {}, limits: { timeoutMs: 1_000 } }))
diff --git a/packages/codemode/test/promise.test.ts b/packages/codemode/test/promise.test.ts
index 4d84c77ec94c..947e3a50d69d 100644
--- a/packages/codemode/test/promise.test.ts
+++ b/packages/codemode/test/promise.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Cause, Deferred, Effect, Exit, Schema } from "effect"
-import { CodeMode, Tool, toolError } from "./lib/index.js"
+import { CodeMode, Tool, toolError } from "../src/index.js"
// Wave 5 acceptance suite: first-class promise values. Un-awaited tool calls start eagerly as
// host work, `await` settles them, Promise.all/allSettled/race/resolve/reject are
diff --git a/packages/codemode/test/regexp-math-test262.test.ts b/packages/codemode/test/regexp-math-test262.test.ts
index d12562d10b2a..bd85d3ef2db4 100644
--- a/packages/codemode/test/regexp-math-test262.test.ts
+++ b/packages/codemode/test/regexp-math-test262.test.ts
@@ -41,7 +41,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/vm/resumable.test.ts b/packages/codemode/test/resumable.test.ts
similarity index 95%
rename from packages/codemode/test/vm/resumable.test.ts
rename to packages/codemode/test/resumable.test.ts
index 8ab9ad6492bf..8bc794f4e3f2 100644
--- a/packages/codemode/test/vm/resumable.test.ts
+++ b/packages/codemode/test/resumable.test.ts
@@ -1,16 +1,16 @@
import { describe, expect, test } from "bun:test"
import path from "node:path"
-import { parseProgram } from "../../src/vm/runtime/execute.js"
-import { Interpreter } from "../../src/vm/runtime/interpreter.js"
-import { createBuiltins } from "../../src/vm/runtime/intrinsics.js"
-import { getOwn, Native, nativeRule, Obj, remove, set } from "../../src/vm/runtime/objects.js"
-import { CodeMode } from "../lib/index.js"
-import { decode, encode } from "../../src/vm/snapshot/codec.js"
-import { Lost, PendingThrow } from "../../src/vm/runtime/model.js"
-import { normalizeError } from "../../src/vm/runtime/errors.js"
+import { parseProgram } from "../src/runtime/execute.js"
+import { Interpreter } from "../src/runtime/interpreter.js"
+import { createBuiltins } from "../src/runtime/intrinsics.js"
+import { getOwn, Native, nativeRule, Obj, remove, set } from "../src/runtime/objects.js"
+import { CodeMode } from "../src/index.js"
+import { decode, encode } from "../src/snapshot/codec.js"
+import { Lost, PendingThrow } from "../src/runtime/model.js"
+import { normalizeError } from "../src/runtime/errors.js"
import { Effect } from "effect"
-import { ToolRuntime } from "../../src/tool-runtime.js"
-import { nodeId, sourceOf } from "../../src/vm/runtime/source.js"
+import { ToolRuntime } from "../src/tool-runtime.js"
+import { nodeId, sourceOf } from "../src/runtime/source.js"
// Groundwork for suspending and resuming a run: everything the state refers to has a stable name.
@@ -281,7 +281,7 @@ describe("heap as data", () => {
describe("prelude", () => {
test("a run saved and restored while prelude built-ins run continues in their frames", async () => {
- const child = Bun.spawn(["bun", path.join(import.meta.dir, "../fixtures/prelude-roundtrip.ts")], {
+ const child = Bun.spawn(["bun", path.join(import.meta.dir, "fixtures/prelude-roundtrip.ts")], {
stdout: "pipe",
stderr: "inherit",
})
@@ -320,7 +320,6 @@ describe("lost values", () => {
unchanged: () => false,
anchorOf: () => undefined,
nodeId: () => undefined,
- astArray: () => undefined,
lost,
strict: false,
})
@@ -328,7 +327,6 @@ describe("lost values", () => {
named: () => undefined,
anchor: () => undefined,
node: () => undefined,
- astArray: () => undefined,
interruption: () => {
throw new Error("no interruption is saved")
},
diff --git a/packages/codemode/test/vm/run.ts b/packages/codemode/test/run-program.ts
similarity index 54%
rename from packages/codemode/test/vm/run.ts
rename to packages/codemode/test/run-program.ts
index 933358ef3285..6277b8d88cad 100644
--- a/packages/codemode/test/vm/run.ts
+++ b/packages/codemode/test/run-program.ts
@@ -1,18 +1,19 @@
import path from "node:path"
import { pathToFileURL } from "node:url"
-import { parse, type Program } from "acorn"
-import type { DataValue, Diagnostic, Result } from "../../src/codemode.js"
-import { normalizeError } from "../../src/vm/runtime/errors.js"
-import { createBuiltins } from "../../src/vm/runtime/intrinsics.js"
-import { Interpreter } from "../../src/vm/runtime/interpreter.js"
-import { formatLocation, PendingThrow, sourceLocation } from "../../src/vm/runtime/model.js"
-import type { Value } from "../../src/vm/runtime/objects.js"
-import { Interruption } from "../../src/vm/runtime/signals.js"
-import { Source } from "../../src/vm/runtime/source.js"
-import type { ToolRuntime } from "../../src/tool-runtime.js"
-import type { Snapshot } from "../../src/vm/snapshot/snapshot.js"
+import type { Program } from "acorn"
+import type { DataValue, Diagnostic, Result } from "../src/codemode.js"
+import { normalizeError } from "../src/runtime/errors.js"
+import { parseProgram } from "../src/runtime/execute.js"
+import { createBuiltins } from "../src/runtime/intrinsics.js"
+import { Interpreter } from "../src/runtime/interpreter.js"
+import { PendingThrow } from "../src/runtime/model.js"
+import type { Value } from "../src/runtime/objects.js"
+import { Interruption } from "../src/runtime/signals.js"
+import type { Source } from "../src/runtime/source.js"
+import type { ToolRuntime } from "../src/tool-runtime.js"
+import type { Snapshot } from "../src/snapshot/snapshot.js"
-/** A quoted `file:` URL for a module relative to `test/vm`, to import from a script run with `bun -e` on any platform. */
+/** A quoted `file:` URL for a module relative to `test`, to import from a script run with `bun -e` on any platform. */
export const moduleUrl = (relative: string) =>
JSON.stringify(pathToFileURL(path.join(import.meta.dir, relative)).href)
@@ -36,7 +37,6 @@ export type RunOptions = {
export const parseVmSource = (
code: string,
- id = "main",
):
| { readonly ok: true; readonly program: Program; readonly source: Source }
| { readonly ok: false; readonly error: Diagnostic } => {
@@ -44,38 +44,8 @@ export const parseVmSource = (
return { ok: false, error: { kind: "ParseError", message: "Code cannot be empty." } }
}
try {
- const program = parse(code, {
- ecmaVersion: "latest",
- sourceType: "script",
- allowReturnOutsideFunction: true,
- allowAwaitOutsideFunction: true,
- allowImportExportEverywhere: true,
- locations: true,
- })
- const exported = program.body.find((statement) => statement.type.startsWith("Export"))
- if (exported) {
- const location = sourceLocation(exported)
- return {
- ok: false,
- error: {
- kind: "ParseError",
- message: `SyntaxError: Exports aren't available. Return the result instead.${formatLocation(location)}`,
- location,
- },
- }
- }
- return { ok: true, program, source: new Source(id, code, program) }
+ return parseProgram(code)
} catch (error) {
- if (error instanceof SyntaxError && "loc" in error) {
- const loc = (error as SyntaxError & { readonly loc: { readonly line: number; readonly column: number } }).loc
- const location = { line: loc.line, column: loc.column + 1 }
- const reason = error.message.replace(/ \(\d+:\d+\)$/, "")
- const text = `${reason.endsWith(".") ? reason : `${reason}.`} Code must be plain JavaScript written as a program body.`
- return {
- ok: false,
- error: { kind: "ParseError", message: `SyntaxError: ${text}${formatLocation(location)}`, location },
- }
- }
if (error instanceof RangeError) {
return { ok: false, error: normalizeError(error) }
}
@@ -173,49 +143,3 @@ export const runProgram = (code: string, options?: RunOptions): Result => {
}
}
}
-
-const WARMUP_SCRIPT = `
-function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2) }
-let sum = 0
-for (let i = 0; i < 400; i++) sum = (sum + i * 3) % 10007
-const closures = []
-for (let i = 0; i < 16; i++) {
- let s = "v" + i
- let o = { x: i, y: s }
- closures.push(() => o.x + s.length)
-}
-for (const fn of closures) sum += fn()
-const arr = Array.from({ length: 64 }, (_, i) => (i * 17) % 64)
-const mapped = arr.map((x) => x * 2).filter((x) => x % 3 !== 0)
-sum += mapped.reduce((a, b) => a + b, 0)
-const sorted = mapped.slice(0, 32).sort((a, b) => a - b)
-sum += sorted.length + fib(8)
-outer: for (let i = 0; i < 3; i++) {
- try {
- for (const x of [1, 2, 3]) {
- try {
- if (x === 2) continue
- if (i === 1 && x === 3) break outer
- sum += x
- } finally { sum += 1 }
- }
- } catch (e) { sum -= 1 } finally { sum += 2 }
-}
-const { a = 1, b: [c = 2, ...rest] = [3, 4, 5] } = { b: [10, 20, 30] }
-return sum + a + c + rest.length
-`
-
-let warmed = false
-
-/**
- * Startup training program (J3): exercises the VM dispatch loop with diverse types
- * (numbers, strings, objects, arrays, closures, cells, try/catch/finally, iteration, destructuring)
- * so JSC's DFG/FTL tiers up `Vm.prototype.exec` with polymorphic value profiles.
- */
-export const warmupVm = (rounds = 8): void => {
- if (warmed) return
- warmed = true
- for (let i = 0; i < rounds; i++) {
- runProgram(WARMUP_SCRIPT)
- }
-}
diff --git a/packages/codemode/test/scan.test.ts b/packages/codemode/test/scan.test.ts
index e4327f019e6c..f6a876901b11 100644
--- a/packages/codemode/test/scan.test.ts
+++ b/packages/codemode/test/scan.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Effect, Result } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
describe("CodeMode.scanTools", () => {
test("extracts dotted, bracketed and nested static tool calls in first-seen order", () => {
diff --git a/packages/codemode/test/set-methods-test262.test.ts b/packages/codemode/test/set-methods-test262.test.ts
index 2aa857ed8645..7d94aac1406e 100644
--- a/packages/codemode/test/set-methods-test262.test.ts
+++ b/packages/codemode/test/set-methods-test262.test.ts
@@ -71,7 +71,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/signature.test.ts b/packages/codemode/test/signature.test.ts
index 2594ebc160f2..ed41e9b02c21 100644
--- a/packages/codemode/test/signature.test.ts
+++ b/packages/codemode/test/signature.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Effect, Schema, SchemaGetter } from "effect"
-import { CodeMode, Tool } from "./lib/index.js"
+import { CodeMode, Tool } from "../src/index.js"
import {
decodeInput,
inputProperties,
diff --git a/packages/codemode/test/vm/snapshot.test.ts b/packages/codemode/test/snapshot.test.ts
similarity index 91%
rename from packages/codemode/test/vm/snapshot.test.ts
rename to packages/codemode/test/snapshot.test.ts
index a42e6e247ffd..509b9f47e2d2 100644
--- a/packages/codemode/test/vm/snapshot.test.ts
+++ b/packages/codemode/test/snapshot.test.ts
@@ -1,14 +1,14 @@
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "../../src/index.js"
-import { createBuiltins } from "../../src/vm/runtime/intrinsics.js"
-import { Interpreter } from "../../src/vm/runtime/interpreter.js"
-import { type Snapshot, SnapshotError } from "../../src/vm/snapshot/snapshot.js"
-import { ToolRuntime } from "../../src/tool-runtime.js"
-import { hashOf } from "../../src/vm/code.js"
-import { compileSource } from "../../src/vm/compiler/compile.js"
-import { moduleUrl, parseVmSource, runProgram } from "./run.js"
-import { buildId } from "../../src/vm/snapshot.js"
+import { CodeMode } from "../src/index.js"
+import { createBuiltins } from "../src/runtime/intrinsics.js"
+import { Interpreter } from "../src/runtime/interpreter.js"
+import { type Snapshot, SnapshotError } from "../src/snapshot/snapshot.js"
+import { ToolRuntime } from "../src/tool-runtime.js"
+import { hashOf } from "../src/code.js"
+import { compileSource } from "../src/compiler/compile.js"
+import { moduleUrl, parseVmSource, runProgram } from "./run-program.js"
+import { buildId } from "../src/snapshot.js"
// The VM's snapshots: a run saved and restored into a fresh runtime anywhere it slices goes on as if it never stopped.
@@ -268,13 +268,13 @@ describe("determinism", () => {
const codes = Object.values(programs)
const local = { hashes: codes.map((code) => hashOf(compileSource(parse(code)))), build: (runtime(), buildId()) }
const script = `
- import { hashOf } from ${moduleUrl("../../src/vm/code.js")}
- import { compileSource } from ${moduleUrl("../../src/vm/compiler/compile.js")}
- import { parseVmSource } from ${moduleUrl("run.js")}
- import { buildId } from ${moduleUrl("../../src/vm/snapshot.js")}
- import { createBuiltins } from ${moduleUrl("../../src/vm/runtime/intrinsics.js")}
- import { Interpreter } from ${moduleUrl("../../src/vm/runtime/interpreter.js")}
- import { ToolRuntime } from ${moduleUrl("../../src/tool-runtime.js")}
+ import { hashOf } from ${moduleUrl("../src/code.js")}
+ import { compileSource } from ${moduleUrl("../src/compiler/compile.js")}
+ import { parseVmSource } from ${moduleUrl("run-program.js")}
+ import { buildId } from ${moduleUrl("../src/snapshot.js")}
+ import { createBuiltins } from ${moduleUrl("../src/runtime/intrinsics.js")}
+ import { Interpreter } from ${moduleUrl("../src/runtime/interpreter.js")}
+ import { ToolRuntime } from ${moduleUrl("../src/tool-runtime.js")}
new Interpreter({ tools: ToolRuntime.make(ToolRuntime.prepare({}), undefined, {}), builtins: createBuiltins() })
const codes = ${JSON.stringify(codes)}
console.log(JSON.stringify({ hashes: codes.map((code) => hashOf(compileSource(parseVmSource(code).source))), build: buildId() }))`
diff --git a/packages/codemode/test/vm/state.test.ts b/packages/codemode/test/state.test.ts
similarity index 92%
rename from packages/codemode/test/vm/state.test.ts
rename to packages/codemode/test/state.test.ts
index 16eab1f96368..a085113421ba 100644
--- a/packages/codemode/test/vm/state.test.ts
+++ b/packages/codemode/test/state.test.ts
@@ -2,21 +2,21 @@ import { describe, expect, test } from "bun:test"
import { Glob } from "bun"
import path from "node:path"
import { Effect, Schema } from "effect"
-import { CodeMode, Tool } from "../lib/index.js"
-import { parseProgram } from "../../src/vm/runtime/execute.js"
-import { Interpreter } from "../../src/vm/runtime/interpreter.js"
-import { createBuiltins } from "../../src/vm/runtime/intrinsics.js"
-import { GeneratorObj, type Native, nativeRule, Obj, PromiseObj, type Value } from "../../src/vm/runtime/objects.js"
-import { normal } from "../../src/vm/runtime/signals.js"
-import { ToolRuntime } from "../../src/tool-runtime.js"
-import { Code } from "../../src/vm/code.js"
-import { AsyncFromSyncIterator } from "../../src/vm/generators.js"
-import { VmIntrinsic } from "../../src/vm/internal-prelude.js"
-import { Cell, CodeFlags } from "../../src/vm/opcodes.js"
-import type { Stop } from "../../src/vm/scheduler.js"
-import { CustomIter, Frame, Mode, Vm } from "../../src/vm/vm.js"
+import { CodeMode, Tool } from "../src/index.js"
+import { parseProgram } from "../src/runtime/execute.js"
+import { Interpreter } from "../src/runtime/interpreter.js"
+import { createBuiltins } from "../src/runtime/intrinsics.js"
+import { GeneratorObj, type Native, nativeRule, Obj, PromiseObj, type Value } from "../src/runtime/objects.js"
+import { normal } from "../src/runtime/signals.js"
+import { ToolRuntime } from "../src/tool-runtime.js"
+import { Code } from "../src/code.js"
+import { AsyncFromSyncIterator } from "../src/generators.js"
+import { VmIntrinsic } from "../src/internal-prelude.js"
+import { Cell, CodeFlags } from "../src/opcodes.js"
+import type { Stop } from "../src/scheduler.js"
+import { CustomIter, Frame, Mode, Vm } from "../src/vm.js"
-// The VM (`src/vm`) runs programs as bytecode frames, and keeps the jobs, promises, and host calls they wait on as
+// The VM (`src/vm.ts`) runs programs as bytecode frames, and keeps the jobs, promises, and host calls they wait on as
// data: a frame is its code, pc, and registers, and every suspension point is one. The Effect driver only does what
// the VM's stops ask.
@@ -218,6 +218,7 @@ describe("vm", () => {
expect(next).toEqual({ kind: "done", completion: normal(2450) })
})
+ // Sorting 300,000 strings (to cross multiple 65,536-item merge steps) with tripEvery = 1 takes ~7s on Windows CI.
test("a large default sort runs in bounded native steps, and sorts as JS does", () => {
const words = Array.from({ length: 300_000 }, (_, i) => ((i * 7919) % 300_007).toString(36))
const vm = vmFor(`
@@ -246,7 +247,7 @@ describe("vm", () => {
9100 in sorted,
]),
})
- })
+ }, 15_000)
test("concurrent tool calls stop the VM once, with every call in one batch", () => {
const vm = vmFor(`return await Promise.all([1, 2, 3].map((value) => tools.echo({ value })))`)
@@ -383,11 +384,24 @@ describe("vm", () => {
})
test("the VM does not import Effect", async () => {
- const root = path.join(import.meta.dir, "../..")
+ const root = path.join(import.meta.dir, "..")
+ const host = new Set([
+ "src/codemode.ts",
+ "src/extension.ts",
+ "src/scan.ts",
+ "src/tool-error.ts",
+ "src/tool-runtime.ts",
+ "src/tool-schema.ts",
+ "src/tool.ts",
+ "src/runtime/driver.ts",
+ "src/runtime/execute.ts",
+ "src/runtime/extensions.ts",
+ "src/runtime/signals.ts",
+ ])
// Glob paths use the platform's separator.
- const files = (await Array.fromAsync(new Glob("src/vm/**/*.ts").scan({ cwd: root }))).filter(
- (file) => !file.split(path.sep).join("/").startsWith("src/vm/runtime/"),
- )
+ const files = (await Array.fromAsync(new Glob("src/**/*.ts").scan({ cwd: root })))
+ .map((file) => file.split(path.sep).join("/"))
+ .filter((file) => !file.startsWith("src/openapi/") && !host.has(file))
expect(files.length).toBeGreaterThan(0)
for (const file of files) {
expect(await Bun.file(path.join(root, file)).text()).not.toMatch(/from "effect"/)
diff --git a/packages/codemode/test/stdlib.test.ts b/packages/codemode/test/stdlib.test.ts
index 9212fe34a04a..9c0d01672cce 100644
--- a/packages/codemode/test/stdlib.test.ts
+++ b/packages/codemode/test/stdlib.test.ts
@@ -16,7 +16,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect, Schema } from "effect"
-import { CodeMode, Tool } from "./lib/index.js"
+import { CodeMode, Tool } from "../src/index.js"
// Standard-library value types: Date, RegExp, Map, Set. Programs use them as ordinary JS;
// intra-CodeMode checkpoints (Object.* helpers, spread, coercion inputs) preserve the live
diff --git a/packages/codemode/test/string-core-test262.test.ts b/packages/codemode/test/string-core-test262.test.ts
index 30400130715e..9173fe352da4 100644
--- a/packages/codemode/test/string-core-test262.test.ts
+++ b/packages/codemode/test/string-core-test262.test.ts
@@ -151,7 +151,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
type Argument = string | number | undefined
type Outcome = "undefined" | "length" | "RangeError"
diff --git a/packages/codemode/test/string-date-methods-test262.test.ts b/packages/codemode/test/string-date-methods-test262.test.ts
index 24a5013c8ecf..417570527560 100644
--- a/packages/codemode/test/string-date-methods-test262.test.ts
+++ b/packages/codemode/test/string-date-methods-test262.test.ts
@@ -24,7 +24,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/string-regexp-test262.test.ts b/packages/codemode/test/string-regexp-test262.test.ts
index 513de982739b..fa0d6f709d6c 100644
--- a/packages/codemode/test/string-regexp-test262.test.ts
+++ b/packages/codemode/test/string-regexp-test262.test.ts
@@ -82,7 +82,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
type Vector = {
readonly path: string
diff --git a/packages/codemode/test/string-search-test262.test.ts b/packages/codemode/test/string-search-test262.test.ts
index 6abf045fe715..b596fc7bf9ae 100644
--- a/packages/codemode/test/string-search-test262.test.ts
+++ b/packages/codemode/test/string-search-test262.test.ts
@@ -102,7 +102,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/vm/suspend.test.ts b/packages/codemode/test/suspend.test.ts
similarity index 99%
rename from packages/codemode/test/vm/suspend.test.ts
rename to packages/codemode/test/suspend.test.ts
index e43c17a05268..7471f9b55d65 100644
--- a/packages/codemode/test/vm/suspend.test.ts
+++ b/packages/codemode/test/suspend.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test"
import { tmpdir } from "node:os"
import path from "node:path"
import { Context, Effect, Fiber, Schema } from "effect"
-import { CodeMode, Extension, Tool } from "../../src/index.js"
+import { CodeMode, Extension, Tool } from "../src/index.js"
// Suspending a run, saving its state, and resuming it in a brand-new runtime.
@@ -450,7 +450,7 @@ describe("suspend", () => {
test("the snapshot codec does not import Effect", async () => {
for (const file of ["codec.ts", "snapshot.ts"]) {
- expect(await Bun.file(path.join(import.meta.dir, "../../src/vm/snapshot", file)).text()).not.toMatch(
+ expect(await Bun.file(path.join(import.meta.dir, "../src/snapshot", file)).text()).not.toMatch(
/from "effect"/,
)
}
@@ -479,7 +479,7 @@ describe("resume", () => {
const file = path.join(tmpdir(), `codemode-${crypto.randomUUID()}.state`)
await Bun.write(file, CodeMode.toBytes(suspended.state))
try {
- const child = Bun.spawn(["bun", path.join(import.meta.dir, "../fixtures/resume-process.ts"), file], {
+ const child = Bun.spawn(["bun", path.join(import.meta.dir, "fixtures/resume-process.ts"), file], {
stdout: "pipe",
stderr: "inherit",
})
diff --git a/packages/codemode/test/test262/run.ts b/packages/codemode/test/test262/run.ts
index 0775e76517b7..1f8dd8d91ec5 100644
--- a/packages/codemode/test/test262/run.ts
+++ b/packages/codemode/test/test262/run.ts
@@ -1,15 +1,15 @@
-// Runs one vendored test262 file verbatim on the bytecode VM. The harness (assert, Test262Error, compareArray, $DONE,
+// Runs one vendored test262 file verbatim. The harness (assert, Test262Error, compareArray, $DONE,
// $DONOTEVALUATE) is host-provided, except `assert` itself: a program function made by the prelude, so that
// `assert.throws` can call the function it tests and catch what it throws as plain program code. Its checks and
// failure messages are the host's (`$assert`).
import path from "node:path"
import { Effect } from "effect"
-import { executeProgram } from "../../src/vm/runtime/execute.js"
-import type { Interpreter } from "../../src/vm/runtime/interpreter.js"
-import { Throw } from "../../src/vm/runtime/model.js"
-import { createErrorValue } from "../../src/vm/runtime/intrinsics.js"
-import { constructor, fn, methods } from "../../src/vm/runtime/native.js"
-import { Callable, define, get, hidden, Arr, Fn, Obj, type Value } from "../../src/vm/runtime/objects.js"
+import { finishExecution, startProgram } from "../../src/runtime/execute.js"
+import type { Interpreter } from "../../src/runtime/interpreter.js"
+import { Throw } from "../../src/runtime/model.js"
+import { createErrorValue } from "../../src/runtime/intrinsics.js"
+import { constructor, fn, methods } from "../../src/runtime/native.js"
+import { Callable, define, get, hidden, Arr, Fn, Obj, type Value } from "../../src/runtime/objects.js"
import { ToolRuntime } from "../../src/tool-runtime.js"
export const root = import.meta.dir
@@ -29,8 +29,11 @@ type Frontmatter = {
negative?: { phase: "parse" | "resolution" | "runtime"; type: string }
}
-const limits = { timeoutMs: 5000, maxToolCalls: undefined, maxOutputBytes: undefined }
-const prepared = ToolRuntime.prepare({})
+const setup = {
+ prepared: ToolRuntime.prepare({}),
+ limits: { timeoutMs: 5000, maxToolCalls: undefined, maxOutputBytes: undefined },
+ hooks: {},
+}
// One line, on the line of the "use strict" directive, so the test's own line numbers stay as they are.
const prelude = [
@@ -52,10 +55,17 @@ export const run = async (file: string): Promise => {
// work instead, so drain explicitly.
const drain = meta.flags?.includes("async") ? "\nfor (let i = 0; i < 100; i++) await null" : ""
const result = await Effect.runPromise(
- executeProgram(`"use strict"; ${prelude}\n${source}${drain}`, prepared, limits, {}, (ctx) =>
- harness(ctx, (error) => {
- done ??= { error }
- }),
+ finishExecution(
+ startProgram(
+ {
+ ...setup,
+ globals: (ctx) =>
+ harness(ctx, (error) => {
+ done ??= { error }
+ }),
+ },
+ `"use strict"; ${prelude}\n${source}${drain}`,
+ ).run(),
),
)
if (meta.negative !== undefined) {
diff --git a/packages/codemode/test/tool-paths.test.ts b/packages/codemode/test/tool-paths.test.ts
index 76c4a875c444..a739d6515109 100644
--- a/packages/codemode/test/tool-paths.test.ts
+++ b/packages/codemode/test/tool-paths.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import { Effect, Schema } from "effect"
-import { CodeMode, Namespace, Tool } from "./lib/index.js"
+import { CodeMode, Namespace, Tool } from "../src/index.js"
const echo = (description: string, result: string) =>
Tool.make({
diff --git a/packages/codemode/test/var-hoisting-test262.test.ts b/packages/codemode/test/var-hoisting-test262.test.ts
index a1729841f491..667603f5232a 100644
--- a/packages/codemode/test/var-hoisting-test262.test.ts
+++ b/packages/codemode/test/var-hoisting-test262.test.ts
@@ -21,7 +21,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
diff --git a/packages/codemode/test/vm/verify.ts b/packages/codemode/test/verify-bytecode.ts
similarity index 99%
rename from packages/codemode/test/vm/verify.ts
rename to packages/codemode/test/verify-bytecode.ts
index 0dce361a8012..9babd65dbc43 100644
--- a/packages/codemode/test/vm/verify.ts
+++ b/packages/codemode/test/verify-bytecode.ts
@@ -1,5 +1,5 @@
-import type { Code } from "../../src/vm/code.js"
-import { CheckBaseKind, CondKind, ImportKind, Op, OpNames } from "../../src/vm/opcodes.js"
+import type { Code } from "../src/code.js"
+import { CheckBaseKind, CondKind, ImportKind, Op, OpNames } from "../src/opcodes.js"
/**
* Stack-depth verifier (C5): runs abstract interpretation over packed bytecode independent of `CodeBuilder`,
diff --git a/packages/codemode/test/vm/vm.test.ts b/packages/codemode/test/vm.test.ts
similarity index 98%
rename from packages/codemode/test/vm/vm.test.ts
rename to packages/codemode/test/vm.test.ts
index 5570bab289c6..b33c1cfb2c90 100644
--- a/packages/codemode/test/vm/vm.test.ts
+++ b/packages/codemode/test/vm.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, test } from "bun:test"
-import { disassembleSource } from "../../script/disasm.js"
-import { hashOf } from "../../src/vm/code.js"
-import { compileSource } from "../../src/vm/compiler/compile.js"
-import { verifyAll } from "./verify.js"
-import { parseVmSource, runProgram, warmupVm } from "./run.js"
+import { disassembleSource } from "../script/disasm.js"
+import { hashOf } from "../src/code.js"
+import { compileSource } from "../src/compiler/compile.js"
+import { verifyAll } from "./verify-bytecode.js"
+import { parseVmSource, runProgram } from "./run-program.js"
const val = (code: string) => {
const parsed = parseVmSource(code)
@@ -496,7 +496,6 @@ describe("generators, async functions, async generators, yield*, and for-await",
describe("built-ins, prelude, and coercion", () => {
test("array callbacks, sort, Map/Set, Object.groupBy, JSON reviver/replacer, and ToPrimitive", () => {
- warmupVm(2)
expect(
val(`
const arr = Array.from({ length: 6 }, (_, i) => i + 1)
diff --git a/packages/codemode/test/web-wpt.test.ts b/packages/codemode/test/web-wpt.test.ts
index dc9e1a64d9a3..05e51d064572 100644
--- a/packages/codemode/test/web-wpt.test.ts
+++ b/packages/codemode/test/web-wpt.test.ts
@@ -13,7 +13,7 @@
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
-import { CodeMode } from "./lib/index.js"
+import { CodeMode } from "../src/index.js"
const base64Cases = (await Bun.file(new URL("./fixtures/wpt-base64.json", import.meta.url)).json()) as Array<
[string, Array | null]
From f738b32d23d9bd33c7b7c9a02fbb4239782ed121 Mon Sep 17 00:00:00 2001
From: usrnk1 <7547651+usrnk1@users.noreply.github.com>
Date: Thu, 12 Nov 2026 19:41:08 +0100
Subject: [PATCH 05/42] feat(app): jump to an earlier prompt by searching
session messages (#63585)
---
.../e2e/regression/timeline-history.spec.ts | 103 +++++++++
packages/app/src/runtime/i18n/en.ts | 9 +
.../commands/dialog-jump-to-message.tsx | 197 ++++++++++++++++++
.../commands/jump-to-message-machine.test.ts | 123 +++++++++++
.../commands/jump-to-message-machine.ts | 161 ++++++++++++++
.../commands/jump-to-message.stories.tsx | 149 +++++++++++++
.../src/session/commands/jump-to-message.tsx | 152 ++++++++++++++
packages/app/src/session/commands/machine.ts | 2 +-
.../session/commands/use-session-commands.tsx | 25 ++-
packages/app/src/session/composer/region.tsx | 1 +
.../app/src/session/timeline/interaction.ts | 1 +
packages/app/src/shell/search-list.css | 4 +-
12 files changed, 921 insertions(+), 6 deletions(-)
create mode 100644 packages/app/src/session/commands/dialog-jump-to-message.tsx
create mode 100644 packages/app/src/session/commands/jump-to-message-machine.test.ts
create mode 100644 packages/app/src/session/commands/jump-to-message-machine.ts
create mode 100644 packages/app/src/session/commands/jump-to-message.stories.tsx
create mode 100644 packages/app/src/session/commands/jump-to-message.tsx
diff --git a/packages/app/e2e/regression/timeline-history.spec.ts b/packages/app/e2e/regression/timeline-history.spec.ts
index 954e4f96b674..b2fd2d91f828 100644
--- a/packages/app/e2e/regression/timeline-history.spec.ts
+++ b/packages/app/e2e/regression/timeline-history.spec.ts
@@ -7,6 +7,7 @@ import {
assistantMessage,
historyMessages,
messageUpdated,
+ partDelta,
partUpdated,
session,
sessionID,
@@ -23,6 +24,108 @@ import { openSession } from "../utils/workspace"
test.use({ serviceWorkers: "block" })
test.describe("timeline history", () => {
+ test("jump to message searches offscreen history without moving the reader until selection", async ({ page }) => {
+ const target = userMessage([textPart("prt_dispatch_note", "Use the loading dock for delivery")], {
+ id: "msg_00000_dispatch",
+ created: 1680000000000,
+ })
+
+ const messages = [
+ target,
+ ...historyMessages(45),
+ userMessage(),
+ assistantMessage([textPart("prt_active", "Checking the route")], { completed: false }),
+ ]
+
+ const timeline = await setupTimeline(page, {
+ sessionMessages: messages,
+ pageMessages: (_, limit, before) => {
+ const end = before ? messages.findIndex((message) => message.id === before) : messages.length
+ const start = Math.max(0, end - Math.min(16, limit))
+
+ return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
+ },
+ })
+
+ const scroller = timelineScroller(page)
+
+ const old = scroller.getByText(target.text, { exact: true })
+
+ await expect(scroller.getByText("Checking the route", { exact: true })).toBeInViewport()
+ await expect(old).toHaveCount(0)
+ const top = await scroller.evaluate((element) => element.scrollTop)
+
+ const mod = await page.evaluate(() => (/Mac/.test(navigator.platform) ? "Meta" : "Control"))
+
+ const search = page.getByRole("combobox", { name: "Jump to message" })
+
+ await page.keyboard.press(`${mod}+Alt+g`)
+ await expect(search).toBeFocused()
+ await search.fill("loading dock")
+ await expect(page.getByRole("option", { name: /Use the loading dock/ })).toBeVisible()
+ await search.press("Escape")
+ await expect(search).toBeHidden()
+ expect(await scroller.evaluate((element) => element.scrollTop)).toBe(top)
+ await expect(old).toHaveCount(0)
+
+ await page.keyboard.press(`${mod}+Shift+p`)
+ await page.getByRole("combobox").fill("sent prompts")
+ await page.getByRole("option", { name: /Jump to message/ }).click()
+ await expect(search).toBeFocused()
+ await search.fill("loading dock")
+ await expect(page.getByRole("option", { name: /Use the loading dock/ })).toBeVisible()
+ await search.press("Enter")
+ await expect(old).toBeInViewport()
+ await timeline.send(partDelta("prt_active", "\n\nThe route is ready."))
+ await expect(old).toBeInViewport()
+ await expect(page).toHaveURL(new RegExp(`#message-${target.id}$`))
+ await page.getByRole("button", { name: "Jump to latest" }).click()
+ await expect(scroller.getByText("The route is ready.", { exact: true })).toBeInViewport()
+ })
+
+ test("jump to message pages back only as far as the prompt", async ({ page }) => {
+ const target = userMessage([textPart("prt_dispatch_note", "Use the loading dock for delivery")], {
+ id: "msg_00100_dispatch",
+ created: 1690000000000,
+ })
+
+ const history = historyMessages(80)
+
+ const messages = [
+ ...history.slice(0, 100),
+ target,
+ ...history.slice(100),
+ userMessage(),
+ assistantMessage([textPart("prt_active", "Checking the route")], { completed: false }),
+ ]
+
+ let oldest = messages.length
+
+ await setupTimeline(page, {
+ sessionMessages: messages,
+ pageMessages: (_, limit, before) => {
+ const end = before ? messages.findIndex((message) => message.id === before) : messages.length
+ const start = Math.max(0, end - Math.min(16, limit))
+
+ // The picker lists older prompts in pages of 200 without touching the timeline; the timeline pages by 20.
+ if (limit < 200) oldest = Math.min(oldest, start)
+
+ return { items: messages.slice(start, end), cursor: start ? messages[start]!.id : undefined }
+ },
+ })
+
+ const mod = await page.evaluate(() => (/Mac/.test(navigator.platform) ? "Meta" : "Control"))
+
+ const search = page.getByRole("combobox", { name: "Jump to message" })
+
+ await page.keyboard.press(`${mod}+Alt+g`)
+ await search.fill("loading dock")
+ await expect(page.getByRole("option", { name: /Use the loading dock/ })).toBeVisible()
+ await search.press("Enter")
+ await expect(timelineScroller(page).getByText(target.text, { exact: true })).toBeInViewport()
+ expect(oldest).toBeGreaterThan(0)
+ })
+
test("restoring a paged transcript waits for another upward scroll before loading history", async ({ page }) => {
const id = "ses_history_restore"
const other = "ses_history_other"
diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts
index a73a7832e456..1874157978a7 100644
--- a/packages/app/src/runtime/i18n/en.ts
+++ b/packages/app/src/runtime/i18n/en.ts
@@ -406,6 +406,15 @@ export const dict = {
"mcp.timedOut": "{{name}} took too long to respond",
"dialog.fork.empty": "No messages to fork from",
+ "dialog.jump.title": "Jump to message",
+ "dialog.jump.description": "Choose a message to jump to",
+ "command.session.jumpToMessage.description": "Search sent prompts in this session",
+ "dialog.jump.loading": "Loading older promptsโฆ",
+ "dialog.jump.opening": "Opening messageโฆ",
+ "dialog.jump.failed": "Couldnโt load the full history.",
+ "dialog.jump.openFailed": "Couldnโt open that message. Try again.",
+ "dialog.jump.empty": "No sent prompts yet",
+ "dialog.jump.noMatches": "No matching prompts",
"dialog.directory.action.selectFile": "Select file",
"dialog.directory.action.selectFolder": "Select folder",
diff --git a/packages/app/src/session/commands/dialog-jump-to-message.tsx b/packages/app/src/session/commands/dialog-jump-to-message.tsx
new file mode 100644
index 000000000000..4e091fd7cda3
--- /dev/null
+++ b/packages/app/src/session/commands/dialog-jump-to-message.tsx
@@ -0,0 +1,197 @@
+import type { SessionMessageUser } from "@opencode/client/promise"
+import { useDialog } from "@opencode/ui/context/dialog"
+import { createEffect, createMemo, createSignal, onCleanup } from "solid-js"
+import { readPromptPresentation } from "@/composer/comment-note"
+import { useLanguage } from "@/runtime/i18n/language"
+import { useServerSDK } from "@/runtime/server/client"
+import { useData } from "@/runtime/server/current"
+import type { SessionCommandContext } from "./use-session-commands"
+import { parseVoiceDelegation } from "../timeline/voice-delegation"
+import { JumpToMessage, type JumpPrompt } from "./jump-to-message"
+import {
+ selectJumpHistory,
+ selectJumpOpening,
+ selectJumpStatus,
+ startJumpToMessage,
+ transitionJumpToMessage,
+ type JumpToMessageEffect,
+ type JumpToMessageEvent,
+} from "./jump-to-message-machine"
+
+function prompt(message: SessionMessageUser, attachment: string): JumpPrompt {
+ const presentation = readPromptPresentation(message.metadata)
+
+ const text = presentation?.displayText ?? message.text
+
+ const voice = parseVoiceDelegation(text)
+
+ const labels = [
+ voice?.framing ?? voice?.instruction ?? text,
+ ...(presentation?.attachments ?? []).map((file) => file.name),
+ ...(message.files ?? []).filter((file) => !file.mention).map((file) => file.name || attachment),
+ ...(message.agents ?? []).filter((agent) => !agent.mention).map((agent) => `@${agent.name}`),
+ ...(message.skills ?? []).filter((skill) => !skill.mention).map((skill) => skill.name),
+ ...(presentation?.comments ?? []).map((comment) => {
+ if (comment.comment) return comment.comment
+
+ if (comment.type === "quote") return comment.text
+
+ if (comment.type === "note") return comment.subject
+
+ return comment.path
+ }),
+ ]
+
+ return {
+ id: message.id,
+ text: labels.filter(Boolean).join("\n"),
+ created: message.time.created,
+ }
+}
+
+export function DialogJumpToMessage(props: {
+ session: SessionCommandContext["session"]
+ onJump: (id: string) => void
+}) {
+ const dialog = useDialog()
+ const language = useLanguage()
+ const data = useData()
+ const sdk = useServerSDK()
+ const key = props.session.identity.sessionKey()
+ const id = props.session.identity.params.id
+
+ if (!id) return void dialog.close()
+ let controller: AbortController | undefined
+ const start = startJumpToMessage()
+
+ const [state, setState] = createSignal(start.state)
+
+ const dispatch = (event: JumpToMessageEvent) => {
+ const next = transitionJumpToMessage(state(), event)
+
+ if (next.state !== state()) setState(next.state)
+ next.effects.forEach(run)
+ }
+
+ const run = (effect: JumpToMessageEffect) => {
+ if (effect.type === "cancel") return controller?.abort()
+
+ if (effect.type === "jump") {
+ dialog.close()
+
+ return props.onJump(effect.id)
+ }
+
+ controller?.abort()
+ const current = new AbortController()
+
+ controller = current
+
+ if (effect.type === "history.load")
+ return void loadHistory(current.signal).then(
+ (history) =>
+ dispatch({
+ type: "history.loaded",
+ attempt: effect.attempt,
+ history,
+ }),
+ () => dispatch({ type: "history.failed", attempt: effect.attempt }),
+ )
+
+ void reveal(effect.target, AbortSignal.any([current.signal, AbortSignal.timeout(60_000)])).then(
+ () => dispatch({ type: "opened", attempt: effect.attempt }),
+ () => dispatch({ type: "open.failed", attempt: effect.attempt }),
+ )
+ }
+
+ // Read older prompts into the picker only. Prepending pages to the timeline while browsing would move the reader.
+ const loadHistory = async (signal: AbortSignal) => {
+ const rows: JumpPrompt[] = []
+
+ // Join the timeline's initial sync before interpreting a missing cursor as the end of history.
+ await data.session.message.sync(id)
+ signal.throwIfAborted()
+
+ if (!data.session.message.more(id)) return rows
+ let cursor: string | undefined
+
+ do {
+ const page = await sdk.api.message.list(
+ { sessionID: id, type: "user", limit: 200, cursor },
+ { signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]) },
+ )
+
+ signal.throwIfAborted()
+
+ for (const message of page.data) {
+ if (message.type === "user") rows.push(prompt(message, language.t("common.attachment")))
+ }
+
+ cursor = page.cursor.next ?? undefined
+ } while (cursor)
+
+ return rows
+ }
+
+ // Page back only as far as the prompt, so the rest of a long session stays unloaded.
+ const reveal = async (messageID: string, signal: AbortSignal) => {
+ while (!data.session.message.get(id, messageID)) {
+ if (!data.session.message.more(id)) throw new Error("Message unavailable")
+ await data.session.message.loadMore(id, { signal })
+ signal.throwIfAborted()
+ }
+
+ if (
+ !props.session.history.visibleUserMessages().some((message) => message.id === messageID) ||
+ data.session.input.has(id, messageID)
+ )
+ throw new Error("Message unavailable")
+ }
+
+ start.effects.forEach(run)
+ onCleanup(() => dispatch({ type: "disposed" }))
+ createEffect(() => {
+ if (key !== props.session.identity.sessionKey() || dialog.closing) dispatch({ type: "disposed" })
+
+ if (key !== props.session.identity.sessionKey()) dialog.close()
+ })
+
+ const prompts = createMemo(() => {
+ const all = new Map(selectJumpHistory(state()).map((row) => [row.id, row]))
+
+ const reverted = data.session.get(id)?.revert?.messageID
+
+ for (const message of props.session.history.visibleUserMessages()) {
+ all.set(message.id, prompt(message, language.t("common.attachment")))
+ }
+
+ const pending = new Set(data.session.input.list(id))
+
+ return [...all.values()].filter(
+ (row) => row.text.trim() && !pending.has(row.id) && (!reverted || row.id < reverted),
+ )
+ })
+
+ const status = () => {
+ const note = selectJumpStatus(state())
+
+ return note && language.t(`dialog.jump.${note}`)
+ }
+
+ return (
+ dispatch({ type: "retry" }) : undefined}
+ onClose={() => dialog.close()}
+ onJump={(row) =>
+ dispatch({
+ type: "selected",
+ id: row.id,
+ loaded: !!data.session.message.get(id, row.id),
+ })
+ }
+ />
+ )
+}
diff --git a/packages/app/src/session/commands/jump-to-message-machine.test.ts b/packages/app/src/session/commands/jump-to-message-machine.test.ts
new file mode 100644
index 000000000000..b88808c27d76
--- /dev/null
+++ b/packages/app/src/session/commands/jump-to-message-machine.test.ts
@@ -0,0 +1,123 @@
+import { expect, test } from "bun:test"
+import {
+ selectJumpHistory,
+ selectJumpOpening,
+ selectJumpStatus,
+ startJumpToMessage,
+ transitionJumpToMessage,
+ type JumpToMessageEvent,
+ type JumpToMessageTransition,
+} from "./jump-to-message-machine"
+
+const history = [{ id: "msg_1", text: "first", created: 1 }]
+
+function replay(events: JumpToMessageEvent[], from: JumpToMessageTransition = startJumpToMessage()) {
+ return events.reduce((steps, event) => {
+ steps.push(transitionJumpToMessage(steps.at(-1)?.state ?? from.state, event))
+
+ return steps
+ }, [])
+}
+
+test("the older history loads on open, then selecting an unloaded prompt pages back to it and jumps", () => {
+ const start = startJumpToMessage()
+
+ const [loaded, selected, opened] = replay(
+ [
+ { type: "history.loaded", attempt: 1, history },
+ { type: "selected", id: "msg_1", loaded: false },
+ { type: "opened", attempt: 2 },
+ ],
+ start,
+ )
+
+ expect(start.effects).toEqual([{ type: "history.load", attempt: 1 }])
+ expect(selectJumpHistory(loaded!.state)).toEqual(history)
+ expect(selected?.effects).toEqual([{ type: "open.load", attempt: 2, target: "msg_1" }])
+ expect(selectJumpOpening(selected!.state)).toBe(true)
+ expect(selectJumpStatus(selected!.state)).toBe("opening")
+ expect(opened?.state.status).toBe("closed")
+ expect(opened?.effects).toEqual([{ type: "jump", id: "msg_1" }])
+})
+
+test("a loaded prompt jumps at once and cancels the history still loading", () => {
+ const [selected] = replay([{ type: "selected", id: "msg_2", loaded: true }])
+
+ expect(selected?.state.status).toBe("closed")
+ expect(selected?.effects).toEqual([{ type: "cancel" }, { type: "jump", id: "msg_2" }])
+})
+
+test("an unloaded prompt cannot be selected before the history loads, or while another opens", () => {
+ const [early, loaded, first, second] = replay([
+ { type: "selected", id: "msg_1", loaded: false },
+ { type: "history.loaded", attempt: 1, history },
+ { type: "selected", id: "msg_1", loaded: false },
+ { type: "selected", id: "msg_1", loaded: true },
+ ])
+
+ expect(early?.effects).toEqual([])
+ expect(early?.state.status).toBe("loading")
+ expect(first?.effects).toHaveLength(1)
+ expect(second?.state).toBe(first!.state)
+ expect(second?.effects).toEqual([])
+ expect(loaded?.state.status).toBe("ready")
+})
+
+test("a failed history offers a retry that loads again, and drops the failed attempt's late result", () => {
+ const [failed, early, retried, stale, loaded] = replay([
+ { type: "history.failed", attempt: 1 },
+ { type: "retry" },
+ { type: "retry" },
+ { type: "history.loaded", attempt: 1, history },
+ { type: "history.loaded", attempt: 2, history },
+ ])
+
+ expect(selectJumpStatus(failed!.state)).toBe("failed")
+ expect(early?.state).toMatchObject({ status: "loading", attempt: 2 })
+ expect(early?.effects).toEqual([{ type: "history.load", attempt: 2 }])
+ expect(retried?.state).toBe(early!.state)
+ expect(retried?.effects).toEqual([])
+ expect(stale?.state).toBe(early!.state)
+ expect(loaded?.state.status).toBe("ready")
+})
+
+test("a failed or timed out open returns to the list, and selecting again tries again", () => {
+ const [, , failed, again, opened] = replay([
+ { type: "history.loaded", attempt: 1, history },
+ { type: "selected", id: "msg_1", loaded: false },
+ { type: "open.failed", attempt: 2 },
+ { type: "selected", id: "msg_1", loaded: false },
+ { type: "opened", attempt: 3 },
+ ])
+
+ expect(selectJumpStatus(failed!.state)).toBe("openFailed")
+ expect(selectJumpHistory(failed!.state)).toEqual(history)
+ expect(again?.effects).toEqual([{ type: "open.load", attempt: 3, target: "msg_1" }])
+ expect(opened?.effects).toEqual([{ type: "jump", id: "msg_1" }])
+})
+
+test("a result from an earlier attempt is ignored", () => {
+ const [, , stale] = replay([
+ { type: "history.loaded", attempt: 1, history },
+ { type: "selected", id: "msg_1", loaded: false },
+ { type: "opened", attempt: 1 },
+ ])
+
+ expect(selectJumpOpening(stale!.state)).toBe(true)
+ expect(stale?.effects).toEqual([])
+})
+
+test("disposing cancels the work, and nothing after it changes or jumps", () => {
+ const [, , disposed, opened, again] = replay([
+ { type: "history.loaded", attempt: 1, history },
+ { type: "selected", id: "msg_1", loaded: false },
+ { type: "disposed" },
+ { type: "opened", attempt: 2 },
+ { type: "disposed" },
+ ])
+
+ expect(disposed?.effects).toEqual([{ type: "cancel" }])
+ expect(opened?.state).toBe(disposed!.state)
+ expect(opened?.effects).toEqual([])
+ expect(again?.effects).toEqual([])
+})
diff --git a/packages/app/src/session/commands/jump-to-message-machine.ts b/packages/app/src/session/commands/jump-to-message-machine.ts
new file mode 100644
index 000000000000..4b61b79d29b5
--- /dev/null
+++ b/packages/app/src/session/commands/jump-to-message-machine.ts
@@ -0,0 +1,161 @@
+import type { JumpPrompt } from "./jump-to-message"
+
+/**
+ * The jump dialog browses the loaded timeline's prompts at once while older ones load, and opens an unloaded prompt by
+ * paging the timeline back to it. `failed` is a history that did not load; `retry` loads it again. A failed open
+ * returns to `ready` with `failed` set, and selecting the prompt again tries again.
+ */
+export type JumpToMessageState =
+ | { readonly status: "loading"; readonly attempt: number }
+ | { readonly status: "failed"; readonly attempt: number }
+ | {
+ readonly status: "ready"
+ readonly attempt: number
+ readonly history: readonly JumpPrompt[]
+ readonly failed: boolean
+ }
+ | {
+ readonly status: "opening"
+ readonly attempt: number
+ readonly history: readonly JumpPrompt[]
+ readonly target: string
+ }
+ | { readonly status: "closed" }
+
+export type JumpToMessageEvent =
+ | {
+ readonly type: "history.loaded"
+ readonly attempt: number
+ readonly history: readonly JumpPrompt[]
+ }
+ | { readonly type: "history.failed"; readonly attempt: number }
+ | { readonly type: "retry" }
+ | { readonly type: "selected"; readonly id: string; readonly loaded: boolean }
+ | { readonly type: "opened"; readonly attempt: number }
+ | { readonly type: "open.failed"; readonly attempt: number }
+ | { readonly type: "disposed" }
+
+export type JumpToMessageEffect =
+ | { readonly type: "history.load"; readonly attempt: number }
+ | {
+ readonly type: "open.load"
+ readonly attempt: number
+ readonly target: string
+ }
+ | { readonly type: "jump"; readonly id: string }
+ | { readonly type: "cancel" }
+
+export type JumpToMessageTransition = {
+ readonly state: JumpToMessageState
+ readonly effects: readonly JumpToMessageEffect[]
+}
+
+const NO_EFFECTS: readonly never[] = Object.freeze([])
+
+export function startJumpToMessage(): JumpToMessageTransition {
+ return {
+ state: { status: "loading", attempt: 1 },
+ effects: [{ type: "history.load", attempt: 1 }],
+ }
+}
+
+export function transitionJumpToMessage(state: JumpToMessageState, event: JumpToMessageEvent): JumpToMessageTransition {
+ if (state.status === "closed") return { state, effects: NO_EFFECTS }
+
+ if (event.type === "disposed") return { state: { status: "closed" }, effects: [{ type: "cancel" }] }
+
+ if (event.type === "selected") {
+ if (state.status === "opening") return { state, effects: NO_EFFECTS }
+
+ // Rows beyond the loaded timeline only exist once the older history has loaded.
+ if (event.loaded)
+ return {
+ state: { status: "closed" },
+ effects: [{ type: "cancel" }, { type: "jump", id: event.id }],
+ }
+
+ if (state.status !== "ready") return { state, effects: NO_EFFECTS }
+
+ return {
+ state: {
+ status: "opening",
+ attempt: state.attempt + 1,
+ history: state.history,
+ target: event.id,
+ },
+ effects: [{ type: "open.load", attempt: state.attempt + 1, target: event.id }],
+ }
+ }
+
+ if (event.type === "retry") {
+ if (state.status !== "failed") return { state, effects: NO_EFFECTS }
+
+ return {
+ state: { status: "loading", attempt: state.attempt + 1 },
+ effects: [{ type: "history.load", attempt: state.attempt + 1 }],
+ }
+ }
+
+ if (event.attempt !== state.attempt) return { state, effects: NO_EFFECTS }
+
+ if (state.status === "loading") {
+ if (event.type === "history.loaded")
+ return {
+ state: {
+ status: "ready",
+ attempt: state.attempt,
+ history: event.history,
+ failed: false,
+ },
+ effects: NO_EFFECTS,
+ }
+
+ if (event.type === "history.failed")
+ return {
+ state: { status: "failed", attempt: state.attempt },
+ effects: NO_EFFECTS,
+ }
+
+ return { state, effects: NO_EFFECTS }
+ }
+
+ if (state.status !== "opening") return { state, effects: NO_EFFECTS }
+
+ if (event.type === "opened")
+ return {
+ state: { status: "closed" },
+ effects: [{ type: "jump", id: state.target }],
+ }
+
+ if (event.type === "open.failed")
+ return {
+ state: {
+ status: "ready",
+ attempt: state.attempt,
+ history: state.history,
+ failed: true,
+ },
+ effects: NO_EFFECTS,
+ }
+
+ return { state, effects: NO_EFFECTS }
+}
+
+export function selectJumpHistory(state: JumpToMessageState) {
+ return state.status === "ready" || state.status === "opening" ? state.history : []
+}
+
+export function selectJumpOpening(state: JumpToMessageState) {
+ return state.status === "opening"
+}
+
+/** The note the dialog shows beside its rows, if any. */
+export function selectJumpStatus(state: JumpToMessageState) {
+ if (state.status === "opening") return "opening"
+
+ if (state.status === "failed") return "failed"
+
+ if (state.status === "ready" && state.failed) return "openFailed"
+
+ if (state.status === "loading") return "loading"
+}
diff --git a/packages/app/src/session/commands/jump-to-message.stories.tsx b/packages/app/src/session/commands/jump-to-message.stories.tsx
new file mode 100644
index 000000000000..ea0fb8b8fbb9
--- /dev/null
+++ b/packages/app/src/session/commands/jump-to-message.stories.tsx
@@ -0,0 +1,149 @@
+import { Button } from "@opencode/ui/button"
+import { useDialog } from "@opencode/ui/context/dialog"
+import { Keybind } from "@opencode/ui/keybind"
+import { For, onMount, Show } from "solid-js"
+import { useLanguage } from "@/runtime/i18n/language"
+import { formatKeybindParts, matchKeybind, parseKeybind } from "@/shell/commands/command"
+import { JumpToMessage } from "./jump-to-message"
+
+const shortcut = "mod+alt+g"
+
+const turns = [
+ [
+ "Our delivery CSV has 48 stops. Why does the import preview show 49?",
+ "The extra stop appears after order 731. Could you paste that record straight from the CSV? A spreadsheet hides some of the formatting.",
+ ],
+ [
+ 'Hereโs the header and the record as they appear in the file:\n\norder_id,driver,note\n731,Sam,"Use the loading dock\nRing twice"\n\nThe preview puts โRing twiceโ in the order ID column.',
+ "That newline is inside the quoted note. The preview splits the file into lines before it parses the fields, so it treats โRing twiceโ as the start of another stop.",
+ ],
+ [
+ "Did we save a bogus stop too?",
+ "I checked the import receipt: 48 stops. The upload worker parses the whole file and keeps both lines in the note for 731.",
+ ],
+ [
+ "Can the preview use that parser?",
+ "Yes. I switched the preview to the workerโs CSV reader. Your file now shows 48 stops before upload.",
+ ],
+ [
+ "Another note says โGate 2, ask for ููููโ. Does that comma break it?",
+ "I tried it as a quoted field. The whole note stayed in one cell, and Sam was still in the driver column.",
+ ],
+ [
+ "Try it with Windows line endings too.",
+ "With CRLF between records and inside the quoted note, I still get one stop for 731. Both lines of its note are there.",
+ ],
+ [
+ "Which line do we report if the next order is missing its ID?",
+ "Line 4 in your sample: the header is line 1 and order 731 spans lines 2 and 3. The error uses the next recordโs starting line.",
+ ],
+ [
+ "Keep that case in the tests.",
+ "Added a fixture with the two-line note followed by a missing ID. The test checks the note on 731 and the error on line 4. It passes with both LF and CRLF.",
+ ],
+].map(([text, reply], index) => ({
+ id: `prompt-${index}`,
+ created: new Date(2026, 9, 28, 10, index * 4).getTime(),
+ text,
+ reply,
+}))
+
+function SessionStory(props: { query?: string; empty?: boolean; failed?: boolean }) {
+ const language = useLanguage()
+
+ const dialog = useDialog()
+
+ const prompts = () => (props.empty ? [] : turns)
+
+ const bubbles = new Map()
+
+ let session!: HTMLElement
+
+ let transcript!: HTMLDivElement
+
+ const open = (query = "") =>
+ dialog.show(() => (
+ dialog.close() : undefined}
+ onClose={() => dialog.close()}
+ onJump={(prompt) => {
+ dialog.close()
+ const bubble = bubbles.get(prompt.id)
+ bubble?.focus({ preventScroll: true })
+ bubble?.scrollIntoView({ block: "center", inline: "nearest" })
+ }}
+ />
+ ))
+
+ onMount(() => {
+ transcript.scrollTop = transcript.scrollHeight
+ session.focus({ preventScroll: true })
+
+ void open(props.query)
+ })
+
+ return (
+ {
+ if (!matchKeybind(parseKeybind(shortcut), event)) return
+ event.preventDefault()
+ event.stopPropagation()
+ void open()
+ }}
+ >
+
+ Extra stop in CSV import preview
+
+
+
+
+ {(turn) => (
+
+
bubbles.set(turn.id, el)}
+ tabIndex={-1}
+ class="ms-8 self-end whitespace-pre-wrap rounded-xl bg-v2-background-bg-layer-02 px-4 py-3 focus:outline-v2-border-border-base"
+ dir="auto"
+ >
+ {turn.text}
+
+
{turn.reply}
+
+ )}
+
+
+ Your conversation will appear here.
+
+
+
+
+ )
+}
+
+export default {
+ title: "Session/Jump to message",
+ id: "session-jump-to-message",
+ parameters: { layout: "fullscreen" },
+}
+
+export const Browse = { render: () => }
+
+export const MultilineMatch = { render: () => }
+
+export const Empty = { render: () => }
+
+export const HistoryFailed = { render: () => }
+
+export const NoMatches = { render: () => }
diff --git a/packages/app/src/session/commands/jump-to-message.tsx b/packages/app/src/session/commands/jump-to-message.tsx
new file mode 100644
index 000000000000..0eb8ff7d6397
--- /dev/null
+++ b/packages/app/src/session/commands/jump-to-message.tsx
@@ -0,0 +1,152 @@
+import { Button } from "@opencode/ui/button"
+import { Dialog, DialogBody, DialogTitle, DialogTitleGroup } from "@opencode/ui/dialog"
+import { Icon } from "@opencode/ui/icon"
+import { SearchHighlight, SearchList, type SearchListHandle } from "@opencode/ui/search-list"
+import { TextInput } from "@opencode/ui/text-input"
+import { Tooltip } from "@opencode/ui/tooltip"
+import { createMemo, createSignal, Show } from "solid-js"
+import { useLanguage } from "@/runtime/i18n/language"
+import { getRelativeTime } from "@/shell/time"
+import "@/shell/commands/dialog.css"
+import "@/shell/palette-menu.css"
+import "@/shell/search-list.css"
+
+export type JumpPrompt = { id: string; text: string; created: number }
+
+export function JumpToMessage(props: {
+ prompts: JumpPrompt[]
+ initialQuery?: string
+ status?: string
+ opening?: boolean
+ onJump: (prompt: JumpPrompt) => void
+ onRetry?: () => void
+ onClose: () => void
+}) {
+ const language = useLanguage()
+
+ const [query, setQuery] = createSignal(props.initialQuery ?? "")
+
+ const timestamp = createMemo(
+ () =>
+ new Intl.DateTimeFormat(language.intl(), {
+ day: "numeric",
+ month: "short",
+ year: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ }),
+ )
+
+ const prompts = createMemo(() =>
+ props.prompts
+ .toSorted((a, b) => b.created - a.created)
+ .map((prompt) => ({
+ prompt,
+ text: prompt.text.replace(/\s+/g, " ").trim(),
+ })),
+ )
+
+ const rows = createMemo(() => {
+ const needle = query().trim().toLowerCase()
+
+ return prompts().flatMap(({ prompt, text }) => {
+ const match = text.toLowerCase().indexOf(needle)
+
+ if (match < 0) return []
+ const prefix = Math.max(0, match - 16)
+
+ const space = text.indexOf(" ", prefix)
+
+ const start = prefix && space >= prefix && space < match ? space + 1 : prefix
+
+ const end = Math.min(text.length, Math.max(start + 90, match + needle.length + 16))
+
+ return [
+ {
+ prompt,
+ snippet: (start ? "โฆ" : "") + text.slice(start, end) + (end < text.length ? "โฆ" : ""),
+ },
+ ]
+ })
+ })
+
+ let list!: SearchListHandle[number]>
+
+ return (
+
+ )
+}
diff --git a/packages/app/src/session/commands/machine.ts b/packages/app/src/session/commands/machine.ts
index 3d6a5404fb02..f3257f2e8842 100644
--- a/packages/app/src/session/commands/machine.ts
+++ b/packages/app/src/session/commands/machine.ts
@@ -4,7 +4,7 @@
export const SESSION_DIALOG_LOAD_TIMEOUT_MS = 15_000
/** The lazily loaded dialogs: the /fork picker, the /open file palette and the /mcp list. */
-export type SessionDialogKind = "fork" | "palette" | "mcp"
+export type SessionDialogKind = "fork" | "jump" | "palette" | "mcp"
/**
* The session commands stay mounted while tabs switch between sessions, so compactions are keyed by the session they
diff --git a/packages/app/src/session/commands/use-session-commands.tsx b/packages/app/src/session/commands/use-session-commands.tsx
index 43980249d694..db507390e6b6 100644
--- a/packages/app/src/session/commands/use-session-commands.tsx
+++ b/packages/app/src/session/commands/use-session-commands.tsx
@@ -1,4 +1,4 @@
-import { createEffect, createSignal, on, onCleanup, type JSX } from "solid-js"
+import { createEffect, createSignal, createUniqueId, on, onCleanup, type JSX } from "solid-js"
import { createEventListener } from "@solid-primitives/event-listener"
import { useCommand, type CommandOption } from "@/shell/commands/command"
import { adjacentTabKey } from "@/shell/titlebar/tab-order"
@@ -54,6 +54,7 @@ export type SessionCommandContext = {
move: () => Promise
}
navigateMessageByOffset: (offset: number) => void
+ jumpToMessage: (id: string) => void
revert: Pick
focusInput: () => void
// The composer's model, which a compaction runs with.
@@ -68,7 +69,13 @@ const withCategory = (category: string) => {
}
// Loads a dialog's chunk and returns its renderer.
-async function loadDialog(kind: SessionDialogKind): Promise<() => JSX.Element> {
+async function loadDialog(kind: SessionDialogKind, context: SessionCommandContext): Promise<() => JSX.Element> {
+ if (kind === "jump") {
+ const { DialogJumpToMessage } = await import("./dialog-jump-to-message")
+
+ return () =>
+ }
+
if (kind === "fork") {
const { DialogFork } = await import("@/session/commands/fork-dialog")
@@ -227,6 +234,8 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
const permissionsCommand = withCategory(language.t("command.category.permissions"))
const [commandsState, setCommandsState] = createSignal(createSessionCommandsState())
+ const jumpDialog = createUniqueId()
+ onCleanup(() => dialog.close(jumpDialog))
// Renders each dialog once its chunk has loaded.
const dialogs: Partial JSX.Element>> = {}
let dialogTimer: ReturnType | undefined
@@ -256,7 +265,7 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
const kind = effect.kind
clearTimeout(dialogTimer)
dialogTimer = setTimeout(() => dispatchCommands({ type: "dialog.timed-out", attempt }), effect.timeoutMs)
- loadDialog(kind).then(
+ loadDialog(kind, actions).then(
(render) => {
dialogs[kind] = render
dispatchCommands({ type: "dialog.loaded", attempt })
@@ -277,7 +286,7 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
if (effect.type === "dialog.show") {
const render = dialogs[effect.kind]
- if (render) dialog.show(render)
+ if (render) dialog.show(render, undefined, effect.kind === "jump" ? jumpDialog : undefined)
return
}
@@ -662,6 +671,14 @@ export const useSessionCommands = (actions: SessionCommandContext) => {
]
const messageCmds = () => [
+ sessionCommand({
+ id: "session.jumpToMessage",
+ title: language.t("dialog.jump.title"),
+ description: language.t("command.session.jumpToMessage.description"),
+ keybind: "mod+alt+g",
+ disabled: !actions.session.identity.params.id,
+ onSelect: () => openDialog("jump"),
+ }),
sessionCommand({
id: "message.previous",
title: language.t("command.message.previous"),
diff --git a/packages/app/src/session/composer/region.tsx b/packages/app/src/session/composer/region.tsx
index 2ef53edc2d0c..40292d873daa 100644
--- a/packages/app/src/session/composer/region.tsx
+++ b/packages/app/src/session/composer/region.tsx
@@ -317,6 +317,7 @@ export function createActiveSessionRegion(input: {
move: state.background.move,
},
navigateMessageByOffset: input.timeline.actions.navigateMessage,
+ jumpToMessage: input.timeline.actions.jumpToMessage,
revert,
focusInput: focus,
model: () => {
diff --git a/packages/app/src/session/timeline/interaction.ts b/packages/app/src/session/timeline/interaction.ts
index f236a1ead25e..3b7205a2dfb3 100644
--- a/packages/app/src/session/timeline/interaction.ts
+++ b/packages/app/src/session/timeline/interaction.ts
@@ -417,6 +417,7 @@ export function createSessionTimelineInteraction(session: SessionModel, visible:
return {
actions: {
navigateMessage,
+ jumpToMessage: (id: string) => cursor.jump(id, "auto"),
page: (direction: 1 | -1) => page(direction),
// Find and tool reveals move the view like a scroll, so the chosen prompt is no longer where navigation starts.
revealMessage: (id: string, partID?: string) => {
diff --git a/packages/app/src/shell/search-list.css b/packages/app/src/shell/search-list.css
index aca1d75a55a3..d68f0c52fdff 100644
--- a/packages/app/src/shell/search-list.css
+++ b/packages/app/src/shell/search-list.css
@@ -259,13 +259,15 @@
}
}
-.fork-dialog .search-list-results {
+.fork-dialog .search-list-results,
+.fork-dialog [data-slot="search-list-section"] {
gap: 2px;
padding-top: 0;
}
.fork-dialog [data-slot="search-list-row"] {
height: 28px;
+ gap: 12px;
padding-inline: 8px;
}
From becb9c7c9f3907257d12e95993a47ccc6e3b9625 Mon Sep 17 00:00:00 2001
From: James Long
Date: Thu, 12 Nov 2026 12:45:04 -0600
Subject: [PATCH 06/42] fix(app): order Recent sessions by the last list reload
and drop the rename guard (#63370)
---
packages/app/e2e/regression/tabs.spec.ts | 68 ++++++
packages/app/src/composer/model.ts | 1 +
packages/app/src/home/sessions/controller.tsx | 2 +-
.../app/src/home/start/command-palette.tsx | 1 +
packages/app/src/runtime/server/data.test.ts | 201 ++++++++----------
packages/app/src/runtime/server/data.ts | 168 ++++-----------
.../app/src/runtime/server/session-index.ts | 15 +-
.../src/session/commands/rename-session.ts | 12 +-
packages/app/src/shell/commands/palette.ts | 13 +-
.../app/src/shell/commands/session-search.tsx | 2 +-
.../app/src/shell/titlebar/inbox-model.ts | 7 +-
.../titlebar/recent-sessions-model.test.ts | 194 ++++++++++++++++-
.../shell/titlebar/recent-sessions-model.ts | 85 +++++++-
.../src/shell/titlebar/recent-sessions.tsx | 89 ++++++--
.../src/shell/titlebar/sidebar-sessions.ts | 2 +-
15 files changed, 567 insertions(+), 293 deletions(-)
diff --git a/packages/app/e2e/regression/tabs.spec.ts b/packages/app/e2e/regression/tabs.spec.ts
index 0ff9ca736284..007fbc5f48ae 100644
--- a/packages/app/e2e/regression/tabs.spec.ts
+++ b/packages/app/e2e/regression/tabs.spec.ts
@@ -814,6 +814,74 @@ test("Recent shows the last 7 days, and Show more reveals 30 more rows, fetching
await expect(more).toBeHidden()
})
+test("Recent keeps the server's order from its last reload, which a run end or window focus triggers", async ({
+ page,
+}) => {
+ const t = Date.now() - 60_000
+
+ const workspace = await mockWorkspace(page, {
+ name: "RecentOrder",
+ sessions: [
+ { ...a, time: { created: t, updated: t, idle: t } },
+ { ...b, time: { created: t + 1, updated: t + 1, idle: t + 1 } },
+ ],
+ seed: {
+ tabs: [],
+ settings: { appearance: { tabLayout: "vertical" }, general: { sidebarOrganize: "recent" } },
+ },
+ })
+
+ await page.goto(
+ `/e2e/utils/windows-menu.html?${new URLSearchParams({ server: SERVER, path: sessionHref(a.id, "sidecar") })}`,
+ )
+
+ const recent = page.locator('[data-slot="sidebar-recent"]').getByRole("group", { name: "Recent", exact: true })
+ const rows = recent.locator("[data-titlebar-tab-slot]")
+
+ // The mock serves these records, so changing one changes what the next list reload returns.
+ const advance = (id: string, time: { updated: number; idle?: number }, title?: string) => {
+ const session = workspace.sessions.find((item) => item.id === id)
+
+ if (!session) throw new Error(`Unknown session ${id}`)
+
+ Object.assign(session, { title: title ?? session.title, time: { ...session.time, ...time } })
+ }
+
+ await expect(rows).toHaveText([/Tab B session/, /Tab A session/])
+
+ // Renaming advances the server's time, but the row stays where the last reload put it.
+ advance(a.id, { updated: t + 2 }, "Renamed A session")
+ await workspace.push([
+ {
+ id: "evt_recent_order_rename",
+ created: t + 2,
+ type: "session.renamed",
+ location: { directory: workspace.directory },
+ durable: { aggregateID: a.id, seq: 1, version: 1 },
+ data: { sessionID: a.id, title: "Renamed A session" },
+ } satisfies Extract,
+ ])
+ await expect(rows.first()).toContainText("Tab B session")
+ await expect(rows.last()).toContainText("Renamed A session")
+
+ // The window coming back reloads the list, as the iOS app does when it returns to the foreground.
+ await page.evaluate(() => window.dispatchEvent(new Event("focus")))
+ await expect(rows).toHaveText([/Renamed A session/, /Tab B session/])
+
+ advance(b.id, { updated: t + 3, idle: t + 3 })
+ await workspace.push([
+ {
+ id: "evt_recent_order_run_end",
+ created: t + 3,
+ type: "session.execution.succeeded",
+ location: { directory: workspace.directory },
+ durable: { aggregateID: b.id, seq: 1, version: 1 },
+ data: { sessionID: b.id },
+ } satisfies Extract,
+ ])
+ await expect(rows).toHaveText([/Tab B session/, /Renamed A session/])
+})
+
test("an unfocused window preserves a restored manual unread reminder", async ({ page }) => {
// Playwright emulates focus for each page, so model a background window explicitly.
await page.addInitScript(() => {
diff --git a/packages/app/src/composer/model.ts b/packages/app/src/composer/model.ts
index fca0283ee6d6..c4c4a931c7c9 100644
--- a/packages/app/src/composer/model.ts
+++ b/packages/app/src/composer/model.ts
@@ -204,6 +204,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
const sessions = createServerSessionEntries({
server: server.key,
known: createKnownServerSessions(() => server.ctx),
+ apply: server.ctx.data.session.apply,
projects: server.ctx.projects.list,
load: async (search, signal) => {
const page = await serverSDK.api.session.list({ parentID: null, search, archived: false, limit: 50 }, { signal })
diff --git a/packages/app/src/home/sessions/controller.tsx b/packages/app/src/home/sessions/controller.tsx
index 939ea01f75ab..fffbb8039416 100644
--- a/packages/app/src/home/sessions/controller.tsx
+++ b/packages/app/src/home/sessions/controller.tsx
@@ -390,7 +390,7 @@ export function createHomeSessionsController(home: HomeController) {
.update({ sessionID: session.id, title: next }, { signal })
.then(() => {
ctx.data.session.remember({ ...(ctx.data.session.get(session.id) ?? session), title: next })
- // Rename advances time.updated server-side, but the data layer's rename guard keeps the session where it was.
+ // Rename advances time.updated server-side; like the iOS app, the session moves when the list next reloads.
queryClient.setQueryData(["home-sessions", conn], (current) =>
current?.map((item) => (item.id === session.id ? { ...item, title: next } : item)),
)
diff --git a/packages/app/src/home/start/command-palette.tsx b/packages/app/src/home/start/command-palette.tsx
index bc3154b4227e..fdf85981c1b5 100644
--- a/packages/app/src/home/start/command-palette.tsx
+++ b/packages/app/src/home/start/command-palette.tsx
@@ -36,6 +36,7 @@ export function HomeCommandPalette(props: {
const sessions = createServerSessionEntries({
server: ServerConnection.key(props.server),
known: createKnownServerSessions(server),
+ apply: (sessions) => server()?.data.session.apply(sessions) ?? sessions,
projects: () => server()?.projects.list() ?? [],
load: (search, signal) =>
server()?.sdk.api.session.list({ parentID: null, search, archived: false, limit: 50 }, { signal }) ??
diff --git a/packages/app/src/runtime/server/data.test.ts b/packages/app/src/runtime/server/data.test.ts
index 160938dccc1f..ba23b1bda91d 100644
--- a/packages/app/src/runtime/server/data.test.ts
+++ b/packages/app/src/runtime/server/data.test.ts
@@ -2,7 +2,9 @@ import { afterEach, expect, setSystemTime, test } from "bun:test"
import { createRoot } from "solid-js"
import { createData, type CreateDataInput } from "@opencode/client/solid"
import { OpenCode, type OpenCodeEvent, type SessionInfo } from "@opencode/client/promise"
+import { mergeRecentSessions } from "@/shell/titlebar/recent-sessions-model"
import { createDesktopData, createSessionMutations, createSessionRecency, createSessionRefresh } from "./data"
+import { mergeRootSessionIndex } from "./session-index"
const session: SessionInfo = {
id: "ses_test",
@@ -167,61 +169,80 @@ test("passive session events do not promote a session", () => {
}
})
-test("a rename does not promote the session, including when a refetch returns the rename time", () => {
- const setup = setupDesktop(async () => Response.json({ data: session }))
+test("after a reload, Recent shows the order a restarted window shows for the same server data", () => {
+ const other = { ...session, id: "ses_other", time: { created: 0, updated: 20 } }
+ const running = setupDesktop(async () => Response.json({ data: session }))
+ const restarted = setupDesktop(async () => Response.json({ data: session }))
+
+ const order = (setup: typeof running, snapshot: SessionInfo[]) =>
+ mergeRecentSessions("server", snapshot, setup.data.session.known(), (rows) =>
+ setup.data.session.apply(rows, { reloads: true }),
+ ).map((entry) => entry.session.id)
+
+ try {
+ // The running window renamed the session, which advanced its server time. It keeps its row until a reload.
+ running.seed(10)
+ running.emit("session.renamed", 30, { title: "Renamed" })
+ expect(order(running, [other, { ...session, time: { created: 0, updated: 10 } }])).toEqual([
+ "ses_other",
+ session.id,
+ ])
+
+ const reloaded = [{ ...session, title: "Renamed", time: { created: 0, updated: 30 } }, other]
+ restarted.seed(30)
+ expect(order(running, reloaded)).toEqual([session.id, "ses_other"])
+ expect(order(restarted, reloaded)).toEqual([session.id, "ses_other"])
+ } finally {
+ running.dispose()
+ restarted.dispose()
+ }
+})
+
+// The live record lags the server after a rename, model or agent change, step or metadata update, while a reloaded
+// list shows the newer time. A send must still bump past it until a newer record arrives.
+test("a send after a list showed a time ahead of the live record still bumps until the server passes it", () => {
+ const setup = setupDesktop(async () => Response.json({ data: { ...session, time: { created: 0, updated: 10 } } }))
try {
setup.seed(10)
- setup.emit("session.renamed", 50, { title: "Renamed" })
+ setup.data.session.apply([{ ...session, time: { created: 0, updated: 50 } }], { reloads: true })
+ setSystemTime(new Date(1_000))
+ setup.data.session.acceptSend(session.id)
- const renamed = { ...session, title: "Renamed", time: { created: 0, updated: 50 } }
- expect(setup.data.session.apply([renamed])[0].time.updated).toBe(10)
+ const at = (updated: number) =>
+ setup.data.session.apply([{ ...session, time: { created: 0, updated } }], { reloads: true })[0].time.updated
- // A later change promoted the session. A stale refetch at the rename time must not demote it.
- expect(setup.data.session.apply([{ ...renamed, time: { created: 0, updated: 60 } }])[0].time.updated).toBe(60)
- expect(setup.data.session.apply([renamed])[0].time.updated).toBe(60)
+ expect(setup.data.session.get(session.id)?.time.updated).toBe(10)
+ expect(at(50)).toBe(1_000)
+ expect(at(51)).toBe(51)
} finally {
setup.dispose()
}
})
-test("a rename with no live record waits for a stale copy before settling", () => {
- const stale = { ...session, time: { created: 0, updated: 10 } }
- const renamed = { ...session, title: "Renamed", time: { created: 0, updated: 50 } }
+test("a projected send bump merged through an index never becomes a server time", () => {
+ const setup = setupDesktop(async () => Response.json({ data: session }))
- const batch = (records: SessionInfo[]) => {
- const recency = createSessionRecency()
- recency.renamed(session.id, undefined, 50)
+ try {
+ setup.seed(10)
+ setSystemTime(new Date(1_000))
+ setup.data.session.acceptSend(session.id)
- return recency.apply(records).map((item) => item.time.updated)
- }
+ // A list rendered the projected row, then merged it with a fetched copy whose idle did not advance.
+ const projected = setup.data.session.apply([{ ...session, time: { created: 0, updated: 10 } }])
+ expect(projected[0].time.updated).toBe(1_000)
- // Whichever order the copies appear in, the stale copy supplies the pre-rename value.
- expect(batch([stale, renamed])).toEqual([10, 10])
- expect(batch([renamed, stale])).toEqual([10, 10])
+ const merged = mergeRootSessionIndex(projected, [
+ { ...session, title: "Fetched", time: { created: 0, updated: 20 } },
+ ])
- const sequence = (records: SessionInfo[]) => {
- const recency = createSessionRecency()
- recency.renamed(session.id, undefined, 50)
+ expect(setup.data.session.apply(merged)[0].time.updated).toBe(1_000)
- return [...records, stale, renamed].map((record) => recency.apply([record])[0].time.updated)
+ // The server caught up behind the local clock. A laundered 1,000 would have pinned the session there.
+ expect(setup.data.session.apply([{ ...session, time: { created: 0, updated: 150 } }])[0].time.updated).toBe(150)
+ } finally {
+ setup.dispose()
}
-
- // A renamed-only read has nothing to compare against. It uses the creation floor instead of promoting to `at`.
- const renamedFirst = sequence([renamed])
- expect(renamedFirst[0]).toBe(0)
- expect(renamedFirst.slice(1)).toEqual([10, 10])
-
- const staleFirst = sequence([stale])
- expect(staleFirst).toEqual([10, 10, 10])
-})
-
-test("a pre-rename record observed before the rename supplies the guard value", () => {
- const recency = createSessionRecency()
- recency.apply([{ ...session, time: { created: 0, updated: 10 } }])
- recency.renamed(session.id, undefined, 50)
-
- expect(recency.apply([{ ...session, time: { created: 0, updated: 50 } }])[0].time.updated).toBe(10)
})
test("an accepted send promotes immediately and survives a stale fetch until the server catches up", () => {
@@ -246,23 +267,6 @@ test("an accepted send promotes immediately and survives a stale fetch until the
}
})
-test("a send after a rename is not demoted by a stale refetch at the rename time", () => {
- const setup = setupDesktop(async () => Response.json({ data: session }))
-
- try {
- setup.seed(10)
- setup.emit("session.renamed", 50, { title: "Renamed" })
- setSystemTime(new Date(1_000))
- setup.data.session.acceptSend(session.id)
-
- expect(
- setup.data.session.apply([{ ...session, title: "Renamed", time: { created: 0, updated: 50 } }])[0].time.updated,
- ).toBe(1_000)
- } finally {
- setup.dispose()
- }
-})
-
test("send catch-up does not depend on the order records are applied", () => {
const stale = { ...session, time: { created: 0, updated: 90 } }
const fresh = { ...session, time: { created: 0, updated: 150 } }
@@ -291,44 +295,6 @@ test("send catch-up does not depend on the order records are applied", () => {
expect(sequence([fresh, stale])).toBe(150)
})
-test("multiple renames keep the original pre-rename value through either renamed copy", () => {
- const recency = createSessionRecency()
- const pre = { ...session, time: { created: 0, updated: 10 } }
- const first = { ...session, time: { created: 0, updated: 50 } }
- const second = { ...session, time: { created: 0, updated: 80 } }
-
- recency.renamed(session.id, pre, 50)
- expect(recency.apply([first])[0].time.updated).toBe(10)
-
- // The live store now holds the first rename time, but it is not real activity.
- recency.renamed(session.id, first, 80)
- expect(recency.apply([first])[0].time.updated).toBe(10)
- expect(recency.apply([second])[0].time.updated).toBe(10)
- expect(recency.apply([first, second]).map((item) => item.time.updated)).toEqual([10, 10])
-})
-
-test("a refetch that lands before the rename event still supplies the pre-rename value", () => {
- const recency = createSessionRecency()
- const stale = { ...session, time: { created: 0, updated: 10 } }
- const renamed = { ...session, time: { created: 0, updated: 50 } }
-
- recency.apply([stale])
- recency.apply([renamed])
- recency.renamed(session.id, undefined, 50)
-
- expect(recency.apply([renamed])[0].time.updated).toBe(10)
-})
-
-test("a rename during a send does not clamp the session to the local send time", () => {
- const recency = createSessionRecency()
- const before = { ...session, time: { created: 0, updated: 200 } }
-
- recency.acceptSend(session.id, before, 1_000)
- recency.renamed(session.id, before, 300)
-
- expect(recency.apply([{ ...session, time: { created: 0, updated: 210 } }])[0].time.updated).toBe(210)
-})
-
test("remember restores the raw server time after apply projected a send bump", () => {
const setup = setupDesktop(async () => Response.json({ data: session }))
@@ -357,14 +323,6 @@ test("bounds per-session recency state", () => {
expect(recency.apply([{ ...session, id: "ses_0", time: { created: 0, updated: 0 } }])[0].time.updated).toBe(0)
})
-test("the newest indexed row keeps its pre-rename time across a large page batch", () => {
- const recency = createSessionRecency()
- const rows = Array.from({ length: 600 }, (_, i) => ({ ...session, id: `ses_${i}`, time: { created: 0, updated: 600 - i } }))
- recency.apply(rows)
- recency.renamed(rows[0].id, undefined, 1_000)
- expect(recency.apply([{ ...rows[0], time: { created: 0, updated: 1_000 } }])[0].time.updated).toBe(600)
-})
-
test("reading passively synced metadata leaves an accepted send pending for indexed lists", () => {
const recency = createSessionRecency()
const indexed = { ...session, time: { created: 0, updated: 10 } }
@@ -427,26 +385,33 @@ test.each(["loaded", "listed"] as const)("an execution end refreshes a %s root e
}
})
-test.each(["child", "unknown"] as const)("an execution end skips an unloaded %s session", async (source) => {
- let gets = 0
+test.each(["child", "unknown", "self-reloading"] as const)(
+ "an execution end skips an unloaded %s session",
+ async (source) => {
+ let gets = 0
- const setup = setupDesktop(async () => {
- gets++
+ const setup = setupDesktop(async () => {
+ gets++
- return Response.json({ data: session })
- })
+ return Response.json({ data: session })
+ })
- try {
- if (source === "child") setup.data.session.apply([{ ...session, parentID: "ses_parent" }])
- setup.emit("session.execution.succeeded", 50)
- await new Promise((resolve) => setTimeout(resolve, 0))
+ try {
+ if (source === "child") setup.data.session.apply([{ ...session, parentID: "ses_parent" }])
- expect(gets).toBe(0)
- expect(setup.data.session.get(session.id)).toBeUndefined()
- } finally {
- setup.dispose()
- }
-})
+ // Recent reloads its snapshot at run end, so its roots need no separate refresh.
+ if (source === "self-reloading") setup.data.session.apply([session], { reloads: true })
+
+ setup.emit("session.execution.succeeded", 50)
+ await new Promise((resolve) => setTimeout(resolve, 0))
+
+ expect(gets).toBe(0)
+ expect(setup.data.session.get(session.id)).toBeUndefined()
+ } finally {
+ setup.dispose()
+ }
+ },
+)
test("coalesces overlapping refreshes for one session and keeps a queued one", async () => {
const calls: string[] = []
diff --git a/packages/app/src/runtime/server/data.ts b/packages/app/src/runtime/server/data.ts
index b711366afbaf..58054affd613 100644
--- a/packages/app/src/runtime/server/data.ts
+++ b/packages/app/src/runtime/server/data.ts
@@ -8,17 +8,11 @@ type SessionMutation = { readonly id: string; readonly type: "remove"; readonly
type SendRecency = { readonly sentAt: number; readonly serverUpdatedAt: number }
-type RenameRecency = { readonly ats: Set; readonly latest: number; previous?: number }
-
-type ObservedRecency = { readonly values: readonly number[] }
-
const REMOVED_SESSION_LIMIT = 512
// Recency bookkeeping is per session and only needed for lists; bound it like the removed-session set.
const RECENCY_SESSION_LIMIT = 512
-const OBSERVED_VALUE_LIMIT = 4
-
// Times returned by apply() are projections. Remember their raw server value so remember() never stores the bump.
const syntheticTimes = new WeakMap()
@@ -48,16 +42,9 @@ export function createDesktopData(input: { data: Data; remove: (sessionID: strin
mutation.deleted(event.data.sessionID)
}),
)
- // Renaming advances `time.updated` server-side. Remember the value shown before the rename so a refetch of the
- // renamed record cannot promote the session; a newer record becomes the floor so stale refetches cannot demote it.
- onCleanup(
- input.data.on("session.renamed", (event) => {
- recency.renamed(event.data.sessionID, session(event.data.sessionID), event.created)
- changed()
- }),
- )
// The SDK invalidates and syncs loaded sessions on execution end. Desktop also needs a fresh record for roots
- // that only appear in a fetched index. Coalesce those reads across overlapping ends.
+ // that only appear in an index that does not reload itself at run end (Home, Inbox, the project sidebars).
+ // Coalesce those reads across overlapping ends.
SESSION_EXECUTION_ENDED.forEach((type) =>
onCleanup(
input.data.on(type, (event) => {
@@ -75,12 +62,13 @@ export function createDesktopData(input: { data: Data; remove: (sessionID: strin
return input.data.session.get(sessionID) ?? input.data.session.list().find((item) => item.id === sessionID)
}
- const apply = (sessions: readonly SessionInfo[]) => {
+ // `reloads` marks a list that reloads its own snapshot at run end, so its roots need no per-session refresh.
+ const apply = (sessions: readonly SessionInfo[], options?: { reloads: true }) => {
version.value
- const result = recency.apply(mutation.apply(sessions))
+ const result = recency.apply(mutation.apply(sessions), !options?.reloads)
- // A record can settle a send or a rename while a memo reads it. Rerun the other readers after this computation
+ // A record can settle a send while a memo reads it. Rerun the other readers after this computation
// so every list converges on the same recency in the next tick.
if (recency.takeMutated()) queueMicrotask(changed)
@@ -96,7 +84,7 @@ export function createDesktopData(input: { data: Data; remove: (sessionID: strin
return mutation.apply(input.data.session.list()).map(recency.project)
},
- // Index consumers merge the raw server snapshots before applying pending sends and rename protection.
+ // Index consumers merge the raw server snapshots before applying pending sends.
known: input.data.session.list,
apply,
remember(info: SessionInfo) {
@@ -121,13 +109,12 @@ export function createDesktopData(input: { data: Data; remove: (sessionID: strin
export function createSessionRecency() {
const sends = new Map()
- const renames = new Map()
// The newest server value a send's catch-up has taught us. Stale list fetches must not drop below it.
const floors = new Map()
- // Raw non-rename values already rendered, newest first. A rename with no live record recovers its pre-rename
- // value from here even when a refetched rename record landed before the SSE event.
- const observed = new Map()
- // Run-end refresh eligibility comes from list reads. A send or rename can also populate timestamp history.
+ // The newest server time any list row has shown. The live record lags it after a rename, model or agent change,
+ // step or metadata update, so a send starts from it. Only a send reads it, so nothing reorders on it.
+ const latest = new Map()
+ // Run-end refresh eligibility comes from reads of lists that do not reload themselves.
const listedRoots = new Map()
let mutated = false
@@ -143,138 +130,59 @@ export function createSessionRecency() {
}
const grow = (map: Map, sessionID: string, value: number) => {
- if (value <= (map.get(sessionID) ?? Number.NEGATIVE_INFINITY)) return
+ if (value <= (map.get(sessionID) ?? Number.NEGATIVE_INFINITY)) return false
keep(map, sessionID, value)
- mutated = true
- }
- const observe = (sessionID: string, value: number) => {
- if (renames.get(sessionID)?.ats.has(value)) return
-
- const values = observed.get(sessionID)?.values ?? []
-
- if (values.includes(value)) return
-
- keep(observed, sessionID, {
- values: [...values, value].sort((a, b) => b - a).slice(0, OBSERVED_VALUE_LIMIT),
- })
+ return true
}
- const observedPrior = (sessionID: string) => observed.get(sessionID)?.values[0]
-
// Reading live metadata for status must not settle a send or change another list's ordering.
function project(info: SessionInfo) {
const send = sends.get(info.id)
- const updated = rawTime(info)
+ const raw = rawTime(info)
+ const updated = Math.max(raw, floors.get(info.id) ?? 0)
- if (send) return withTime(info, Math.max(updated, send.sentAt, floors.get(info.id) ?? 0))
+ grow(latest, info.id, raw)
- const rename = renames.get(info.id)
-
- const projected = rename
- ? rename.ats.has(updated)
- ? (rename.previous ?? observedPrior(info.id) ?? Math.min(info.time.created, rename.latest))
- : Math.max(updated, rename.previous ?? 0)
- : updated
-
- return withTime(info, Math.max(projected, floors.get(info.id) ?? 0))
+ return withTime(info, send ? Math.max(updated, send.sentAt) : updated)
}
return {
project,
wasListedRoot: (sessionID: string) => listedRoots.has(sessionID),
acceptSend(sessionID: string, info: SessionInfo | undefined, sentAt: number) {
- const previous = sends.get(sessionID)
- const renamedAt = renames.get(sessionID)?.latest ?? 0
- const updated = info ? rawTime(info) : 0
keep(sends, sessionID, {
sentAt,
- // Keep the highest server value known before this send. A pending rename is already on the server, so a
- // stale fetch at the rename time must not be mistaken for the send catching up.
- serverUpdatedAt: Math.max(previous?.serverUpdatedAt ?? 0, updated, renamedAt, floors.get(sessionID) ?? 0),
+ // Keep the highest server value known before this send; only a newer server record settles it.
+ serverUpdatedAt: Math.max(
+ sends.get(sessionID)?.serverUpdatedAt ?? 0,
+ info ? rawTime(info) : 0,
+ floors.get(sessionID) ?? 0,
+ latest.get(sessionID) ?? 0,
+ ),
})
-
- if (info) observe(sessionID, updated)
},
- renamed(sessionID: string, info: SessionInfo | undefined, at: number) {
- const existing = renames.get(sessionID)
- const ats = new Set(existing?.ats ?? [])
- ats.add(at)
-
- if (ats.size > RECENCY_SESSION_LIMIT) {
- const oldest = ats.values().next().value
-
- if (oldest !== undefined) ats.delete(oldest)
- }
-
- // The rename time itself is not activity. Drop it, and every earlier rename time, from the observed values.
- const values = (observed.get(sessionID)?.values ?? []).filter((value) => !ats.has(value))
-
- if (values.length > 0) keep(observed, sessionID, { values })
- else observed.delete(sessionID)
-
- const infoUpdated = info ? rawTime(info) : undefined
- const infoPrior = infoUpdated !== undefined && !ats.has(infoUpdated) ? infoUpdated : undefined
-
- const previous = Math.max(
- existing?.previous ?? Number.NEGATIVE_INFINITY,
- infoPrior ?? Number.NEGATIVE_INFINITY,
- values[0] ?? Number.NEGATIVE_INFINITY,
- floors.get(sessionID) ?? Number.NEGATIVE_INFINITY,
- )
-
- keep(renames, sessionID, {
- ats,
- latest: Math.max(existing?.latest ?? 0, at),
- previous: previous === Number.NEGATIVE_INFINITY ? undefined : previous,
- })
- },
- apply(infos: readonly SessionInfo[]) {
+ apply(infos: readonly SessionInfo[], listed = true) {
mutated = false
- const pending = new Map()
+ const newest = new Map()
- // Settle state from the whole batch first, so [stale, fresh] and [fresh, stale] compute the same values.
+ // Settle from the whole batch first, so [stale, fresh] and [fresh, stale] compute the same values.
for (const [index, info] of infos.entries()) {
- const rename = renames.get(info.id)
- const updated = rawTime(info)
- const renameTime = rename?.ats.has(updated) ?? false
-
- if (index < RECENCY_SESSION_LIMIT) {
- if (!info.parentID) keep(listedRoots, info.id, true)
-
- if (!renameTime) observe(info.id, updated)
- }
+ if (listed && index < RECENCY_SESSION_LIMIT && !info.parentID) keep(listedRoots, info.id, true)
- if (!sends.has(info.id) && !rename) continue
+ if (!sends.has(info.id)) continue
- const settled = pending.get(info.id) ?? {
- newest: Number.NEGATIVE_INFINITY,
- settled: rename?.previous ?? Number.NEGATIVE_INFINITY,
- }
-
- if (!renameTime) {
- settled.newest = Math.max(settled.newest, updated)
- settled.settled = Math.max(settled.settled, updated)
- }
-
- pending.set(info.id, settled)
+ newest.set(info.id, Math.max(newest.get(info.id) ?? Number.NEGATIVE_INFINITY, rawTime(info)))
}
- pending.forEach((settled, sessionID) => {
+ newest.forEach((updated, sessionID) => {
const send = sends.get(sessionID)
- if (send && settled.newest > send.serverUpdatedAt) {
- sends.delete(sessionID)
- mutated = true
- grow(floors, sessionID, settled.newest)
- }
-
- const rename = renames.get(sessionID)
+ if (!send || updated <= send.serverUpdatedAt) return
- if (rename && settled.settled > (rename.previous ?? Number.NEGATIVE_INFINITY)) {
- rename.previous = settled.settled
- mutated = true
- }
+ sends.delete(sessionID)
+ mutated = true
+ grow(floors, sessionID, updated)
})
return infos.map(project)
@@ -288,15 +196,15 @@ export function createSessionRecency() {
},
forget(sessionID: string) {
sends.delete(sessionID)
- renames.delete(sessionID)
floors.delete(sessionID)
- observed.delete(sessionID)
+ latest.delete(sessionID)
listedRoots.delete(sessionID)
},
}
}
-function rawTime(info: SessionInfo) {
+/** The server's `time.updated` behind a row `apply` or `list` may have projected. Copy it when cloning a row's time. */
+export function rawTime(info: SessionInfo) {
return syntheticTimes.get(info.time) ?? info.time.updated
}
diff --git a/packages/app/src/runtime/server/session-index.ts b/packages/app/src/runtime/server/session-index.ts
index b75689aafabe..7ec5fda0cd7e 100644
--- a/packages/app/src/runtime/server/session-index.ts
+++ b/packages/app/src/runtime/server/session-index.ts
@@ -1,13 +1,22 @@
import type { SessionInfo } from "@opencode/client/promise"
+import { rawTime } from "./data"
/** Merge live metadata into indexed roots. Only a completed run advances an indexed row's recency. */
export function mergeRootSessionIndex(indexed: readonly SessionInfo[], known: readonly SessionInfo[]) {
const rows = new Map(indexed.map((info) => [info.id, info]))
for (const info of known) {
- const time = rows.get(info.id)?.time
- const passive = time && (info.time.idle ?? 0) <= (time.idle ?? 0) && info.time.updated !== time.updated
- rows.set(info.id, passive ? { ...info, time: { ...info.time, updated: time.updated } } : info)
+ const row = rows.get(info.id)
+
+ if (!row) {
+ rows.set(info.id, info)
+ continue
+ }
+
+ // A projected send bump must not reach `apply` as a server time, so copy the raw one.
+ const updated = rawTime(row)
+ const passive = (info.time.idle ?? 0) <= (row.time.idle ?? 0) && info.time.updated !== updated
+ rows.set(info.id, passive ? { ...info, time: { ...info.time, updated } } : info)
}
return [...rows.values()].filter((info) => !info.parentID)
diff --git a/packages/app/src/session/commands/rename-session.ts b/packages/app/src/session/commands/rename-session.ts
index dba965c2e9cf..727d0799c11f 100644
--- a/packages/app/src/session/commands/rename-session.ts
+++ b/packages/app/src/session/commands/rename-session.ts
@@ -18,10 +18,14 @@ export function createSessionRenamer() {
if (!ctx || !conn) throw new Error(language.t("common.requestFailed"))
await ctx.sdk.api.session.update({ sessionID: session.id, title })
- // The data layer's rename guard keeps the server's advanced time.updated from moving the session.
ctx.data.session.remember({ ...(ctx.data.session.get(session.id) ?? session), title })
- void queryClient.invalidateQueries({ queryKey: ["home-sessions", conn], exact: true })
- void queryClient.invalidateQueries({ queryKey: ["inbox-sessions", conn], exact: true })
- void queryClient.invalidateQueries({ queryKey: ["inbox-archived-sessions", conn], exact: true })
+
+ // Like the iOS app, a rename changes the title only. The server advanced time.updated, and the session moves
+ // when a list next reloads, so update the cached indexes instead of refetching them now.
+ for (const queryKey of ["home-sessions", "inbox-sessions", "inbox-archived-sessions"]) {
+ queryClient.setQueryData([queryKey, conn], (current) =>
+ current?.map((item) => (item.id === session.id ? { ...item, title } : item)),
+ )
+ }
}
}
diff --git a/packages/app/src/shell/commands/palette.ts b/packages/app/src/shell/commands/palette.ts
index 9f3161e12f12..31578e290a93 100644
--- a/packages/app/src/shell/commands/palette.ts
+++ b/packages/app/src/shell/commands/palette.ts
@@ -197,6 +197,7 @@ export function createCommandPaletteModel(props: { filesOnly?: () => boolean; on
const sessions = createServerSessionEntries({
server: ServerConnection.key(serverSDK.server),
known: createKnownServerSessions(() => serverCtx),
+ apply: serverCtx.data.session.apply,
projects: serverCtx.projects.list,
load: (search, signal) =>
serverSDK.api.session.list({ parentID: null, search, archived: false, limit: 50 }, { signal }),
@@ -271,7 +272,7 @@ export function createServerSessionEntries(props: {
server: ServerConnection.Key
archived?: boolean
known?: () => SessionInfo[]
- /** Hides sessions deleted since they were loaded. */
+ /** Hides sessions deleted since they were loaded and adds a pending send's bump. */
apply?: (sessions: SessionInfo[]) => SessionInfo[]
projects: () => Project[]
load: (search: string, signal: AbortSignal) => Promise<{ data: SessionInfo[] }>
@@ -294,12 +295,11 @@ export function createServerSessionEntries(props: {
>()
// The server's list carries each step's `time.updated` bump. Like Home, keep the cached time until a run ends.
+ // Sort after `apply` so a pending send's bump decides which sessions make the recent group.
const known = createMemo(() => {
- const merged = mergeRootSessionIndex(props.known?.() ?? [], sourceState().loaded).toSorted(
- (a, b) => b.time.updated - a.time.updated,
- )
+ const merged = mergeRootSessionIndex(props.known?.() ?? [], sourceState().loaded)
- return props.apply?.(merged) ?? merged
+ return (props.apply?.(merged) ?? merged).toSorted((a, b) => b.time.updated - a.time.updated)
})
const dispatch = (event: SessionSourceEvent) =>
@@ -452,6 +452,7 @@ export function createKnownServerSessions(context: Accessor !session.parentID && !session.time.archived)
+ // Raw records: `apply` adds the send bump after the merge, so a projected time never reaches it as a server time.
+ return server.data.session.known().filter((session) => !session.parentID && !session.time.archived)
}
}
diff --git a/packages/app/src/shell/commands/session-search.tsx b/packages/app/src/shell/commands/session-search.tsx
index f0b142bd31d1..4f9fbe17d85f 100644
--- a/packages/app/src/shell/commands/session-search.tsx
+++ b/packages/app/src/shell/commands/session-search.tsx
@@ -38,7 +38,7 @@ export function DialogSessionSearch(props: { archived?: boolean }) {
server: ServerConnection.key(conn),
archived: props.archived,
known: props.archived
- ? () => ctx.data.session.list().filter((session) => !session.parentID)
+ ? () => ctx.data.session.known().filter((session) => !session.parentID)
: createKnownServerSessions(() => ctx),
apply: ctx.data.session.apply,
projects: ctx.projects.list,
diff --git a/packages/app/src/shell/titlebar/inbox-model.ts b/packages/app/src/shell/titlebar/inbox-model.ts
index e3f580cce1ae..a24e0ee42ab3 100644
--- a/packages/app/src/shell/titlebar/inbox-model.ts
+++ b/packages/app/src/shell/titlebar/inbox-model.ts
@@ -12,6 +12,7 @@ import { useTabs } from "@/shell/tabs/tabs"
import { sessionBusy, sessionRequests, type SessionRequests } from "@/shell/layout/project-avatar-state"
import { pathKey } from "@/workspaces/path-key"
import { parseHomeSessionIndex } from "@/home/sessions/index"
+import { rawTime } from "@/runtime/server/data"
import { mergeRootSessionIndex } from "@/runtime/server/session-index"
import { sessionFormRequest, sessionPermissionRequest, sessionTreeIDs } from "@/session/requests/session-request-tree"
import { notifySessionTabsRemoved } from "./session-events"
@@ -411,7 +412,11 @@ export function createSessionInbox(options: { archived?: boolean } = {}) {
// Move the session between the cached indexes so it changes section before either refetches.
const move = (entry: InboxEntry, archivedAt: number | undefined) => {
- const session = { ...entry.session, time: { ...entry.session.time, archived: archivedAt } }
+ // The cached index goes back through `apply`, so it keeps the server time rather than a send bump.
+ const session = {
+ ...entry.session,
+ time: { ...entry.session.time, updated: rawTime(entry.session), archived: archivedAt },
+ }
forget(entry.conn, entry.session.id)
queryClient.setQueryData(
diff --git a/packages/app/src/shell/titlebar/recent-sessions-model.test.ts b/packages/app/src/shell/titlebar/recent-sessions-model.test.ts
index 9fc8e5fcc09c..6a163f2d850e 100644
--- a/packages/app/src/shell/titlebar/recent-sessions-model.test.ts
+++ b/packages/app/src/shell/titlebar/recent-sessions-model.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from "bun:test"
-import type { SessionInfo } from "@opencode/client/promise"
+import type { OpenCodeEvent, SessionInfo } from "@opencode/client/promise"
import { resolveServerList, ServerConnection } from "@/runtime/server/registry"
import {
addPin,
@@ -11,6 +11,9 @@ import {
RECENT_WINDOW_MS,
mergeRecentSessions,
partitionRecentSessions,
+ recentPageHasMore,
+ recentPageLoadingMore,
+ recentReloadsOn,
recentSessionEndpoints,
recentSessionKey,
recentRowUnread,
@@ -119,8 +122,51 @@ test("merging prefers the live store and keeps root, unarchived sessions", () =>
item("server", session("ses_a", 10, { title: "loaded" })),
item("server", session("ses_live", 5)),
])
- const ended = session("ses_a", 30, { time: { created: 1, updated: 30, idle: 29 } })
- expect(mergeRecentSessions("server", [session("ses_a", 10)], [ended])).toEqual([item("server", ended)])
+})
+
+// Like the iOS app, only a reload of the list or the user's own send moves a row.
+test.each([
+ ["a rename", session("ses_b", 30, { title: "Renamed" })],
+ ["a model selection", session("ses_b", 30, { model: { providerID: "provider", id: "other" } })],
+ ["an agent selection", session("ses_b", 30, { agent: "plan" })],
+ ["a step", session("ses_b", 30, { time: { created: 1, updated: 30, busy: 30 } })],
+ ["a run end", session("ses_b", 30, { time: { created: 1, updated: 30, idle: 30 } })],
+])("%s does not move a row until the next reload, which re-sorts it", (_, live) => {
+ const order = (fetched: readonly SessionInfo[]) =>
+ mergeRecentSessions("server", fetched, [live]).map((entry) => entry.session.id)
+
+ const snapshot = readyPage([session("ses_a", 20), session("ses_b", 10)])
+ expect(order(snapshot.sessions)).toEqual(["ses_a", "ses_b"])
+ expect(mergeRecentSessions("server", snapshot.sessions, [live])[1]?.session).toEqual({
+ ...live,
+ time: { ...live.time, updated: 10 },
+ })
+
+ const started = transitionRecentPage(snapshot, { type: "reload", attempt: 1 })
+
+ const reloaded = transitionRecentPage(started.state, {
+ type: "succeeded",
+ attempt: 1,
+ sessions: [session("ses_b", 30), session("ses_a", 20)],
+ next: undefined,
+ })
+
+ expect(order(reloaded.state.sessions)).toEqual(["ses_b", "ses_a"])
+})
+
+test("a session created since the last reload ranks by its live time, an older one outside the pages never above them", () => {
+ // Another client renamed an old session, and the live store loaded it with the rename time.
+ const renamed = session("ses_renamed", 300, { time: { created: 5, updated: 300 } })
+ const created = session("ses_created", 200, { time: { created: 200, updated: 200 } })
+
+ const merged = mergeRecentSessions("server", [session("ses_a", 100), session("ses_b", 90)], [renamed, created])
+
+ expect(merged.map((entry) => [entry.session.id, entry.session.time.updated])).toEqual([
+ ["ses_created", 200],
+ ["ses_a", 100],
+ ["ses_b", 90],
+ ["ses_renamed", 90],
+ ])
})
test("sessions with equal timestamps order by id, and missing updates fall back to creation", () => {
@@ -480,6 +526,148 @@ test("a reconnect snapshot drops page-one ghosts and keeps older rows and the ad
expect(page.state.olderLoaded).toBe(true)
})
+test("a reload waits for the first page, and otherwise starts page one again", () => {
+ expect(transitionRecentPage(INITIAL_RECENT_PAGE_STATE, { type: "reload", attempt: 1 }).state).toBe(
+ INITIAL_RECENT_PAGE_STATE,
+ )
+
+ const first = transitionRecentPage(INITIAL_RECENT_PAGE_STATE, { type: "load", kind: "first", attempt: 1 })
+ expect(transitionRecentPage(first.state, { type: "reload", attempt: 2 }).state).toMatchObject({
+ kind: "first",
+ attempt: 2,
+ })
+
+ const reconnect = transitionRecentPage(readyPage([session("ses_a", 20)]), {
+ type: "load",
+ kind: "refresh",
+ attempt: 3,
+ })
+
+ expect(transitionRecentPage(reconnect.state, { type: "reload", attempt: 4 }).state).toMatchObject({
+ kind: "refresh",
+ attempt: 4,
+ })
+
+ const reloaded = transitionRecentPage(readyPage([session("ses_a", 20)], { cursor: "cursor-2" }), {
+ type: "reload",
+ attempt: 5,
+ })
+
+ expect(reloaded.state).toMatchObject({ status: "loading", kind: "reload", cursor: "cursor-2" })
+ expect(reloaded.effects[0]).toEqual({ type: "fetch", attempt: 5, cursor: undefined })
+ expect(recentPageLoadingMore(reloaded.state)).toBe(false)
+})
+
+test("Show more stays while a snapshot reload runs, and gives way to the loader for its own page", () => {
+ const state = readyPage([session("ses_a", 20)], { cursor: "cursor-2" })
+ const reload = transitionRecentPage(state, { type: "reload", attempt: 1 })
+ const refresh = transitionRecentPage(state, { type: "load", kind: "refresh", attempt: 2 })
+ const next = transitionRecentPage(state, { type: "load", kind: "next", attempt: 3 })
+
+ expect([state, reload.state, refresh.state, next.state].map(recentPageHasMore)).toEqual([true, true, true, false])
+})
+
+test("a reload supersedes Show more's page and keeps the older rows already loaded", () => {
+ const first = session("ses_first", 100)
+ const older = session("ses_older", 10)
+ const state = readyPage([first, older], { cursor: "cursor-3", olderLoaded: true })
+ const next = transitionRecentPage(state, { type: "load", kind: "next", attempt: 1 })
+ expect(recentPageLoadingMore(next.state)).toBe(true)
+
+ const reload = transitionRecentPage(next.state, { type: "reload", attempt: 2 })
+
+ // The superseded page cannot land after the reload started.
+ expect(
+ transitionRecentPage(reload.state, { type: "succeeded", attempt: 1, sessions: [session("ses_x", 5)], next: "x" })
+ .state,
+ ).toBe(reload.state)
+
+ const incoming = [
+ session("ses_moved", 200),
+ first,
+ ...Array.from({ length: RECENT_PAGE_LIMIT - 2 }, (_, i) => session(`ses_new${i}`, 99 - i)),
+ ]
+
+ const page = transitionRecentPage(reload.state, {
+ type: "succeeded",
+ attempt: 2,
+ sessions: incoming,
+ next: "cursor-2",
+ })
+
+ expect(page.state).toMatchObject({ status: "ready", cursor: "cursor-3", olderLoaded: true })
+ expect(page.state.sessions.map((entry) => entry.id).toSorted()).toEqual(
+ [...incoming, older].map((entry) => entry.id).toSorted(),
+ )
+
+ const failed = transitionRecentPage(transitionRecentPage(page.state, { type: "reload", attempt: 3 }).state, {
+ type: "failed",
+ attempt: 3,
+ })
+
+ expect(transitionRecentPage(failed.state, { type: "retry", attempt: 4 }).state).toMatchObject({
+ kind: "reload",
+ sessions: page.state.sessions,
+ })
+})
+
+test("run ends reload Recent except a known subagent's or a shutdown, as do new root sessions and archiving", () => {
+ const sessions = new Map([
+ ["ses_root", session("ses_root", 10)],
+ ["ses_child", session("ses_child", 10, { parentID: "ses_root" })],
+ ])
+
+ const envelope = (sessionID: string) => ({
+ id: `evt_${sessionID}`,
+ created: 1,
+ durable: { aggregateID: sessionID, seq: 1, version: 1 as const },
+ })
+
+ const ended = (sessionID: string) => ({
+ ...envelope(sessionID),
+ type: "session.execution.succeeded" as const,
+ data: { sessionID },
+ })
+
+ const failed = (sessionID: string) => ({
+ ...envelope(sessionID),
+ type: "session.execution.failed" as const,
+ data: { sessionID, error: { type: "unknown", message: "failed" } },
+ })
+
+ const interrupted = (sessionID: string, reason: "user" | "shutdown") => ({
+ ...envelope(sessionID),
+ type: "session.execution.interrupted" as const,
+ data: { sessionID, reason },
+ })
+
+ const created = (sessionID: string, parentID?: string) => ({
+ ...envelope(sessionID),
+ type: "session.created" as const,
+ data: { sessionID, projectID: "project", location: { directory: "/project" }, slug: sessionID, version: "1", parentID },
+ })
+
+ const cases: [OpenCodeEvent, boolean][] = [
+ [ended("ses_root"), true],
+ [failed("ses_root"), true],
+ [interrupted("ses_root", "user"), true],
+ [ended("ses_unknown"), true],
+ [ended("ses_child"), false],
+ [failed("ses_child"), false],
+ [interrupted("ses_child", "user"), false],
+ [interrupted("ses_root", "shutdown"), false],
+ [created("ses_new"), true],
+ [created("ses_sub", "ses_root"), false],
+ [{ ...envelope("ses_root"), type: "session.archived", data: { sessionID: "ses_root" } }, true],
+ [{ ...envelope("ses_root"), type: "session.unarchived", data: { sessionID: "ses_root" } }, true],
+ [{ ...envelope("ses_root"), type: "session.renamed", data: { sessionID: "ses_root", title: "Renamed" } }, false],
+ ]
+
+ expect(cases.map(([value]) => recentReloadsOn(value, (id) => sessions.get(id)))).toEqual(
+ cases.map(([, expected]) => expected),
+ )
+})
+
test("removing a server clears its page", () => {
const state = readyPage([session("ses_a", 20)], { cursor: "cursor-2" })
const removed = transitionRecentPage(state, { type: "removed" })
diff --git a/packages/app/src/shell/titlebar/recent-sessions-model.ts b/packages/app/src/shell/titlebar/recent-sessions-model.ts
index a3e23742c208..c9774f6840cb 100644
--- a/packages/app/src/shell/titlebar/recent-sessions-model.ts
+++ b/packages/app/src/shell/titlebar/recent-sessions-model.ts
@@ -1,6 +1,5 @@
-import type { SessionInfo } from "@opencode/client/promise"
+import type { OpenCodeEvent, SessionInfo } from "@opencode/client/promise"
import { ServerConnection } from "@/runtime/server/registry"
-import { mergeHomeSessionIndex } from "@/home/sessions/index"
const separator = "\u0000"
@@ -9,6 +8,9 @@ export const RECENT_PAGE_LIMIT = 50
/** Bounds a hanging server request; matches the Home session list's fetch deadline. */
export const RECENT_PAGE_TIMEOUT_MS = 30_000
+/** Coalesces the events that reload a server's first page, like the iOS app's session list. */
+export const RECENT_RELOAD_DELAY_MS = 250
+
export type RecentSession = {
/** `${server}\u0000${sessionID}`, the same key the pin order stores. */
key: string
@@ -132,19 +134,26 @@ type RecentPageBase = {
readonly olderLoaded: boolean
}
+/**
+ * How a load joins the rows already held. `refresh` is a reconnect snapshot, which also re-reads pins it does not
+ * cover; `reload` is the same snapshot taken while connected (run end, new session, focus, archive).
+ */
+type RecentPageKind = "first" | "next" | "refresh" | "reload"
+
/** One server's fetched pages. `loading.kind` decides how a response joins the rows already held. */
export type RecentPageState =
| ({ readonly status: "idle" } & RecentPageBase)
| ({
readonly status: "loading"
- readonly kind: "first" | "next" | "refresh"
+ readonly kind: RecentPageKind
readonly attempt: number
} & RecentPageBase)
| ({ readonly status: "ready" } & RecentPageBase)
- | ({ readonly status: "failed"; readonly kind: "first" | "next" | "refresh" } & RecentPageBase)
+ | ({ readonly status: "failed"; readonly kind: RecentPageKind } & RecentPageBase)
export type RecentPageEvent =
| { readonly type: "load"; readonly kind: "first" | "next" | "refresh"; readonly attempt: number }
+ | { readonly type: "reload"; readonly attempt: number }
| { readonly type: "retry"; readonly attempt: number }
| {
readonly type: "succeeded"
@@ -190,7 +199,7 @@ function mergeSessions(current: readonly SessionInfo[], next: readonly SessionIn
return [...new Map([...current, ...next].map((session) => [session.id, session] as const)).values()]
}
-function startLoading(state: RecentPageState, kind: "first" | "next" | "refresh", attempt: number) {
+function startLoading(state: RecentPageState, kind: RecentPageKind, attempt: number) {
const requestCursor = kind === "next" ? state.cursor : undefined
const cursor = kind === "first" ? undefined : state.cursor
@@ -278,6 +287,29 @@ function finishLoading(
}
}
+/**
+ * Whether an event changes which root sessions page one holds or their order, so Recent reloads it: a run that ended
+ * (except a shutdown, which leaves the server's times alone), a new root session, archive and unarchive. A run end
+ * from a known subagent session does not; an unknown session may be a root, so it does.
+ */
+export function recentReloadsOn(event: OpenCodeEvent, session: (sessionID: string) => SessionInfo | undefined) {
+ if (event.type === "session.created") return !event.data.parentID
+
+ if (event.type === "session.archived" || event.type === "session.unarchived") return true
+
+ if (event.type === "session.execution.interrupted" && event.data.reason === "shutdown") return false
+
+ if (
+ event.type !== "session.execution.succeeded" &&
+ event.type !== "session.execution.failed" &&
+ event.type !== "session.execution.interrupted"
+ ) {
+ return false
+ }
+
+ return !session(event.data.sessionID)?.parentID
+}
+
/** One server's page lifecycle. I/O lives in the driver; this only says what to fetch and what the rows become. */
export function transitionRecentPage(
state: RecentPageState,
@@ -297,6 +329,16 @@ export function transitionRecentPage(
return startLoading(state, event.kind, event.attempt)
}
+ // A reload supersedes whatever is in flight, so an older response cannot land after it. Before the first page
+ // there is nothing to reload, and a pending first page or reconnect refresh keeps its own kind.
+ if (event.type === "reload") {
+ if (state.status === "idle") return unchanged(state)
+
+ const pending = state.status !== "ready" && (state.kind === "first" || state.kind === "refresh")
+
+ return startLoading(state, pending ? state.kind : "reload", event.attempt)
+ }
+
if (event.type === "retry") {
if (state.status !== "failed") return unchanged(state)
@@ -332,18 +374,45 @@ export function recentPageFailed(state: RecentPageState | undefined) {
return state?.status === "failed"
}
+/** Only Show more's page shows a loader; snapshot reloads replace rows in place. */
+export function recentPageLoadingMore(state: RecentPageState | undefined) {
+ return state?.status === "loading" && state.kind === "next"
+}
+
export function recentPageHasMore(state: RecentPageState | undefined) {
- return !!state && (state.status === "ready" || state.status === "failed") && !state.exhausted && !!state.cursor
+ if (!state || state.exhausted || !state.cursor) return false
+
+ // A snapshot reload keeps the pages and cursor it started with, so Show more stays while it runs.
+ return state.status !== "idle" && (state.status !== "loading" || state.kind === "reload" || state.kind === "refresh")
}
-/** One server's sessions plus the live store, keeping root, unarchived sessions. Live entries win. */
+/**
+ * One server's fetched pages plus the live store, keeping root, unarchived sessions. Live entries supply every field
+ * except `time.updated`: a fetched row keeps the time from its page until the next reload, so steps, renames and
+ * model or agent changes never reorder it. A session created since the last reload uses its live time. One that
+ * existed then but is outside the loaded pages was older than all of them, so it never ranks above them before a
+ * reload includes it, even when the live store loaded it with a newer time (a rename from another client).
+ * `apply` adds the local send bump.
+ */
export function mergeRecentSessions(
server: string,
fetched: readonly SessionInfo[],
known: readonly SessionInfo[],
apply: (rows: SessionInfo[]) => SessionInfo[] = (rows) => rows,
) {
- const sessions = apply(mergeHomeSessionIndex(fetched, known))
+ const snapshot = new Map(fetched.map((info) => [info.id, info.time.updated]))
+ const rows = new Map(fetched.map((info) => [info.id, info]))
+ const newest = fetched.reduce((value, info) => Math.max(value, info.time.updated), -Infinity)
+ const oldest = fetched.reduce((value, info) => Math.min(value, info.time.updated), Infinity)
+
+ for (const info of known) {
+ const updated =
+ snapshot.get(info.id) ?? (info.time.created <= newest ? Math.min(info.time.updated, oldest) : info.time.updated)
+
+ rows.set(info.id, updated === info.time.updated ? info : { ...info, time: { ...info.time, updated } })
+ }
+
+ const sessions = apply([...rows.values()].filter((info) => !info.parentID && info.time.archived === undefined))
return sortRecentSessions(sessions.map((session) => ({ key: recentSessionKey(server, session.id), server, session })))
}
diff --git a/packages/app/src/shell/titlebar/recent-sessions.tsx b/packages/app/src/shell/titlebar/recent-sessions.tsx
index 82301499aaac..9667e42deff2 100644
--- a/packages/app/src/shell/titlebar/recent-sessions.tsx
+++ b/packages/app/src/shell/titlebar/recent-sessions.tsx
@@ -17,6 +17,7 @@ import { arrayMove } from "@/runtime/array-move"
import { useLanguage } from "@/runtime/i18n/language"
import { Persistence } from "@/runtime/persistence/schema"
import { Persist, persisted } from "@/runtime/persistence/storage"
+import { rawTime } from "@/runtime/server/data"
import { ServerConnection, useServers } from "@/runtime/server/registry"
import { useGlobal, type ServerCtx } from "@/runtime/server/runtime"
import { sessionTreeIDs } from "@/session/requests/session-request-tree"
@@ -31,12 +32,15 @@ import {
dedupePins,
INITIAL_RECENT_PAGE_STATE,
RECENT_PAGE_LIMIT,
+ RECENT_RELOAD_DELAY_MS,
RECENT_VISIBLE_LIMIT,
mergeRecentSessions,
partitionRecentSessions,
recentPageFailed,
recentPageHasMore,
recentPageLoaded,
+ recentPageLoadingMore,
+ recentReloadsOn,
recentRowUnread,
recentSessionEndpoints,
recentSessionKey,
@@ -92,6 +96,7 @@ export function RecentSessions() {
const controllers = new Map()
const timers = new Map>()
+ const reloads = new Map>()
const hydrationControllers = new Map()
const statuses = new Map()
let attempt = 0
@@ -120,6 +125,27 @@ export function RecentSessions() {
timers.delete(server)
}
+ const cancelReload = (server: string) => {
+ clearTimeout(reloads.get(server))
+ reloads.delete(server)
+ }
+
+ // Order follows each server's last snapshot, so the moments the iOS app reloads its list reload page one here:
+ // run end, a new root session, archive and unarchive, and the window coming back. Bursts coalesce per server.
+ const reload = (item: Connection) => {
+ cancelReload(item.server)
+ reloads.set(
+ item.server,
+ setTimeout(() => {
+ reloads.delete(item.server)
+
+ if (disposed || !isCurrent(item) || item.ctx.sdk.connection.status() !== "connected") return
+
+ dispatch(item, { type: "reload", attempt: ++attempt })
+ }, RECENT_RELOAD_DELAY_MS),
+ )
+ }
+
const abortPages = (server: string) => {
controllers.forEach((owner, controller) => {
if (owner === server) controller.abort()
@@ -197,6 +223,7 @@ export function RecentSessions() {
abortPages(server)
abortHydration(server)
clearTimer(server)
+ cancelReload(server)
setPages(produce((current) => void delete current[server]))
clearHydration(server)
}
@@ -245,7 +272,7 @@ export function RecentSessions() {
if (page?.status !== "loading" || page.attempt !== effect.attempt) return
batch(() => {
- if (page.kind === "refresh") {
+ if (page.kind === "refresh" || page.kind === "reload") {
const covered = new Map(response.data.map((info) => [info.id, info]))
for (const key of state.pins) {
@@ -255,7 +282,8 @@ export function RecentSessions() {
const info = covered.get(pin.sessionID)
if (info) rememberPin(item, key, info)
- else hydrate(item, key, pin.sessionID)
+ // Live events keep other pins current while connected; only a reconnect may have missed some.
+ else if (page.kind === "refresh") hydrate(item, key, pin.sessionID)
}
}
@@ -289,6 +317,9 @@ export function RecentSessions() {
}
function load(item: Connection, kind: "first" | "next" | "refresh") {
+ // A first page or reconnect refresh is already a fresh snapshot, so a pending reload would only repeat it.
+ if (kind !== "next") cancelReload(item.server)
+
dispatch(item, { type: "load", kind, attempt: ++attempt })
}
@@ -297,6 +328,20 @@ export function RecentSessions() {
controllers.forEach((_, controller) => controller.abort())
hydrationControllers.forEach((controller) => controller.abort())
timers.forEach((timer) => clearTimeout(timer))
+ reloads.forEach((timer) => clearTimeout(timer))
+ })
+
+ const reloadAll = () => connections().forEach(reload)
+
+ const onVisible = () => {
+ if (document.visibilityState === "visible") reloadAll()
+ }
+
+ window.addEventListener("focus", reloadAll)
+ document.addEventListener("visibilitychange", onVisible)
+ onCleanup(() => {
+ window.removeEventListener("focus", reloadAll)
+ document.removeEventListener("visibilitychange", onVisible)
})
// The store is local and long-lived; drop duplicates a previous version or a manual edit left behind.
@@ -324,7 +369,11 @@ export function RecentSessions() {
// A replaced controller owns no old requests or pin snapshots, even before it reconnects.
if (replaced) dropServer(item.server)
- if (status !== "connected") return
+ if (status !== "connected") {
+ cancelReload(item.server)
+
+ return
+ }
if (!untrack(() => pages[item.server])) {
load(item, "first")
@@ -351,11 +400,8 @@ export function RecentSessions() {
connections().flatMap((item) => {
const fetched = pages[item.server]
- return mergeRecentSessions(
- item.server,
- fetched?.sessions ?? [],
- item.ctx.data.session.known(),
- item.ctx.data.session.apply,
+ return mergeRecentSessions(item.server, fetched?.sessions ?? [], item.ctx.data.session.known(), (rows) =>
+ item.ctx.data.session.apply(rows, { reloads: true }),
)
}),
)
@@ -373,7 +419,7 @@ export function RecentSessions() {
if (!value) return
- const session = item.ctx.data.session.apply([value])[0]
+ const session = item.ctx.data.session.apply([value], { reloads: true })[0]
if (session) result.set(key, { key, server: item.server, session })
})
@@ -427,6 +473,16 @@ export function RecentSessions() {
})
})
+ createEffect(() => {
+ connections().forEach((item) => {
+ onCleanup(
+ item.ctx.data.listen(({ details }) => {
+ if (recentReloadsOn(details, item.ctx.data.session.get)) reload(item)
+ }),
+ )
+ })
+ })
+
// A hydrated pin has no live entry, so archive events must reach its snapshot or Pinned keeps showing it.
createEffect(() => {
connections().forEach((item) => {
@@ -520,13 +576,7 @@ export function RecentSessions() {
})
})
- const loadingMore = createMemo(() =>
- connections().some((item) => {
- const value = pages[item.server]
-
- return value?.status === "loading" && value.kind !== "first" && value.sessions.length > 0
- }),
- )
+ const loadingMore = createMemo(() => connections().some((item) => recentPageLoadingMore(pages[item.server])))
const failed = createMemo(() => connections().some((item) => recentPageFailed(pages[item.server])))
@@ -700,7 +750,12 @@ export function RecentSessions() {
if (state.pins.includes(item.key)) {
setHydration(item.key, {
...item.session,
- time: { ...item.session.time, archived: item.session.time.archived ?? Date.now() },
+ // The row's time may be a send bump; the snapshot goes back through `apply` and must stay raw.
+ time: {
+ ...item.session.time,
+ updated: rawTime(item.session),
+ archived: item.session.time.archived ?? Date.now(),
+ },
})
}
diff --git a/packages/app/src/shell/titlebar/sidebar-sessions.ts b/packages/app/src/shell/titlebar/sidebar-sessions.ts
index 68be31b2f43a..a21842fc3a3e 100644
--- a/packages/app/src/shell/titlebar/sidebar-sessions.ts
+++ b/packages/app/src/shell/titlebar/sidebar-sessions.ts
@@ -25,5 +25,5 @@ export function isSidebarSessionActivity(
// Loading a tab refreshes its metadata, not its place in the project list. A newer idle marker means a run ended
// after the index was fetched, which is the one server change that may move the session. Recency overrides are
-// applied afterward by the shared desktop data layer, which also owns send promotion and the rename guard.
+// applied afterward by the shared desktop data layer, which owns send promotion.
export const mergeSidebarSessions = mergeHomeSessionIndex
From 6cca5988638c25cc880cd1b11e448033a746cab1 Mon Sep 17 00:00:00 2001
From: James Long
Date: Thu, 12 Nov 2026 12:51:17 -0600
Subject: [PATCH 07/42] fix(session-ui): keep links whose label contains inline
code (#63587)
---
.../component-tests/markdown.spec.ts | 96 +++++++++++++++++++
.../session-ui/src/components/markdown.css | 13 ++-
.../session-ui/src/components/markdown.tsx | 19 +---
3 files changed, 108 insertions(+), 20 deletions(-)
diff --git a/packages/session-ui/component-tests/markdown.spec.ts b/packages/session-ui/component-tests/markdown.spec.ts
index 36048887453e..528ca8299250 100644
--- a/packages/session-ui/component-tests/markdown.spec.ts
+++ b/packages/session-ui/component-tests/markdown.spec.ts
@@ -330,6 +330,102 @@ story("shows a stable GitHub mark without changing link text or other sites", as
}
})
+for (const mode of ["cached", "streamed"] as const) {
+ story(`keeps the whole label of a link that contains inline code (${mode})`, async ({ page }) => {
+ await page.evaluate(
+ async ({ fixture, mode }) => {
+ const { mountMarkdown } = await import(fixture)
+ await mountMarkdown({
+ text: [
+ "Console [removes `providerCost` from managed standard and Go events](https://github.com/anomalyco/opencode/pull/1) **before** [writing them to the log queue](https://github.com/anomalyco/opencode/pull/2).",
+ "[`providerCost`](https://github.com/anomalyco/opencode/pull/3) and [`https://example.com/code`](https://example.com/target)",
+ ].join("\n\n"),
+ cached: mode === "cached",
+ streaming: mode === "streamed",
+ })
+ },
+ { fixture, mode },
+ )
+
+ const harness = page.getByTestId("markdown-fixture")
+ const markdown = harness.locator('[data-component="markdown"]')
+
+ if (mode === "streamed") await harness.getByLabel("Streaming").uncheck()
+ await expect(markdown).toHaveAttribute("data-markdown-ready", "")
+
+ const mixed = markdown.getByRole("link", { name: "removes providerCost from managed standard and Go events" })
+ await expect(mixed).toHaveAttribute("href", "https://github.com/anomalyco/opencode/pull/1")
+ await expect(mixed.locator("code")).toHaveText("providerCost")
+ await expect(mixed.locator(".markdown-link-favicon[data-github]")).toHaveCount(1)
+ await expect(markdown.getByRole("link", { name: "writing them to the log queue" })).toHaveAttribute(
+ "href",
+ "https://github.com/anomalyco/opencode/pull/2",
+ )
+ await expect(markdown.locator("p").first()).toHaveText(
+ "Console removes providerCost from managed standard and Go events before writing them to the log queue.",
+ )
+
+ const code = markdown.getByRole("link", { name: "providerCost", exact: true })
+ await expect(code).toHaveAttribute("href", "https://github.com/anomalyco/opencode/pull/3")
+ await expect(code.locator("code")).toHaveText("providerCost")
+ await expect(markdown.getByRole("link", { name: "https://example.com/code" })).toHaveAttribute(
+ "href",
+ "https://example.com/target",
+ )
+ })
+}
+
+for (const theme of ["light", "dark"]) {
+ story(`styles inline code inside a link like the link label in ${theme}`, async ({ mount, page }) => {
+ await mount("components-markdown--complete-response", { globals: { theme } })
+ await expect(page.locator("html")).toHaveClass(new RegExp(theme))
+ await page.evaluate(async (fixture) => {
+ const { mountMarkdown } = await import(fixture)
+ await mountMarkdown({
+ text: "[removes `providerCost` from events](https://github.com/anomalyco/opencode/pull/1) and `plainCode`",
+ cached: true,
+ })
+ }, fixture)
+
+ const markdown = page.getByTestId("markdown-fixture").locator('[data-component="markdown"]')
+ await expect(markdown).toHaveAttribute("data-markdown-ready", "")
+ const link = markdown.getByRole("link", { name: "removes providerCost from events" })
+ const code = link.locator("code")
+
+ const style = () =>
+ code.evaluate((code) => {
+ const style = getComputedStyle(code)
+
+ return {
+ color: style.color,
+ background: style.backgroundColor,
+ padding: style.padding,
+ font: style.fontFamily,
+ }
+ })
+
+ const plain = await markdown.locator("code", { hasText: "plainCode" }).evaluate((code) => {
+ const style = getComputedStyle(code)
+
+ return { color: style.color, backgroundColor: style.backgroundColor, fontFamily: style.fontFamily }
+ })
+
+ expect(await style()).toEqual({
+ color: await resolvedColor(page, "--v2-text-text-accent"),
+ background: "rgba(0, 0, 0, 0)",
+ padding: "0px",
+ font: plain.fontFamily,
+ })
+ expect(plain.backgroundColor).not.toBe("rgba(0, 0, 0, 0)")
+ expect(plain.color).not.toBe(await resolvedColor(page, "--v2-text-text-accent"))
+
+ await link.hover()
+ await expect(link).toHaveCSS("text-decoration-line", "underline")
+ const hover = await resolvedColor(page, "--v2-text-text-accent-hover")
+ await expect.poll(async () => (await style()).color).toBe(hover)
+ })
+}
+
story("keeps favicon space stable across loading and failure without fetching private hosts", async ({ page }) => {
const requested: string[] = []
let release: () => void = () => undefined
diff --git a/packages/session-ui/src/components/markdown.css b/packages/session-ui/src/components/markdown.css
index 88d487c89898..2cf7d0971ffd 100644
--- a/packages/session-ui/src/components/markdown.css
+++ b/packages/session-ui/src/components/markdown.css
@@ -45,7 +45,6 @@
[data-component="markdown"] {
--markdown-inline-code-path-color: var(--v2-text-text-code-path);
- --markdown-inline-code-color: var(--v2-text-text-code-accent);
--markdown-inline-code-bg-mix: 8%;
--markdown-shell-code-background: var(--v2-background-bg-layer-02);
--markdown-shell-code-border: var(--v2-border-border-muted);
@@ -450,11 +449,17 @@
background-color 200ms ease-out;
}
- a.external-link > code[data-inline-code-kind="url"] {
- color: var(--markdown-inline-code-color);
+ /* Code inside a link reads as part of its label, so it takes the link's colour and hover. */
+ a code {
+ color: inherit;
+ padding: 0;
+ border-radius: 0;
background: none;
+ }
+
+ a.external-link > code[data-inline-code-kind="url"] {
text-decoration: underline;
- text-decoration-color: color-mix(in oklch, var(--markdown-inline-code-color) 25%, transparent);
+ text-decoration-color: color-mix(in oklch, currentColor 25%, transparent);
text-underline-offset: 2px;
}
diff --git a/packages/session-ui/src/components/markdown.tsx b/packages/session-ui/src/components/markdown.tsx
index c42df57f4bb7..099398d15e23 100644
--- a/packages/session-ui/src/components/markdown.tsx
+++ b/packages/session-ui/src/components/markdown.tsx
@@ -488,24 +488,11 @@ function markCodeLinks(root: HTMLDivElement) {
const codeNodes = Array.from(root.querySelectorAll(":not(pre) > code"))
for (const code of codeNodes) {
+ // Code inside a link already goes where the link does.
+ if (code.closest("a")) continue
const href = codeUrl(code.textContent ?? "")
- const parentLink =
- code.parentElement instanceof HTMLAnchorElement &&
- code.parentElement.classList.contains("external-link") &&
- !code.parentElement.hasAttribute("data-local-link")
- ? code.parentElement
- : null
-
- if (!href) {
- if (parentLink) parentLink.replaceWith(code)
- continue
- }
-
- if (parentLink) {
- parentLink.href = href
- continue
- }
+ if (!href) continue
const link = document.createElement("a")
link.href = href
From 8c809fb1f85b7cc5879006ccfefe1a7c7ad357aa Mon Sep 17 00:00:00 2001
From: "opencode-agent[bot]"
<219766164+opencode-agent[bot]@users.noreply.github.com>
Date: Thu, 12 Nov 2026 11:10:55 -0800
Subject: [PATCH 08/42] docs(console): add Gemini 4 Hydrogen to Zen (#63589)
Co-authored-by: opencode-agent[bot] <219766164+opencode-agent[bot]@users.noreply.github.com>
---
services/site/src/docs/content/console/models.mdx | 2 ++
1 file changed, 2 insertions(+)
diff --git a/services/site/src/docs/content/console/models.mdx b/services/site/src/docs/content/console/models.mdx
index 562150aec395..91cef660b630 100644
--- a/services/site/src/docs/content/console/models.mdx
+++ b/services/site/src/docs/content/console/models.mdx
@@ -79,6 +79,7 @@ translates. See [Base URLs](/console/harnesses#base-urls) for the full set.
| Claude Haiku 4.5 | claude-haiku-4-5 | `https://opencode.ai/inference/anthropic/v1/messages` | `@ai-sdk/anthropic` |
| Gemini 4 Carbon | gemini-4-carbon | `https://opencode.ai/inference/google/v1beta/models/gemini-4-carbon` | `@ai-sdk/google` |
| Gemini 4 Argon | gemini-4-argon | `https://opencode.ai/inference/google/v1beta/models/gemini-4-argon` | `@ai-sdk/google` |
+| Gemini 4 Hydrogen | gemini-4-hydrogen | `https://opencode.ai/inference/google/v1beta/models/gemini-4-hydrogen` | `@ai-sdk/google` |
| Gemini 3.8 Flash | gemini-3.8-flash | `https://opencode.ai/inference/google/v1beta/models/gemini-3.8-flash` | `@ai-sdk/google` |
| Gemini 3.7 Flash | gemini-3.7-flash | `https://opencode.ai/inference/google/v1beta/models/gemini-3.7-flash` | `@ai-sdk/google` |
| Gemini 3.6 Flash | gemini-3.6-flash | `https://opencode.ai/inference/google/v1beta/models/gemini-3.6-flash` | `@ai-sdk/google` |
@@ -287,6 +288,7 @@ Console uses pay-as-you-go pricing. Below are the prices **per 1M tokens**.
| Claude Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 |
| Gemini 4 Carbon (50% off) | ~~$4.00~~ $2.00 | ~~$20.00~~ $10.00 | ~~$0.20~~ $0.10 | - |
| Gemini 4 Argon (50% off) | ~~$4.00~~ $2.00 | ~~$20.00~~ $10.00 | ~~$0.20~~ $0.10 | - |
+| Gemini 4 Hydrogen | $1.50 | $7.50 | $0.075 | - |
| Gemini 3.8 Flash (50% off) | ~~$1.50~~ $0.75 | ~~$7.50~~ $3.75 | ~~$0.15~~ $0.075 | - |
| Gemini 3.7 Flash (50% off) | ~~$1.50~~ $0.75 | ~~$7.50~~ $3.75 | ~~$0.15~~ $0.075 | - |
| Gemini 3.6 Flash (50% off) | ~~$1.50~~ $0.75 | ~~$7.50~~ $3.75 | ~~$0.15~~ $0.075 | - |
From a1aa513f78c7e9c57ea6c1237de09b702e18f934 Mon Sep 17 00:00:00 2001
From: James Long
Date: Thu, 12 Nov 2026 13:23:00 -0600
Subject: [PATCH 09/42] fix(core): resume directly driven child sessions after
restart (#63415)
---
AGENTS.md | 2 +-
.../core/src/session/execution/restart.ts | 35 ++++--
packages/core/src/session/store.ts | 15 +--
packages/core/test/session-execution.test.ts | 107 ++++++++++++++++--
specs/v2/session.md | 4 +-
5 files changed, 130 insertions(+), 33 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index 15f27a31245d..7ce72dcb52c9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -216,7 +216,7 @@ const table = sqliteTable("session", {
- Keep `SessionExecution` process-global and Session-ID based. Its local implementation owns the process-local Session coordinator and discovers placement through `SessionStore` plus `LocationServiceMap.get(session.location)` only when a drain starts; no layer should take a Session ID. Interruption targets the active process-local ownership chain for that Session; interruption of a known but idle or locally unowned Session is a no-op, while the public API rejects an unknown Session.
- Keep `SessionRunner`, model resolution, tool registry, permissions, and filesystem Location-scoped. Omitted `Location.workspaceID` means implicit-local placement; explicit workspace identity remains reserved for future placement semantics.
- Each step is one explicit `llm.stream` call that continues from reloaded history. Do not add an in-memory tool loop.
-- Keep local Session drains process-local until clustering is implemented. `SessionRunCoordinator` joins explicit same-Session resumes, coalesces prompt wakeups, and allows different Sessions to run concurrently. A write-ahead execution claim marks a process-local busy period for restart recovery: terminal completion, failure, or user interruption releases it, while shutdown interruption and process death preserve it. Startup recovery resumes claimed top-level Sessions with durable per-execution attempt accounting. The claim is a recovery marker, not clustered ownership, fencing, or an exactly-once guarantee.
+- Keep local Session drains process-local until clustering is implemented. `SessionRunCoordinator` joins explicit same-Session resumes, coalesces prompt wakeups, and allows different Sessions to run concurrently. A write-ahead execution claim marks a process-local busy period for restart recovery: terminal completion, failure, or user interruption releases it, while shutdown interruption and process death preserve it. Startup recovery resumes claimed Sessions with durable per-execution attempt accounting. Running subagent Jobs own recovery of the children they represent. The claim is a recovery marker, not clustered ownership, fencing, or an exactly-once guarantee.
- Keep delivery vocabulary explicit. Prompts steer by default. At safe step boundaries, steered compaction takes priority up to the first steered move control; other steers retain enqueue order. At an idle boundary, steers take priority; otherwise exactly one queued item delivers before the runner reevaluates continuation. Inbox items may be cancelled or changed between queue and steer before delivery. Promoting new user input resets the selected agent's step allowance; a batch of steers resets it once.
- One step is one logical LLM call; its durable record covers only the model-visible span. Do not write "provider turn", and do not use bare "turn" for a single call: "turn" is reserved for the future assistant-turn unit containing all steps from prompt promotion until the session would go idle.
- Keep event replay ownership separate from clustered Session execution ownership.
diff --git a/packages/core/src/session/execution/restart.ts b/packages/core/src/session/execution/restart.ts
index af2f126443a9..541f22611c97 100644
--- a/packages/core/src/session/execution/restart.ts
+++ b/packages/core/src/session/execution/restart.ts
@@ -354,7 +354,7 @@ export const layer = (options?: Options) =>
})
return false
}
- // Defer the start until every suspended root has counted its attempt; a fast
+ // Defer the start until every suspended session has counted its attempt; a fast
// resumed child settling in Phase 1 would wake its parent past that budget.
return true
})
@@ -368,11 +368,23 @@ export const layer = (options?: Options) =>
resumeSuspendedSessions: Effect.gen(function* () {
const active = yield* execution.active
const pending = yield* jobs.pendingBackground
- const children = pending.flatMap((background) =>
- background.status === "running" && background.recovery.kind === "subagent"
- ? [background.recovery.childSessionID]
- : [],
+ const children = new Set(
+ pending.flatMap((background) =>
+ background.status === "running" && background.recovery.kind === "subagent"
+ ? [background.recovery.childSessionID]
+ : [],
+ ),
)
+ yield* store.releaseOrphanedChildClaims()
+ // Job.cancel persists the cancellation before interrupting the execution. A crash
+ // in between leaves its claim behind. Settlement writes a formatted error to the
+ // outbox atomically with release; such an older report can coexist with a new claim.
+ for (const { status, recovery, error } of pending) {
+ if (status !== "cancelled" || recovery.kind !== "subagent" || error !== undefined) continue
+ if (!active.has(recovery.childSessionID) && !children.has(recovery.childSessionID)) {
+ yield* store.release(recovery.childSessionID)
+ }
+ }
// Early notices wait for recovery's accounting, including Sessions that exhaust their budget.
const suspended = new Set(
[...(yield* store.listSuspended()), ...children].filter((sessionID) => !active.has(sessionID)),
@@ -386,7 +398,7 @@ export const layer = (options?: Options) =>
suspended.clear()
}),
)
- // Hold notice wakes until every suspended root has counted its attempt, so a woken
+ // Hold notice wakes until every suspended session has counted its attempt, so a woken
// child cannot settle mid-sweep and wake its parent past that budget.
const notices: Notices = {
synthetic: (input) =>
@@ -400,7 +412,6 @@ export const layer = (options?: Options) =>
Effect.uninterruptible,
),
}
- yield* store.releaseChildClaims(children)
const recoverable = Effect.fnUntraced(function* (background: Job.Background) {
return (yield* jobs.get(background.id))?.status !== "running"
})
@@ -438,12 +449,16 @@ export const layer = (options?: Options) =>
{ discard: true },
)
- // Count every suspended root's attempt before a resumed child can settle and wake it.
+ // A directly driven child can also settle and wake its parent. Account for every
+ // claimed execution before starting any of them, leaving running jobs to SubagentJob.
const resumed = yield* execution.active
+ const direct = yield* Effect.filter(
+ (yield* store.listSuspended()).filter((sessionID) => !resumed.has(sessionID) && !children.has(sessionID)),
+ prepareResume,
+ )
yield* Effect.forEach(
- (yield* store.listSuspended()).filter((sessionID) => !resumed.has(sessionID)),
+ direct,
Effect.fnUntraced(function* (sessionID) {
- if (!(yield* prepareResume(sessionID))) return
suspended.delete(sessionID)
yield* execution.resume(sessionID).pipe(Effect.ignore, Effect.forkIn(scope))
}),
diff --git a/packages/core/src/session/store.ts b/packages/core/src/session/store.ts
index d38f979112ce..94e13d2717df 100644
--- a/packages/core/src/session/store.ts
+++ b/packages/core/src/session/store.ts
@@ -75,8 +75,7 @@ export interface Interface {
messageID: SessionMessage.ID,
) => Effect.Effect<{ readonly sessionID: Session.ID; readonly message: SessionMessage.MediaInfo } | undefined>
/**
- * Top-level Sessions holding an execution claim. Recoverable background
- * children are resumed separately through their durable Job records.
+ * Sessions holding an execution claim, including directly driven children.
*/
readonly listSuspended: () => Effect.Effect>
/**
@@ -89,10 +88,9 @@ export interface Interface {
/** Releases the claim and resets resume accounting. Terminal events call this on commit. */
readonly release: (sessionID: Session.ID) => Effect.Effect
/**
- * Clears orphaned child claims except children owned by recoverable
- * background subagent jobs.
+ * Release abandoned claims when the child's parent was deleted.
*/
- readonly releaseChildClaims: (recoverable: ReadonlyArray) => Effect.Effect
+ readonly releaseOrphanedChildClaims: () => Effect.Effect
/**
* Durably counts one more resume of an orphaned claim, returning the new
* total โ or undefined when the Session no longer exists.
@@ -243,7 +241,7 @@ const layer = Layer.effect(
return yield* db
.select({ sessionID: SessionTable.id })
.from(SessionTable)
- .where(and(isNotNull(SessionTable.time_suspended), isNull(SessionTable.parent_id)))
+ .where(isNotNull(SessionTable.time_suspended))
.all()
.pipe(
Effect.orDie,
@@ -270,15 +268,14 @@ const layer = Layer.effect(
.run()
.pipe(Effect.orDie)
}),
- releaseChildClaims: Effect.fn("SessionStore.releaseChildClaims")((recoverable) =>
+ releaseOrphanedChildClaims: Effect.fn("SessionStore.releaseOrphanedChildClaims")(() =>
db
.update(SessionTable)
.set({ time_suspended: null, resume_attempts: 0, time_updated: sql`${SessionTable.time_updated}` })
.where(
and(
isNotNull(SessionTable.time_suspended),
- isNotNull(SessionTable.parent_id),
- recoverable.length > 0 ? notInArray(SessionTable.id, Array.from(recoverable)) : undefined,
+ notInArray(SessionTable.parent_id, db.select({ id: SessionTable.id }).from(SessionTable)),
),
)
.run()
diff --git a/packages/core/test/session-execution.test.ts b/packages/core/test/session-execution.test.ts
index f1787d1e6b11..710d42367d84 100644
--- a/packages/core/test/session-execution.test.ts
+++ b/packages/core/test/session-execution.test.ts
@@ -60,23 +60,63 @@ describe("SessionExecution lifecycle", () => {
expect(SessionExecution.terminal(interrupted, "user")).toEqual({ type: "interrupted", reason: "user" })
})
- it.effect("the sweep only lists claimed top-level Sessions", () =>
+ it.effect("resumes a directly driven child after execution teardown", () =>
Effect.gen(function* () {
const database = yield* Database.Service
const store = yield* SessionStore.Service
const parent = Session.ID.make("ses_recover_parent")
const child = Session.ID.make("ses_recover_child")
const idle = Session.ID.make("ses_recover_idle")
- yield* seedSessions(database, [parent], { time_suspended: Date.now() })
- yield* seedSessions(database, [idle])
- // Children recover through background Job records, never through the root claim sweep.
- yield* seedSessions(database, [child], { time_suspended: Date.now(), parent_id: parent })
+ yield* seedSessions(database, [parent])
+ yield* seedSessions(database, [child, idle], { parent_id: parent })
+ const scope = yield* Scope.fork(yield* Effect.scope)
+ const running = yield* Deferred.make()
+ const before = yield* buildExecution(scope, () =>
+ Deferred.succeed(running, undefined).pipe(Effect.andThen(Effect.never)),
+ )
+ yield* Context.get(before, SessionExecution.Service).resume(child).pipe(Effect.forkIn(scope))
+ yield* Deferred.await(running)
+ yield* Scope.close(scope, Exit.void)
+ expect((yield* claims(database))[child]).toBe(true)
- expect(yield* store.listSuspended()).toEqual([parent])
+ const drained: Session.ID[] = []
+ const resumed = yield* Deferred.make()
+ const after = yield* buildExecution(yield* Scope.fork(yield* Effect.scope), ({ sessionID }) =>
+ Effect.sync(() => void drained.push(sessionID)).pipe(Effect.andThen(Deferred.succeed(resumed, undefined))),
+ )
+ const restart = Context.get(after, SessionRestart.Service)
+ yield* restart.resumeSuspendedSessions
+ expect((yield* store.context(child)).filter((message) => message.type === "synthetic")).toMatchObject([
+ { metadata: { notice: "restart" } },
+ ])
+ yield* Deferred.await(resumed)
+ yield* Context.get(after, SessionExecution.Service).awaitIdle(child)
+ yield* restart.resumeSuspendedSessions
+ expect(drained).toEqual([child])
+ expect(yield* claims(database)).toEqual({ [parent]: false, [child]: false, [idle]: false })
+ }),
+ )
- // The sweep clears orphaned child claims outright; parents keep theirs.
- yield* store.releaseChildClaims([])
- expect(yield* claims(database)).toEqual({ [parent]: true, [child]: false, [idle]: false })
+ it.effect("leaves a child parked when its parent is gone or its restart budget is exhausted", () =>
+ Effect.gen(function* () {
+ const database = yield* Database.Service
+ const parent = Session.ID.make("ses_child_budget_parent")
+ const exhausted = Session.ID.make("ses_child_budget_exhausted")
+ const orphan = Session.ID.make("ses_child_budget_orphan")
+ yield* seedSessions(database, [parent])
+ yield* seedSessions(database, [exhausted], { parent_id: parent, time_suspended: Date.now(), resume_attempts: 2 })
+ yield* seedSessions(database, [orphan], { parent_id: Session.ID.make("ses_deleted"), time_suspended: Date.now() })
+ const drained: Session.ID[] = []
+ const context = yield* buildExecution(
+ yield* Scope.fork(yield* Effect.scope),
+ ({ sessionID }) => Effect.sync(() => void drained.push(sessionID)),
+ { maxAttempts: 2 },
+ )
+ yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions
+ yield* Effect.forEach([exhausted, orphan], Context.get(context, SessionExecution.Service).awaitIdle)
+ expect(drained).toEqual([])
+ expect(yield* claims(database)).toEqual({ [parent]: false, [exhausted]: false, [orphan]: false })
+ expect(yield* attempts(database, exhausted)).toBe(0)
}),
)
@@ -279,6 +319,50 @@ describe("SessionExecution lifecycle", () => {
}),
)
+ it.effect("honors a job cancellation persisted before its child could release the claim", () =>
+ Effect.gen(function* () {
+ const database = yield* Database.Service
+ const jobs = yield* Job.Service
+ const parent = Session.ID.make("ses_cancel_parent")
+ const child = Session.ID.make("ses_cancel_child")
+ yield* seedSessions(database, [parent])
+ yield* seedSessions(database, [child], { parent_id: parent, time_suspended: Date.now(), resume_attempts: 1 })
+ yield* jobs.start({
+ id: child,
+ type: "subagent",
+ recovery: {
+ kind: "subagent",
+ childSessionID: child,
+ parentSessionID: parent,
+ agent: "general",
+ description: "Inspect",
+ },
+ background: true,
+ run: Effect.never,
+ })
+ yield* jobs.cancel(child)
+ const scope = yield* Scope.fork(yield* Effect.scope)
+ const restarted = yield* Job.make.pipe(Scope.provide(scope))
+ const drained: Session.ID[] = []
+ const context = yield* buildExecution(
+ scope,
+ ({ sessionID }) => Effect.sync(() => void drained.push(sessionID)),
+ undefined,
+ restarted,
+ )
+ const restart = Context.get(context, SessionRestart.Service)
+ yield* restart.resumeSuspendedSessions
+ yield* Context.get(context, SessionExecution.Service).awaitIdle(parent)
+ yield* restart.resumeSuspendedSessions
+ expect(drained).toEqual([parent])
+ expect(yield* SessionInbox.list(database.db, parent)).toMatchObject([
+ { payload: { metadata: { state: "cancelled" } } },
+ ])
+ expect((yield* claims(database))[child]).toBe(false)
+ expect(yield* attempts(database, child)).toBe(0)
+ }),
+ )
+
it.effect("starts every claimed execution without waiting for earlier drains to finish", () =>
Effect.gen(function* () {
const database = yield* Database.Service
@@ -448,7 +532,7 @@ describe("SessionRestart background recovery", () => {
const parent = Session.ID.make("ses_background_recovery_parent")
const child = Session.ID.make("ses_background_recovery_child")
yield* seedSessions(database, [parent])
- yield* seedSessions(database, [child], { parent_id: parent, time_suspended: Date.now() })
+ yield* seedSessions(database, [child], { parent_id: parent })
yield* seedBackground(jobs, parent, [
{ id: "sh_background_orphan", shellID: "sh_background_orphan", command: "sleep 60" },
])
@@ -1243,7 +1327,8 @@ describe("SessionRestart background recovery", () => {
const child = Session.ID.make("ses_subagent_recovery_child")
const unrelated = Session.ID.make("ses_subagent_unrelated_child")
yield* seedSessions(database, [parent], { time_suspended: Date.now(), resume_attempts: 1 })
- yield* seedSessions(database, [child, unrelated], { parent_id: parent, time_suspended: Date.now() })
+ yield* seedSessions(database, [child], { parent_id: parent, time_suspended: Date.now() })
+ yield* seedSessions(database, [unrelated], { parent_id: parent })
yield* jobs.start({
id: child,
type: "subagent",
diff --git a/specs/v2/session.md b/specs/v2/session.md
index 8a320616f4b0..631f1e49f14e 100644
--- a/specs/v2/session.md
+++ b/specs/v2/session.md
@@ -65,7 +65,7 @@ The public interrupt operation verifies that the durable Session exists. An unkn
`sessions.active()` snapshots busy periods currently owned by this process. Durable execution events and claims are historical and recovery records, not proof that this process is still live.
-Execution commits a write-ahead claim when a process-local busy period starts. Success, failure, and user interruption release the claim; shutdown interruption and unclean process death preserve it. On startup, managed Node and fetch runtimes resume claimed top-level Sessions, append a durable continuation instruction, and count recovery attempts. Recovery is bounded per claimed execution but does not guarantee exactly-once provider requests or tool effects.
+Execution commits a write-ahead claim when a process-local busy period starts. Success, failure, and user interruption release the claim; shutdown interruption and unclean process death preserve it. On startup, managed Node and fetch runtimes resume claimed Sessions, append a durable continuation instruction, and count recovery attempts. A running subagent Job owns its child's recovery; a directly driven child resumes through its own claim. Recovery is bounded per claimed execution but does not guarantee exactly-once provider requests or tool effects.
## One Step May Have Several Physical Attempts
@@ -113,6 +113,6 @@ There is no separate finite Session-history endpoint. Request/response consumers
## Recovery Boundaries Stay Explicit
-An advisory wake is not itself crash recovery. Crash recovery is driven by a write-ahead execution claim that survives without a releasing terminal. Startup recovery resumes claimed top-level Sessions from durable projected history with bounded attempt accounting. It fails stale running tool projections before continuing, but it cannot prove whether an interrupted external operation already took effect and does not guarantee exactly-once provider or tool behavior.
+An advisory wake is not itself crash recovery. Crash recovery is driven by a write-ahead execution claim that survives without a releasing terminal. Startup recovery resumes claimed Sessions from durable projected history with bounded attempt accounting. It fails stale running tool projections before continuing, but it cannot prove whether an interrupted external operation already took effect and does not guarantee exactly-once provider or tool behavior.
Event replay ownership is separate from Session execution ownership. Local execution remains process-owned until clustering introduces an explicit placement and fencing protocol.
From ebf6e00ad3e231c5d8bdb6b233fdca2a5dbfd953 Mon Sep 17 00:00:00 2001
From: Adam <2363879+adamdotdevin@users.noreply.github.com>
Date: Thu, 12 Nov 2026 13:49:08 -0600
Subject: [PATCH 10/42] docs(console): document Send identity on custom
providers (#63596)
---
.../src/docs/content/console/providers.mdx | 87 +++++++++++++++++++
1 file changed, 87 insertions(+)
diff --git a/services/site/src/docs/content/console/providers.mdx b/services/site/src/docs/content/console/providers.mdx
index ca0e4004aad5..7472a68487fa 100644
--- a/services/site/src/docs/content/console/providers.mdx
+++ b/services/site/src/docs/content/console/providers.mdx
@@ -106,6 +106,93 @@ Acme Inc. / Anthropic
Turn on **Managed providers only** in **Settings โบ General** to restrict OpenCode to the workspace's providers for
everyone.
+## Send identity
+
+When a provider is a gateway you run, turn on **Send identity** on its page. Console then adds an `x-opencode-actor`
+header to every model request it sends there. The header names the member or service account behind the request, so
+your gateway can log or restrict requests by sender.
+
+```text
+x-opencode-actor: eyJhbGciOiJFUzI1NiIsInR5cCI6Im9wZW5jb2RlLWFjdG9yK2p3dCIsImtpZCI6Ii4uLiJ9...
+```
+
+- It's off by default, and changing the base URL turns it off.
+- A provider still at its vendor's own API, such as `https://api.openai.com/v1`, doesn't show the setting, since the
+ vendor ignores the header.
+- Console removes any `x-opencode-*` header a client sends, so the only `x-opencode-actor` your gateway receives is the
+ one Console signed.
+- **Test connection** and model listing call `GET /models` with the credential alone, so don't require the
+ header on that route.
+
+### Token
+
+The header is a JWT that Console signs for each request.
+
+| Field | Value |
+| ------------ | ------------------------------------------------ |
+| `alg` | `ES256` |
+| `typ` | `opencode-actor+jwt` |
+| `iss` | `https://opencode.ai/inference` |
+| `aud` | The provider's base URL without trailing slashes |
+| `iat`, `exp` | `exp` is 120 seconds after `iat` |
+
+| Claim | Value |
+| -------------------- | ---------------------------------------------------------------------- |
+| `sub` | `user_id` for a member, `service_account_id` otherwise |
+| `workspace_id` | The workspace the request ran in |
+| `user_id`, `email` | The member, when a member sent the request |
+| `service_account_id` | The service account, when a service account sent it (agents included) |
+| `session_id` | The client's session ID, when it sent one |
+| `request_id` | The ID the client gets back in the `x-opencode-log-id` response header |
+
+A member's request carries a payload like this:
+
+```json
+{
+ "iss": "https://opencode.ai/inference",
+ "aud": "https://llm.example.com/v1",
+ "sub": "user_...",
+ "workspace_id": "org_...",
+ "user_id": "user_...",
+ "email": "ada@example.com",
+ "session_id": "ses_...",
+ "request_id": "019a6e8f-24a0-7b12-9c3d-4e5f6a7b8c9d",
+ "iat": 1794500000,
+ "exp": 1794500120
+}
+```
+
+### Verify the token
+
+Console publishes its public keys at `https://opencode.ai/inference/.well-known/jwks.json`, served with
+`Cache-Control: public, max-age=300`. Check the signature, issuer, audience, type and age, then the workspace. This
+example uses [jose](https://github.com/panva/jose).
+
+```ts
+import { createRemoteJWKSet, jwtVerify } from "jose"
+
+const keys = createRemoteJWKSet(new URL("https://opencode.ai/inference/.well-known/jwks.json"))
+
+export async function sender(request: Request) {
+ const token = request.headers.get("x-opencode-actor")
+ if (!token) throw new Error("Missing x-opencode-actor")
+ const { payload } = await jwtVerify(token, keys, {
+ issuer: "https://opencode.ai/inference",
+ audience: "https://llm.example.com/v1",
+ algorithms: ["ES256"],
+ typ: "opencode-actor+jwt",
+ maxTokenAge: "120s",
+ clockTolerance: "5s",
+ })
+ if (payload.workspace_id !== "org_...") throw new Error("Another workspace")
+ return payload
+}
+```
+
+Set `audience` to the provider's base URL as saved in Console, without trailing slashes, and replace `org_...` with the
+workspace ID from your Console URL. Console publishes a new signing key before it signs with it, so a verifier that
+looks keys up by `kid`, as `createRemoteJWKSet` does, keeps working through a rotation.
+
## Disable or remove
Open the provider's **โฏ** menu:
From 892176957717ec08251be8e0c06562a08222205d Mon Sep 17 00:00:00 2001
From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com>
Date: Thu, 12 Nov 2026 13:56:50 -0600
Subject: [PATCH 11/42] fix(core): drop stale thinking when Claude Agent
prompts or tools change (#63592)
---
.../src/plugin/provider/claude-agent/claude/query-options.ts | 3 +++
specs/v2/claude-agent-provider.md | 1 +
2 files changed, 4 insertions(+)
diff --git a/packages/core/src/plugin/provider/claude-agent/claude/query-options.ts b/packages/core/src/plugin/provider/claude-agent/claude/query-options.ts
index b273ee92043d..23cacceec26f 100644
--- a/packages/core/src/plugin/provider/claude-agent/claude/query-options.ts
+++ b/packages/core/src/plugin/provider/claude-agent/claude/query-options.ts
@@ -19,6 +19,9 @@ const ISOLATION_ENV = {
CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK: "1",
// Raised so opencode's own truncation applies instead
MAX_MCP_OUTPUT_TOKENS: "200000",
+ // OpenCode changes the system prompt and tools mid-session (agent switches, instruction edits). Without this,
+ // Claude Code replays thinking bound to the old prompt and the API rejects the request.
+ CLAUDE_CODE_POLISHED_DEWDROP: "drop",
// Skips OAuth, so the subscription would not be used
CLAUDE_CODE_SIMPLE: undefined,
// A shell-level effort override would take precedence over OpenCode's live effort settings.
diff --git a/specs/v2/claude-agent-provider.md b/specs/v2/claude-agent-provider.md
index f71aa3b00679..cecb073e18af 100644
--- a/specs/v2/claude-agent-provider.md
+++ b/specs/v2/claude-agent-provider.md
@@ -67,6 +67,7 @@ We also clear three variables a user might have set in their shell. `CLAUDE_CODE
- Before the call: gives us Claude's ID for the call. Our tool handler can't see this ID, and opencode needs it to send back the right result. Because we only remember one ID at a time, tools must run one at a time, so we never mark them as safe to run in parallel.
- After the call: adds PDFs and linked images from opencode's result, which a normal MCP tool result can't carry.
- Thinking with summaries, so opencode has reasoning text to show
+- Dropping earlier thinking when the system prompt or tools change mid-session (`CLAUDE_CODE_POLISHED_DEWDROP=drop`). Without it the API rejects the next request, because each thinking block is tied to the prompt and tools it was made with.
- Messages sent exactly as given. opencode already expands `/commands` and adds `@file` contents before sending, so Claude Code does not process them again. It also skips the context Claude Code normally adds at the start of each turn, such as nested CLAUDE.md files, skill lists and reminders. This needs Claude Code 2.1.248 or later.
- A higher limit on tool output, so opencode's own truncation applies instead
- Saved Claude sessions for chats, but not for side calls such as titles
From a3d6e54b3dff0975d01a7307464ef7be9fa6b1ee Mon Sep 17 00:00:00 2001
From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com>
Date: Thu, 12 Nov 2026 14:30:06 -0600
Subject: [PATCH 12/42] fix(codemode): decode UTF-8 across chunk boundaries
(#63600)
---
packages/codemode/interpreter-support.md | 5 +-
packages/codemode/src/snapshot/codec.ts | 8 ++-
packages/codemode/src/stdlib/bytes.ts | 81 +++++++++++++++++++++---
packages/codemode/test/snapshot.test.ts | 8 +++
packages/codemode/test/stdlib.test.ts | 80 +++++++++++++++++++++++
5 files changed, 169 insertions(+), 13 deletions(-)
diff --git a/packages/codemode/interpreter-support.md b/packages/codemode/interpreter-support.md
index 52ad4dc9c1ed..099d615ff521 100644
--- a/packages/codemode/interpreter-support.md
+++ b/packages/codemode/interpreter-support.md
@@ -596,14 +596,15 @@ with a hint to encode as text first (`TextDecoder`, `toBase64`, `toHex`).
frozen. Functions, symbols, promises, iterators, URL, Headers, and tool references cannot be cloned; without a
`DOMException`, the failure is a `TypeError` whose message starts with `DataCloneError:`.
- [x] `TextEncoder` and `TextDecoder` for UTF-8 only: any other label is a `RangeError`. `TextDecoder` accepts the
- `fatal` and `ignoreBOM` options; `decode` takes a Uint8Array or nothing.
+ `fatal` and `ignoreBOM` options. `decode(chunk, { stream: true })` accepts incremental Uint8Array input;
+ `decode()` flushes the stream.
- [x] `new Headers()` from records, synchronous iterables of pairs, and Headers, wrapping the host's `Headers`: names
fold to lowercase, values are normalized and combined, and invalid names or values throw a `TypeError`.
- [x] Headers `append`, `delete`, `get`, `getSetCookie`, `has`, `set`, `forEach`, `keys`, `values`, `entries`, and
`[Symbol.iterator]`; iteration is live and sorted by name, with `set-cookie` values kept apart.
- [x] Headers serialize to a `{ name: value }` object in JSON, in results, and in tool arguments.
- [ ] `Request`, `Response`, and `Blob`.
-- [ ] `crypto.subtle` and `TextDecoder` streaming or non-UTF-8 encodings.
+- [ ] `crypto.subtle` and non-UTF-8 `TextDecoder` encodings.
## Extensions
diff --git a/packages/codemode/src/snapshot/codec.ts b/packages/codemode/src/snapshot/codec.ts
index 4345a199dfa9..2f998e5da20d 100644
--- a/packages/codemode/src/snapshot/codec.ts
+++ b/packages/codemode/src/snapshot/codec.ts
@@ -225,7 +225,13 @@ const builtinSpecs = (): ReadonlyArray => [
{ name: "HeadersObj", ctor: HeadersObj, fields: ["headers"], obj: true, constants: { tag: "Headers" } },
{ name: "URLObj", ctor: URLObj, fields: ["searchParams", "url"], obj: true, constants: { tag: "URL" } },
{ name: "Bytes", ctor: Bytes, fields: ["bytes"], obj: true, constants: { tag: "Uint8Array" } },
- { name: "TextDecoderObj", ctor: TextDecoderObj, fields: ["decoder"], obj: true, constants: { tag: "Object" } },
+ {
+ name: "TextDecoderObj",
+ ctor: TextDecoderObj,
+ fields: ["decoder", "ignoreBOM", "queued", "seen"],
+ obj: true,
+ constants: { tag: "Object" },
+ },
{
name: "AsyncFromSyncIterator",
ctor: AsyncFromSyncIterator,
diff --git a/packages/codemode/src/stdlib/bytes.ts b/packages/codemode/src/stdlib/bytes.ts
index 815074471c41..c7b55b3415cb 100644
--- a/packages/codemode/src/stdlib/bytes.ts
+++ b/packages/codemode/src/stdlib/bytes.ts
@@ -196,14 +196,74 @@ export const textEncoderGlobal = (ctx: Interpreter) => {
})
}
-/** A `TextDecoder` holding the host decoder its label and options configured. */
+// Replacement mode only needs to identify an incomplete suffix (at most three bytes).
+// Fatal mode also needs the queue position after the first error, which the host doesn't expose.
+const streamBoundary = (bytes: Uint8Array, fatal: boolean) => {
+ let next = fatal ? 0 : Math.max(0, bytes.length - 3)
+ while (next < bytes.length) {
+ const start = next
+ const lead = bytes[next++]!
+ if (lead < 0x80) continue
+ if (lead < 0xc2 || lead > 0xf4) {
+ if (fatal) return { end: next, error: true }
+ continue
+ }
+ const width = lead < 0xe0 ? 2 : lead < 0xf0 ? 3 : 4
+ let lower = lead === 0xe0 ? 0xa0 : lead === 0xf0 ? 0x90 : 0x80
+ let upper = lead === 0xed ? 0x9f : lead === 0xf4 ? 0x8f : 0xbf
+ while (next < start + width) {
+ if (next === bytes.length) return { end: start, error: false }
+ const byte = bytes[next]!
+ // A bad continuation is reprocessed as a leading byte, even after a fatal error.
+ if (byte < lower || byte > upper) {
+ if (fatal) return { end: next, error: true }
+ break
+ }
+ next++
+ lower = 0x80
+ upper = 0xbf
+ }
+ }
+ return { end: next, error: false }
+}
+
+const empty = new Uint8Array()
+
export class TextDecoderObj extends Obj {
+ queued: Uint8Array = empty
+ seen = false
+
constructor(
proto: Obj,
readonly decoder: TextDecoder,
+ readonly ignoreBOM: boolean,
) {
super(proto)
}
+
+ decode(bytes: Uint8Array, stream: boolean) {
+ if (this.queued.length && bytes.length) {
+ checkArrayLength(this.queued.length + bytes.length)
+ const joined = new Uint8Array(this.queued.length + bytes.length)
+ joined.set(this.queued)
+ joined.set(bytes, this.queued.length)
+ bytes = joined
+ }
+ if (!bytes.length) bytes = this.queued
+ const { end, error } = stream ? streamBoundary(bytes, this.decoder.fatal) : { end: bytes.length, error: false }
+ this.queued = end < bytes.length ? bytes.slice(end) : empty
+ if (error) throw typeError("TextDecoder.decode: the input is not valid utf-8.")
+ const stripBOM = !this.ignoreBOM && !this.seen
+ if (!stream) this.seen = false
+ try {
+ // Keep the host decoder stateless: snapshots own the pending bytes and BOM decision.
+ const text = this.decoder.decode(end === bytes.length ? bytes : bytes.subarray(0, end))
+ if (stream && text.length) this.seen = true
+ return stripBOM && text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
+ } catch {
+ throw typeError("TextDecoder.decode: the input is not valid utf-8.")
+ }
+ }
}
// The WHATWG labels for UTF-8, the only encoding CodeMode decodes.
@@ -215,22 +275,22 @@ export const textDecoderGlobal = (ctx: Interpreter) => {
const self = (thisValue: Value, name: string) => receiver(TextDecoderObj, thisValue, `TextDecoder.prototype.${name}`)
defineAccessor(proto, "encoding", (thisValue) => self(thisValue, "encoding").decoder.encoding)
defineAccessor(proto, "fatal", (thisValue) => self(thisValue, "fatal").decoder.fatal)
- defineAccessor(proto, "ignoreBOM", (thisValue) => self(thisValue, "ignoreBOM").decoder.ignoreBOM)
+ defineAccessor(proto, "ignoreBOM", (thisValue) => self(thisValue, "ignoreBOM").ignoreBOM)
methods(builtins, proto, [
[
"decode",
0,
(thisValue, args) => {
- const decoder = self(thisValue, "decode").decoder
- if (args[0] === undefined) return ""
- if (!(args[0] instanceof Bytes)) {
+ const decoder = self(thisValue, "decode")
+ if (args[0] !== undefined && !(args[0] instanceof Bytes)) {
throw typeError(`TextDecoder.decode expects a Uint8Array, received ${describeValue(args[0])}.`)
}
- try {
- return decoder.decode(args[0].bytes)
- } catch {
- throw typeError(`TextDecoder.decode: the input is not valid ${decoder.encoding}.`)
+ const options = args[1]
+ if (options !== undefined && typeof options !== "object") {
+ throw typeError("TextDecoder.decode expects an options object.")
}
+ const stream = options instanceof Obj && Boolean(get(options, "stream"))
+ return decoder.decode(args[0]?.bytes ?? empty, stream)
},
],
])
@@ -244,7 +304,8 @@ export const textDecoderGlobal = (ctx: Interpreter) => {
const flag = (name: string) => options !== undefined && Boolean(get(options, name))
return new TextDecoderObj(
prototypeFrom(newTarget, proto),
- new TextDecoder("utf-8", { fatal: flag("fatal"), ignoreBOM: flag("ignoreBOM") }),
+ new TextDecoder("utf-8", { fatal: flag("fatal"), ignoreBOM: true }),
+ flag("ignoreBOM"),
)
},
})
diff --git a/packages/codemode/test/snapshot.test.ts b/packages/codemode/test/snapshot.test.ts
index 509b9f47e2d2..0587bdfa45ab 100644
--- a/packages/codemode/test/snapshot.test.ts
+++ b/packages/codemode/test/snapshot.test.ts
@@ -13,6 +13,14 @@ import { buildId } from "../src/snapshot.js"
// The VM's snapshots: a run saved and restored into a fresh runtime anywhere it slices goes on as if it never stopped.
const programs: Record = {
+ "a UTF-8 decoder with unread bytes after a fatal stream error": `
+ const decoder = new TextDecoder('utf8', { fatal: true })
+ try { decoder.decode(new Uint8Array([255, 65, 66, 67, 68]), { stream: true }) }
+ catch (error) { return [error.name, decoder.decode()] }`,
+ "a UTF-8 decoder with pending bytes and a consumed BOM": `
+ const decoder = new TextDecoder('utf8', { fatal: true })
+ const start = decoder.decode(new Uint8Array([0xef, 0xbb, 0xbf, 0xef]), { stream: true })
+ return [start, decoder.decode(new Uint8Array([0xbb, 0xbf]))]`,
"closures over per-iteration bindings": `
const fns = []
for (let i = 0; i < 5; i++) fns.push(() => i * 2)
diff --git a/packages/codemode/test/stdlib.test.ts b/packages/codemode/test/stdlib.test.ts
index 9c0d01672cce..ef09e2d3303b 100644
--- a/packages/codemode/test/stdlib.test.ts
+++ b/packages/codemode/test/stdlib.test.ts
@@ -1218,6 +1218,86 @@ describe("TextEncoder and TextDecoder", () => {
])
})
+ test("streams an emoji one byte at a time and copies the pending bytes", async () => {
+ expect(
+ await value(`
+ const decoder = new TextDecoder()
+ const chunk = new Uint8Array([65, 0xf0])
+ const stream = { stream: true }
+ const start = decoder.decode(chunk, stream)
+ chunk[1] = 0
+ return [start, decoder.decode(undefined, stream), decoder.decode(new Uint8Array([0x9f]), stream),
+ decoder.decode(new Uint8Array([0x98]), stream), decoder.decode(new Uint8Array([0x80, 66])), decoder.decode()]
+ `),
+ ).toEqual(["A", "", "", "", "๐B", ""])
+ })
+
+ test("only strips the first BOM of each stream, including a split BOM", async () => {
+ expect(
+ await value(`
+ return [false, true].map(ignoreBOM => {
+ const decoder = new TextDecoder('utf8', { ignoreBOM })
+ const bom = new Uint8Array([0xef, 0xbb, 0xbf])
+ return [decoder.decode(bom.slice(0, 1), { stream: true }), decoder.decode(bom.slice(1), { stream: true }),
+ decoder.decode(bom), decoder.decode(bom)]
+ })
+ `),
+ ).toEqual([
+ ["", "", "\ufeff", ""],
+ ["", "\ufeff", "\ufeff", "\ufeff"],
+ ])
+ })
+
+ test("reports malformed UTF-8 immediately and truncated UTF-8 on flush", async () => {
+ expect(
+ await value(`
+ return [false, true].map(fatal => {
+ return [[[0xe0], [0x80]], [[0xed, 0xa0]], [[0xf0, 0x80]], [[0xf4, 0x90]],
+ [[0xe2, 0x82], [65]], [[0xf0, 0x9f], undefined, undefined, [0xef, 0xbb, 0xbf, 66]]].flatMap(chunks => {
+ const decoder = new TextDecoder('utf8', { fatal })
+ return chunks.map(bytes => {
+ try { return bytes ? decoder.decode(new Uint8Array(bytes), { stream: true }) : decoder.decode() }
+ catch (error) { return error.name }
+ })
+ })
+ })
+ `),
+ ).toEqual([
+ ["", "๏ฟฝ๏ฟฝ", "๏ฟฝ๏ฟฝ", "๏ฟฝ๏ฟฝ", "๏ฟฝ๏ฟฝ", "", "๏ฟฝA", "", "๏ฟฝ", "", "B"],
+ ["", "TypeError", "TypeError", "TypeError", "TypeError", "", "TypeError", "", "TypeError", "", "B"],
+ ])
+ })
+
+ test("keeps unread input in order after a fatal stream error", async () => {
+ expect(
+ await value(`
+ const decoder = new TextDecoder('utf8', { fatal: true })
+ const stream = { stream: true }
+ const fail = bytes => {
+ try { return decoder.decode(bytes, stream) } catch (error) { return error.name }
+ }
+ const chunk = new Uint8Array([0xff, 65])
+ const first = fail(chunk)
+ chunk[1] = 0
+ return [first, decoder.decode(), fail(new Uint8Array([0xe2, 0x82])),
+ fail(new Uint8Array([66, 67])), decoder.decode(new Uint8Array([68])), decoder.decode()]
+ `),
+ ).toEqual(["TypeError", "A", "", "TypeError", "BCD", ""])
+ })
+
+ test("rejects primitive options before touching the partial character", async () => {
+ expect(
+ await value(`
+ const decoder = new TextDecoder()
+ decoder.decode(new Uint8Array([0xc2]), { stream: true })
+ const errors = [true, false, 0, '', Symbol.iterator].map(options => {
+ try { return decoder.decode(undefined, options) } catch (error) { return error.name }
+ })
+ return [...errors, decoder.decode(new Uint8Array([0xa2]), null)]
+ `),
+ ).toEqual(["TypeError", "TypeError", "TypeError", "TypeError", "TypeError", "ยข"])
+ })
+
test("only UTF-8 is supported; fatal decoding rejects malformed input", async () => {
expect((await error(`new TextDecoder("latin1")`)).message).toContain('The "latin1" encoding is not supported')
expect((await error(`new TextDecoder("utf-8", { fatal: true }).decode(new Uint8Array([0xff]))`)).message).toContain(
From 9bc30594ab90d1adb2489ecf5443b1e7d685b465 Mon Sep 17 00:00:00 2001
From: David Hill <1879069+iamdavidhill@users.noreply.github.com>
Date: Thu, 12 Nov 2026 14:57:16 -0600
Subject: [PATCH 13/42] refactor(site): put every neutral grey on one shared
scale (#63604)
---
package.json | 2 +-
packages/data/app/src/app.css | 123 -----------
packages/data/app/src/routes/index.css | 197 ++++++++----------
packages/nav-menus/src/nav-menus.css | 33 +--
script/check-greys.ts | 170 +++++++++++++++
.../src/component/header-context-menu.css | 8 +-
.../src/component/site/changelog-entry.css | 4 +-
.../site/src/component/site/css-variants.json | 2 +-
.../site/src/component/site/docs-variants.css | 44 ++--
.../component/site/docs-version-notice.css | 2 +-
.../site/src/component/site/home-order.css | 2 +-
.../site/src/component/site/nav-order.css | 2 +-
.../src/component/site/open-source-fork.css | 14 +-
.../site/src/component/site/pair-panel.css | 20 +-
.../src/component/site/preload-settings.ts | 2 +-
.../site/src/component/site/product-list.css | 8 +-
.../site/src/component/site/product-page.css | 18 +-
services/site/src/component/site/products.css | 20 +-
services/site/src/component/site/site.css | 127 +++++++----
services/site/src/component/site/site.tsx | 2 +-
.../site/src/component/site/voice/orb.css | 4 +-
.../src/component/site/voice/voice-mode.css | 8 +-
services/site/src/docs/styles/docs.css | 8 +-
services/site/src/routes/brand/index.css | 19 +-
services/site/src/routes/font/index.css | 26 ++-
services/site/src/routes/index.css | 4 +-
services/site/src/routes/legal/legal.css | 3 +-
services/site/src/routes/press/index.css | 6 +-
.../site/src/routes/press/media-gallery.css | 10 +-
services/site/src/routes/product/index.css | 2 +-
30 files changed, 490 insertions(+), 400 deletions(-)
delete mode 100644 packages/data/app/src/app.css
create mode 100644 script/check-greys.ts
diff --git a/package.json b/package.json
index ddc3177d21f6..0d8ec57314a3 100644
--- a/package.json
+++ b/package.json
@@ -14,7 +14,7 @@
"dev:desktop": "bun --cwd packages/desktop dev",
"dev:web": "bun --cwd packages/app dev",
"dev:site": "bun run --cwd services/site dev",
- "lint": "oxlint && ast-grep scan -c script/ast-grep/gui-plugins/sgconfig.yml && bun script/sdk-docs.ts",
+ "lint": "oxlint && ast-grep scan -c script/ast-grep/gui-plugins/sgconfig.yml && bun script/sdk-docs.ts && bun script/check-greys.ts",
"lint:changed": "bun script/lint-changed.ts",
"lint:effect-patterns": "ast-grep scan -c script/ast-grep/sgconfig.yml packages/util/src packages/core/src packages/server/src packages/protocol/src packages/cli/src",
"lint:effect-simplifications": "ast-grep scan -c script/ast-grep/effect-simplifications/sgconfig.yml --off=unused-suppression packages",
diff --git a/packages/data/app/src/app.css b/packages/data/app/src/app.css
deleted file mode 100644
index 6b7652a0337c..000000000000
--- a/packages/data/app/src/app.css
+++ /dev/null
@@ -1,123 +0,0 @@
-:root {
- color-scheme: light dark;
- --stats-bg: #f8f5ee;
- --stats-ink: #16110d;
- --stats-muted: #6d6257;
- --stats-line: #ded5c9;
- --stats-panel: #fffaf1;
- --stats-accent: #2357ff;
-}
-
-@media (prefers-color-scheme: dark) {
- :root {
- --stats-bg: #11100e;
- --stats-ink: #f7efe4;
- --stats-muted: #b8aa99;
- --stats-line: #322d27;
- --stats-panel: #1a1714;
- --stats-accent: #86a2ff;
- }
-}
-
-html {
- line-height: 1;
- background: var(--stats-bg);
-}
-
-body {
- margin: 0;
- min-width: 320px;
- background:
- radial-gradient(circle at top left, color-mix(in srgb, var(--stats-accent) 16%, transparent), transparent 32rem),
- var(--stats-bg);
- color: var(--stats-ink);
- font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
- -webkit-font-smoothing: antialiased;
-}
-
-a {
- color: inherit;
-}
-
-.shell {
- box-sizing: border-box;
- min-height: 100vh;
- padding: 2rem clamp(1rem, 4vw, 4rem);
-}
-
-.panel {
- display: grid;
- gap: clamp(2rem, 8vw, 5rem);
- box-sizing: border-box;
- width: min(100%, 72rem);
- margin: 0 auto;
- padding: clamp(1.25rem, 4vw, 3rem);
- border: 1px solid var(--stats-line);
- border-radius: 1.5rem;
- background: color-mix(in srgb, var(--stats-panel) 88%, transparent);
-}
-
-.eyebrow {
- margin: 0 0 1rem;
- color: var(--stats-muted);
- font-size: 0.75rem;
- letter-spacing: 0.14em;
- text-transform: uppercase;
-}
-
-h1 {
- max-width: 11ch;
- margin: 0;
- font-size: clamp(3rem, 14vw, 9rem);
- line-height: 0.85;
- letter-spacing: -0.08em;
-}
-
-.summary {
- max-width: 42rem;
- margin: 1.5rem 0 0;
- color: var(--stats-muted);
- font-size: clamp(1rem, 2vw, 1.25rem);
- line-height: 1.6;
-}
-
-.grid {
- display: grid;
- grid-template-columns: repeat(3, minmax(0, 1fr));
- gap: 1px;
- overflow: hidden;
- border: 1px solid var(--stats-line);
- border-radius: 1rem;
- background: var(--stats-line);
-}
-
-.metric {
- padding: 1rem;
- background: var(--stats-panel);
-}
-
-.metric b {
- display: block;
- margin-bottom: 0.5rem;
- font-size: clamp(1.5rem, 4vw, 3rem);
- letter-spacing: -0.05em;
-}
-
-.metric span {
- color: var(--stats-muted);
- font-size: 0.8125rem;
-}
-
-.link {
- display: inline-flex;
- width: fit-content;
- margin-top: 1.5rem;
- color: var(--stats-accent);
- text-decoration: none;
-}
-
-@media (max-width: 720px) {
- .grid {
- grid-template-columns: 1fr;
- }
-}
diff --git a/packages/data/app/src/routes/index.css b/packages/data/app/src/routes/index.css
index 01e30dcc303c..0323e4e0b77b 100644
--- a/packages/data/app/src/routes/index.css
+++ b/packages/data/app/src/routes/index.css
@@ -118,19 +118,22 @@
line-gap-override: 0%;
}
+/* The page behind the app, in the page step of the shared grey scale (--stats-bg), written out because the tokens
+ live on [data-page], inside this element. grey-ok: outside the tokens' scope */
:root {
- background: #ffffff;
+ background: #fbfbfb;
}
:root[data-stats-theme="dark"] {
- background: #161616;
+ background: #0c0c0c;
}
@media (prefers-color-scheme: dark) {
:root:not([data-stats-theme="light"]) {
- background: #161616;
+ background: #0c0c0c;
}
}
+/* grey-ok-end */
body {
min-width: 320px;
@@ -139,34 +142,28 @@ body {
[data-page="stats"] {
color-scheme: light;
- --color-background: #ffffff;
- --color-background-weak: #fafafa;
- --color-background-weak-hover: #eeeeee;
- --color-background-strong: #161616;
- --color-background-strong-hover: #242424;
- --color-text: #5c5c5c;
- --color-text-weak: #707070;
- --color-text-strong: #161616;
- --color-text-inverted: #ffffff;
- --color-border-weak: #0000001a;
- --stats-bg: #ffffff;
- --stats-layer: #fafafa;
+ --stats-bg: #fbfbfb;
+ --stats-layer: #ffffff;
--stats-layer-2: #eeeeee;
--stats-line: #0000001a;
--stats-line-strong: #00000033;
--stats-text: #161616;
--stats-muted: #5c5c5c;
- --stats-faint: #707070;
+ --stats-faint: #6b6b6b;
--stats-theme-icon-active: #3a3a3a;
--stats-accent: #3b5cf6;
--stats-accent-text: #3b5cf6;
- --stats-bar-idle: #d4d4d4;
- --stats-dot: #d4d4d4;
+ --stats-bar-idle: #d2d2d2;
+ --stats-dot: #d2d2d2;
--stats-hero-muted: #5c5c5c;
--stats-hero-pattern: #eeeeee;
- --stats-logo-bg: #161616;
- --stats-logo-fill: #454545;
- --stats-logo-stroke: #e2e2e2;
+ --stats-logo-bg: #0c0c0c;
+ --stats-logo-fill: #4b4b4b;
+ --stats-logo-stroke: #eeeeee;
+ --stats-popover: #ffffff;
+ --stats-layer-hover: #ffffff;
+ --stats-on-accent: #ffffff;
+ --stats-knob: #fafafa;
--stats-page-padding: 5rem;
--stats-section-padding: 6rem;
min-height: 100vh;
@@ -404,11 +401,11 @@ body {
[data-page="stats"] [data-slot="header-button"][data-variant="contrast"] {
gap: 8px;
- color: #ffffff;
- background: #242424;
+ color: var(--stats-bg);
+ background: var(--stats-text);
box-shadow:
0 0 0 0 #00000000,
- 0 0 0 0.5px #3a3a3a,
+ 0 0 0 0.5px var(--stats-text),
0 1px 1.5px 0 #00000033,
inset 0 -1px 2px 0 #0000000f,
inset 0 1px 2px 0 #ffffff24;
@@ -1393,7 +1390,7 @@ body {
}
[data-page="stats"] [data-component="content"] button[data-active="true"] {
- color: #fff;
+ color: var(--stats-bg);
background: var(--stats-text);
}
@@ -1580,7 +1577,7 @@ body {
gap: 8px;
min-width: 220px;
padding: 16px;
- background: #ffffff;
+ background: var(--stats-popover);
border: 1px solid var(--stats-line-strong);
box-shadow:
0 8px 16px #0000000a,
@@ -1648,7 +1645,7 @@ body {
width: 192px;
min-width: 192px;
padding: 0;
- background: #ffffff;
+ background: var(--stats-popover);
border: 0;
box-shadow:
0 0 0 0.5px #00000024,
@@ -2226,7 +2223,7 @@ body {
[data-page="stats"] [data-component="leader-card"][data-active="true"] {
border-color: var(--stats-line-strong);
- background: #ffffff;
+ background: var(--stats-layer-hover);
box-shadow:
0 0 0 0.5px #00000024,
0 6px 16px #0000000d,
@@ -2248,7 +2245,7 @@ body {
[data-page="stats"] [data-component="leader-card"]:hover,
[data-page="stats"] [data-component="leader-card"]:focus-visible {
border-color: var(--stats-line-strong);
- background: #ffffff;
+ background: var(--stats-layer-hover);
box-shadow:
0 0 0 0.5px #00000024,
0 6px 16px #0000000d,
@@ -2447,7 +2444,7 @@ body {
min-width: 228px;
padding: 0;
border: 0;
- background: #ffffff;
+ background: var(--stats-popover);
box-shadow:
0 0 0 0.5px #00000024,
0 8px 16px #0000000f,
@@ -3163,7 +3160,7 @@ body {
height: 64px;
background: var(--stats-accent-text);
box-shadow: inset 0 0 0 1px #0000001a;
- color: #ffffff;
+ color: var(--stats-on-accent);
}
[data-page="stats"] [data-slot="lab-hero-avatar"][data-empty="true"] {
@@ -3442,7 +3439,7 @@ body {
height: 40px;
background: var(--stats-accent-text);
box-shadow: inset 0 0 0 1px #0000001a;
- color: #ffffff;
+ color: var(--stats-on-accent);
}
[data-page="stats"] [data-slot="model-hero-avatar"] svg {
@@ -4411,7 +4408,7 @@ body {
flex: 0 0 auto;
width: 20px;
height: 20px;
- color: #ffffff;
+ color: var(--stats-on-accent);
background: var(--stats-accent-text);
box-shadow: inset 0 0 0 1px #0000001a;
}
@@ -4488,7 +4485,7 @@ body {
flex: 0 0 auto;
width: 16px;
height: 16px;
- color: #ffffff;
+ color: var(--stats-on-accent);
background: var(--stats-accent-text);
box-shadow: inset 0 0 0 1px #0000001a;
}
@@ -4634,7 +4631,7 @@ body {
flex: 0 0 auto;
width: 28px;
height: 28px;
- color: #ffffff;
+ color: var(--stats-on-accent);
background: var(--stats-accent-text);
box-shadow: inset 0 0 0 1px #0000001a;
}
@@ -4971,10 +4968,10 @@ body {
--lab-usage-column-gutter: calc(var(--lab-usage-gap) / 2);
--lab-usage-bar-height: 76px;
--lab-usage-line-bottom: 124px;
- --lab-usage-bar: #dbdbdb;
- --lab-usage-line: #808080;
+ --lab-usage-bar: #d2d2d2;
+ --lab-usage-line: #6b6b6b;
--lab-usage-active: #3b5cf6;
- --lab-usage-band: #f2f2f2;
+ --lab-usage-band: #eeeeee;
grid-template-rows: minmax(0, 450px) 14px;
gap: 40px;
height: 504px;
@@ -5161,10 +5158,10 @@ body {
--model-trend-column-gutter: calc(var(--model-trend-gap) / 2);
--model-trend-bar-height: 76px;
--model-trend-line-bottom: 124px;
- --model-trend-bar: #dbdbdb;
- --model-trend-line: #808080;
+ --model-trend-bar: #d2d2d2;
+ --model-trend-line: #6b6b6b;
--model-trend-active: #3b5cf6;
- --model-trend-band: #f2f2f2;
+ --model-trend-band: #eeeeee;
grid-template-rows: minmax(0, 450px) 14px;
gap: 40px;
height: 504px;
@@ -5838,11 +5835,12 @@ body {
display: grid;
place-items: center;
flex: 0 0 auto;
- color: #ffffff;
+ color: var(--stats-on-accent);
background: var(--stats-accent-text);
box-shadow: inset 0 0 0 1px #0000001a;
}
+/* grey-ok: the labs' own brand colours */
[data-page="stats"] [data-slot="compare-home-avatar"][data-lab="deepseek"] {
background: #5d6ff4;
}
@@ -5854,6 +5852,7 @@ body {
[data-page="stats"] [data-slot="compare-home-avatar"][data-lab="anthropic"] {
background: #c99b75;
}
+/* grey-ok-end */
[data-page="stats"] [data-slot="compare-home-avatar"][data-size="large"] {
width: 40px;
@@ -6289,7 +6288,7 @@ body {
[data-slot="compare-detail-action"][aria-pressed="true"]
[data-slot="compare-detail-highlight-icon"]
i:last-child {
- background: #fafafa;
+ background: var(--stats-knob);
box-shadow:
0 0 0 0.5px rgb(0 0 0 / 12%),
0 1px 2px -1px rgb(0 0 0 / 8%),
@@ -7377,42 +7376,34 @@ body {
[data-page="stats"][data-theme="dark"],
:root[data-stats-theme="dark"] [data-page="stats"]:not([data-theme="light"]) {
color-scheme: dark;
- --color-background: #161616;
- --color-background-weak: #242424;
- --color-background-weak-hover: #303030;
- --color-background-strong: #ffffff;
- --color-background-strong-hover: #eeeeee;
- --color-text: #d4d4d4;
- --color-text-weak: #a3a3a3;
- --color-text-strong: #ffffff;
- --color-text-inverted: #161616;
- --color-border-weak: #ffffff1a;
- --stats-bg: #161616;
- --stats-layer: #242424;
- --stats-layer-2: #303030;
+ --stats-bg: #0c0c0c;
+ --stats-layer: #161616;
+ --stats-layer-2: #242424;
--stats-line: #ffffff1a;
--stats-line-strong: #ffffff33;
- --stats-text: #ffffff;
- --stats-muted: #d4d4d4;
- --stats-faint: #a3a3a3;
+ --stats-text: #fafafa;
+ --stats-muted: #aeaeae;
+ --stats-faint: #8f8f8f;
--stats-accent: #6b8fff;
--stats-accent-text: #6b8fff;
--stats-theme-icon-active: #fafafa;
- --stats-bar-idle: #303030;
- --stats-dot: #303030;
- --stats-hero-muted: #a3a3a3;
- --stats-hero-pattern: #303030;
- --stats-logo-bg: #f1ecec;
- --stats-logo-fill: #b7b1b1;
- --stats-logo-stroke: #211e1e;
+ --stats-bar-idle: #2e2e2e;
+ --stats-dot: #2e2e2e;
+ --stats-hero-muted: #aeaeae;
+ --stats-hero-pattern: #242424;
+ --stats-logo-bg: #f5f5f5;
+ --stats-logo-fill: #d2d2d2;
+ --stats-logo-stroke: #1f1f1f;
+ --stats-popover: #242424;
+ --stats-layer-hover: #242424;
}
[data-page="stats"][data-theme="dark"] [data-component="model-usage-chart"][data-variant="lab-usage"],
:root[data-stats-theme="dark"]
[data-page="stats"]:not([data-theme="light"])
[data-component="model-usage-chart"][data-variant="lab-usage"] {
- --lab-usage-bar: #3a3a3a;
- --lab-usage-line: #a3a3a3;
+ --lab-usage-bar: #4b4b4b;
+ --lab-usage-line: #8f8f8f;
--lab-usage-band: #242424;
--lab-usage-active: #6b8fff;
}
@@ -7421,15 +7412,15 @@ body {
:root[data-stats-theme="dark"]
[data-page="stats"]:not([data-theme="light"])
[data-component="model-usage-chart"][data-variant="model-trend"] {
- --model-trend-bar: #3a3a3a;
- --model-trend-line: #a3a3a3;
+ --model-trend-bar: #4b4b4b;
+ --model-trend-line: #8f8f8f;
--model-trend-band: #242424;
--model-trend-active: #6b8fff;
}
[data-page="stats"][data-theme="dark"] [data-component="chart-tooltip"],
:root[data-stats-theme="dark"] [data-page="stats"]:not([data-theme="light"]) [data-component="chart-tooltip"] {
- background: #242424;
+ background: var(--stats-popover);
}
[data-page="stats"][data-theme="dark"]
@@ -7444,7 +7435,7 @@ body {
[data-page="stats"]:not([data-theme="light"])
:is([data-section="top-models"], [data-section="unique-users"])
[data-component="chart-tooltip"] {
- background: #242424;
+ background: var(--stats-popover);
box-shadow:
0 0 0 0.5px #ffffff24,
0 8px 16px #0000003d,
@@ -7483,7 +7474,7 @@ body {
:root[data-stats-theme="dark"]
[data-page="stats"]:not([data-theme="light"])
[data-component="leader-card"]:focus-visible {
- background: #303030;
+ background: var(--stats-layer-hover);
box-shadow:
0 0 0 0.5px #ffffff24,
0 6px 16px #0000003d,
@@ -7528,8 +7519,8 @@ body {
:root[data-stats-theme="dark"]
[data-page="stats"]:not([data-theme="light"])
[data-slot="header-button"][data-variant="contrast"] {
- color: #ffffff;
- background: #5c5c5c;
+ color: var(--stats-bg);
+ background: var(--stats-text);
box-shadow:
0 -0.5px 0 0 #ffffff4d,
0 0 0 0.5px #ffffff66,
@@ -7539,41 +7530,33 @@ body {
@media (prefers-color-scheme: dark) {
:root:not([data-stats-theme="light"]) [data-page="stats"]:not([data-theme="light"]) {
color-scheme: dark;
- --color-background: #161616;
- --color-background-weak: #242424;
- --color-background-weak-hover: #303030;
- --color-background-strong: #ffffff;
- --color-background-strong-hover: #eeeeee;
- --color-text: #d4d4d4;
- --color-text-weak: #a3a3a3;
- --color-text-strong: #ffffff;
- --color-text-inverted: #161616;
- --color-border-weak: #ffffff1a;
- --stats-bg: #161616;
- --stats-layer: #242424;
- --stats-layer-2: #303030;
+ --stats-bg: #0c0c0c;
+ --stats-layer: #161616;
+ --stats-layer-2: #242424;
--stats-line: #ffffff1a;
--stats-line-strong: #ffffff33;
- --stats-text: #ffffff;
- --stats-muted: #d4d4d4;
- --stats-faint: #a3a3a3;
+ --stats-text: #fafafa;
+ --stats-muted: #aeaeae;
+ --stats-faint: #8f8f8f;
--stats-accent: #6b8fff;
--stats-accent-text: #6b8fff;
--stats-theme-icon-active: #fafafa;
- --stats-bar-idle: #303030;
- --stats-dot: #303030;
- --stats-hero-muted: #a3a3a3;
- --stats-hero-pattern: #303030;
- --stats-logo-bg: #f1ecec;
- --stats-logo-fill: #b7b1b1;
- --stats-logo-stroke: #211e1e;
+ --stats-bar-idle: #2e2e2e;
+ --stats-dot: #2e2e2e;
+ --stats-hero-muted: #aeaeae;
+ --stats-hero-pattern: #242424;
+ --stats-logo-bg: #f5f5f5;
+ --stats-logo-fill: #d2d2d2;
+ --stats-logo-stroke: #1f1f1f;
+ --stats-popover: #242424;
+ --stats-layer-hover: #242424;
}
:root:not([data-stats-theme="light"])
[data-page="stats"]:not([data-theme="light"])
[data-component="model-usage-chart"][data-variant="lab-usage"] {
- --lab-usage-bar: #3a3a3a;
- --lab-usage-line: #a3a3a3;
+ --lab-usage-bar: #4b4b4b;
+ --lab-usage-line: #8f8f8f;
--lab-usage-band: #242424;
--lab-usage-active: #6b8fff;
}
@@ -7581,21 +7564,21 @@ body {
:root:not([data-stats-theme="light"])
[data-page="stats"]:not([data-theme="light"])
[data-component="model-usage-chart"][data-variant="model-trend"] {
- --model-trend-bar: #3a3a3a;
- --model-trend-line: #a3a3a3;
+ --model-trend-bar: #4b4b4b;
+ --model-trend-line: #8f8f8f;
--model-trend-band: #242424;
--model-trend-active: #6b8fff;
}
:root:not([data-stats-theme="light"]) [data-page="stats"]:not([data-theme="light"]) [data-component="chart-tooltip"] {
- background: #242424;
+ background: var(--stats-popover);
}
:root:not([data-stats-theme="light"])
[data-page="stats"]:not([data-theme="light"])
[data-section="top-models"]
[data-component="chart-tooltip"] {
- background: #242424;
+ background: var(--stats-popover);
box-shadow:
0 0 0 0.5px #ffffff24,
0 8px 16px #0000003d,
@@ -7628,7 +7611,7 @@ body {
:root:not([data-stats-theme="light"])
[data-page="stats"]:not([data-theme="light"])
[data-component="leader-card"]:focus-visible {
- background: #303030;
+ background: var(--stats-layer-hover);
box-shadow:
0 0 0 0.5px #ffffff24,
0 6px 16px #0000003d,
@@ -7654,8 +7637,8 @@ body {
:root:not([data-stats-theme="light"])
[data-page="stats"]:not([data-theme="light"])
[data-slot="header-button"][data-variant="contrast"] {
- color: #ffffff;
- background: #5c5c5c;
+ color: var(--stats-bg);
+ background: var(--stats-text);
box-shadow:
0 -0.5px 0 0 #ffffff4d,
0 0 0 0.5px #ffffff66,
diff --git a/packages/nav-menus/src/nav-menus.css b/packages/nav-menus/src/nav-menus.css
index 266df2981dee..64864a5dddf1 100644
--- a/packages/nav-menus/src/nav-menus.css
+++ b/packages/nav-menus/src/nav-menus.css
@@ -10,12 +10,15 @@
--nav-menu-icon the Brand, ZIP and Press drawings
--nav-menu-mono OpenTUI Mono (the host loads it) */
[data-nav-menu] {
- --ink: var(--nav-menu-ink, light-dark(hsl(0 0% 8%), hsl(0 0% 95%)));
- --weak: var(--nav-menu-weak, light-dark(hsl(0 0% 40%), hsl(0 0% 64%)));
- --popover: var(--nav-menu-popover, light-dark(hsl(0 0% 100%), hsl(0 0% 10%)));
+ --ink: var(--nav-menu-ink, light-dark(#161616, #fafafa));
+ --weak: var(--nav-menu-weak, light-dark(#5c5c5c, #aeaeae));
+ --popover: var(--nav-menu-popover, light-dark(#ffffff, #161616));
--link: var(--nav-menu-link, light-dark(#3b5cf6, #6b8fff));
- --bar: var(--nav-menu-bar, light-dark(hsl(0 0% 40%), hsl(0 0% 62%)));
- --icon: var(--nav-menu-icon, light-dark(hsl(0 0% 40%), hsl(0 0% 56%)));
+ --bar: var(--nav-menu-bar, light-dark(#5c5c5c, #aeaeae));
+ --icon: var(--nav-menu-icon, light-dark(#6b6b6b, #8f8f8f));
+ /* The fixed backgrounds behind the Brand files' light and dark previews. */
+ --tile-light: #f5f5f5;
+ --tile-dark: #0c0c0c;
--tint: color-mix(in srgb, var(--link) 10%, var(--popover));
/* The divider between a card's thumbnail and its label, and the card's ring. */
--divider: light-dark(rgb(0 0 0 / 0.08), rgb(255 255 255 / 0.1));
@@ -158,14 +161,14 @@
/* Each file on the background it is made for: light marks on light, dark on dark. */
&[data-tone="light"] {
- background: hsl(0 0% 96%);
+ background: var(--tile-light);
}
/* A dark preview's ring is its own colour, so it reads at full size (blue while hovered). */
&[data-tone="dark"],
&[data-tone="dark"]:dir(rtl) {
- background: #0a0a0a;
- box-shadow: 0 0 0 1px #0a0a0a;
+ background: var(--tile-dark);
+ box-shadow: 0 0 0 1px var(--tile-dark);
}
&[data-kind="logo"] svg {
@@ -270,14 +273,14 @@
@media (hover: hover) and (pointer: fine) {
&:hover {
background: var(--nav-chevron-hover);
- color: var(--nav-menu-ink, light-dark(hsl(0 0% 8%), hsl(0 0% 95%)));
+ color: var(--nav-menu-ink, var(--nav-chevron-ink));
}
}
&:active,
&[aria-expanded="true"] {
background: var(--nav-chevron-press);
- color: var(--nav-menu-ink, light-dark(hsl(0 0% 8%), hsl(0 0% 95%)));
+ color: var(--nav-menu-ink, var(--nav-chevron-ink));
}
&[aria-expanded="true"] svg {
@@ -306,16 +309,16 @@
--nav-edge: 24px;
--nav-end: 17.5px;
--nav-rule: light-dark(hsl(0 0% 88%), hsl(0 0% 18%));
- /* The product name's one fill (hover, open and pressed), opencode.ai's lockup hover: half the mark's inner grey on
- the docs page (#d2d2d2 over #fbfbfb, #4b4b4b over #0c0c0c). Fixed, so it is the same on every page background. */
- --nav-name-hover: light-dark(#e7e7e7, #2c2c2c);
+ /* The product name's one fill (hover, open and pressed), opencode.ai's lockup hover: the hover step of the shared
+ grey scale. Fixed, so it is the same on every page background. */
+ --nav-name-hover: light-dark(#eeeeee, #242424);
/* The chevron after a product name (and the docs' after DOCS): its box, the gap after the name's highlight, the glyph,
how far its touch target reaches past it, and its colours. */
--nav-chevron-width: 20px;
--nav-chevron-gap: 2px;
--nav-chevron-glyph: 10px;
--nav-chevron-reach: 24px;
- --nav-chevron-ink: light-dark(hsl(0 0% 8%), hsl(0 0% 95%));
+ --nav-chevron-ink: light-dark(#161616, #fafafa);
--nav-chevron-hover: var(--nav-name-hover);
--nav-chevron-press: light-dark(#d2d2d2, #4b4b4b);
/* The product name after the mark (and the docs' DOCS): its size, and the padding under it that puts OpenTUI Mono's
@@ -349,7 +352,7 @@
highlight, --nav-name-hover while hovered, pressed or open (hovering opens the product menu, so it never steps darker).
Placed at --nav-edge, centred in the bar. */
[data-nav-lockup] {
- --nav-lockup-ink: light-dark(hsl(0 0% 8%), hsl(0 0% 95%));
+ --nav-lockup-ink: light-dark(#161616, #fafafa);
--nav-logo-inner: light-dark(#d2d2d2, #4b4b4b);
--nav-logo-code: light-dark(#1f1f1f, #eeeeee);
--nav-lockup-inset: round(calc((var(--nav-logo-box-h) - 25px) / 2), 1px);
diff --git a/script/check-greys.ts b/script/check-greys.ts
new file mode 100644
index 000000000000..d1669c8065b6
--- /dev/null
+++ b/script/check-greys.ts
@@ -0,0 +1,170 @@
+#!/usr/bin/env bun
+// Keeps the web surfaces' greys on one shared scale. Fails when a stylesheet uses a grey, black or
+// white that isn't on the scale, or types a scale grey straight into a rule instead of using a
+// token. Files with a fixed look of their own (the arcade, the video tools, print) are listed in
+// EXCEPTIONS with the reason. Usage:
+// bun script/check-greys.ts report problems, exit 1 if any
+// bun script/check-greys.ts --json every neutral literal with its outcome, for the colour audit
+import path from "node:path"
+
+const ROOTS = ["services/site/src", "packages/nav-menus/src", "packages/data/app/src"]
+
+// The shared neutral scale. A step is a role, and the same step does the same job in light and dark.
+const SCALE = {
+ light: [
+ "#fbfbfb",
+ "#ffffff",
+ "#f5f5f5",
+ "#eeeeee",
+ "#e0e0e0",
+ "#d2d2d2",
+ "#888888",
+ "#6b6b6b",
+ "#5c5c5c",
+ "#3a3a3a",
+ "#161616",
+ ],
+ dark: [
+ "#0c0c0c",
+ "#161616",
+ "#1a1a1a",
+ "#242424",
+ "#2e2e2e",
+ "#4b4b4b",
+ "#6a6a6a",
+ "#8f8f8f",
+ "#aeaeae",
+ "#dbdbdb",
+ "#fafafa",
+ ],
+}
+
+// Pure black and white always pass in masks (where #000 only means "opaque") and shadows.
+const ALPHA_CONTEXT = /^(mask|-webkit-mask|box-shadow|text-shadow|filter|backdrop-filter|--[\w-]*shadow)/
+
+const EXCEPTIONS: [RegExp, string][] = [
+ [/component\/site\/arcade\//, "Arcade game: its own cabinet, screen and metal colours"],
+ [/component\/site\/arcade3d\//, "Arcade game: its own cabinet, screen and metal colours"],
+ [/component\/video-editor\//, "Internal video editor"],
+ [/component\/font-film\//, "Font film: rendered video frames"],
+ [/component\/font-share\//, "Font share cards: exported images"],
+ [/component\/site\/device-preview\.css$/, "Device preview tool: device frames"],
+ [/component\/site\/design-mode\.css$/, "Design mode: internal overlay"],
+ [/component\/site\/legal-print\.css$/, "Print: black on white whatever the theme"],
+ [
+ /style\/token\/color\.css$/,
+ "Legacy tokens: to remove when the dropdown, language picker, 404 and limits graph move to site tokens",
+ ],
+]
+
+// Pure black is a token only for video letterboxing (--media-black).
+const scale = new Set([...SCALE.light, ...SCALE.dark, "#000000"])
+
+const files = (
+ await Promise.all(ROOTS.map((root) => Array.fromAsync(new Bun.Glob(`${root}/**/*.css`).scan({ cwd: repo() }))))
+).flat()
+
+const entries = (
+ await Promise.all(
+ files.map(async (file) => {
+ const source = await Bun.file(path.join(repo(), file)).text()
+ const exception = EXCEPTIONS.find(([re]) => re.test(file))?.[1]
+ const allowed = allowedRanges(source)
+ return declarations(source).flatMap((decl) =>
+ neutrals(decl.value).map((hex) => ({
+ file,
+ line: decl.line,
+ property: decl.property,
+ hex: hex.value,
+ alpha: hex.alpha,
+ text: `${decl.property}: ${decl.value}`.replace(/\s+/g, " ").slice(0, 160),
+ outcome: outcome(
+ decl,
+ hex,
+ exception ?? allowed.find((range) => decl.line >= range.from && decl.line <= range.to)?.why,
+ ),
+ })),
+ )
+ }),
+ )
+).flat()
+
+if (process.argv.includes("--json")) {
+ console.log(JSON.stringify({ scale: SCALE, exceptions: EXCEPTIONS.map(([re, why]) => [re.source, why]), entries }))
+ process.exit(0)
+}
+
+const problems = entries.filter((entry) => entry.outcome.startsWith("problem"))
+for (const p of problems) console.error(`${p.file}:${p.line} ${p.hex} ${p.outcome.slice(9)} (${p.text})`)
+if (problems.length) {
+ console.error(
+ `\n${problems.length} grey${problems.length === 1 ? "" : "s"} off the shared scale (script/check-greys.ts).`,
+ )
+ process.exit(1)
+}
+
+function outcome(
+ decl: { property: string; value: string },
+ hex: { value: string; alpha: boolean },
+ exception: string | undefined,
+) {
+ const pure = hex.value === "#000000" || hex.value === "#ffffff"
+ if (exception) return `exception: ${exception}`
+ if (/^--([a-z]+-)?logo-/.test(decl.property)) return "exception: Brand logo greys (brand guidelines)"
+ if (ALPHA_CONTEXT.test(decl.property) && pure) return "allowed: mask or shadow"
+ if (hex.alpha && pure) return "allowed: black or white wash"
+ if (pure && /color-mix\(.*#(000|fff)\b/i.test(decl.value)) return "allowed: shades a colour"
+ if (!scale.has(hex.value)) return "problem: not on the scale"
+ if (decl.property.startsWith("--") || decl.property === "initial-value") return "token"
+ return "problem: use a token"
+}
+
+// Lines between `/* grey-ok: */` and `/* grey-ok-end */` keep their literal greys, for the
+// few places tokens can't reach, such as the page behind the site.
+function allowedRanges(source: string) {
+ const lines = source.split("\n")
+ return lines.flatMap((line, i) => {
+ const why = line.match(/grey-ok:\s*(.*?)\s*\*\//)?.[1]
+ if (!why) return []
+ const end = lines.findIndex((next, j) => j > i && next.includes("grey-ok-end"))
+ return [{ from: i + 1, to: end === -1 ? i + 1 : end + 1, why }]
+ })
+}
+
+// Every declaration with its property and the line it starts on. Comments are blanked first, keeping
+// line numbers.
+function declarations(source: string) {
+ const text = source.replace(/\/\*[\s\S]*?\*\//g, (comment) => comment.replace(/[^\n]/g, " "))
+ return [...text.matchAll(/([\w-]+)\s*:([^;{}]+)/g)]
+ .filter((m) => /#[0-9a-fA-F]|hsl|rgb/.test(m[2]))
+ .map((m) => ({ property: m[1], value: m[2].trim(), line: text.slice(0, m.index).split("\n").length }))
+}
+
+// Neutral colour literals in a value: hex, hsl() with 0% saturation, and rgb() with equal channels.
+function neutrals(value: string) {
+ return [
+ ...[...value.matchAll(/#([0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})\b/g)].map((m) => {
+ const h = m[1].length <= 4 ? [...m[1]].map((c) => c + c).join("") : m[1]
+ return { value: `#${h.slice(0, 6).toLowerCase()}`, alpha: h.length === 8 }
+ }),
+ ...[...value.matchAll(/hsla?\(\s*[\d.]+(?:deg)?[\s,]+0%[\s,]+([\d.]+)%\s*(?:[,/]\s*([\d.]+%?))?\s*\)/g)].map(
+ (m) => {
+ const v = Math.round((Number(m[1]) / 100) * 255)
+ .toString(16)
+ .padStart(2, "0")
+ return { value: `#${v}${v}${v}`, alpha: m[2] !== undefined }
+ },
+ ),
+ ...[...value.matchAll(/rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)\s*(?:[,/]\s*([\d.]+%?))?\s*\)/g)].map((m) => ({
+ value: `#${[m[1], m[2], m[3]].map((c) => Number(c).toString(16).padStart(2, "0")).join("")}`,
+ alpha: m[4] !== undefined,
+ })),
+ ].filter((hex) => {
+ const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.value.slice(i, i + 2), 16))
+ return Math.max(r, g, b) - Math.min(r, g, b) <= 6
+ })
+}
+
+function repo() {
+ return path.resolve(import.meta.dir, "..")
+}
diff --git a/services/site/src/component/header-context-menu.css b/services/site/src/component/header-context-menu.css
index a9abf8f042ff..ba4bcde7ffcb 100644
--- a/services/site/src/component/header-context-menu.css
+++ b/services/site/src/component/header-context-menu.css
@@ -5,10 +5,10 @@
border-radius: 8px;
background-color: var(--color-background);
box-shadow:
- 0 0 0 1px rgba(19, 16, 16, 0.08),
- 0 6px 8px -4px rgba(19, 16, 16, 0.12),
- 0 4px 3px -2px rgba(19, 16, 16, 0.12),
- 0 1px 2px -1px rgba(19, 16, 16, 0.12);
+ 0 0 0 1px rgba(0, 0, 0, 0.08),
+ 0 6px 8px -4px rgba(0, 0, 0, 0.12),
+ 0 4px 3px -2px rgba(0, 0, 0, 0.12),
+ 0 1px 2px -1px rgba(0, 0, 0, 0.12);
padding: 6px;
@media (prefers-color-scheme: dark) {
diff --git a/services/site/src/component/site/changelog-entry.css b/services/site/src/component/site/changelog-entry.css
index f5fc8c3eaac8..b88ee4ece75a 100644
--- a/services/site/src/component/site/changelog-entry.css
+++ b/services/site/src/component/site/changelog-entry.css
@@ -211,7 +211,7 @@
flex: 0 0 100%;
aspect-ratio: 16 / 9;
overflow: hidden;
- background: #0a0a0a;
+ background: var(--fixed-dark);
:is(video, img) {
position: absolute;
@@ -972,7 +972,7 @@
width: 2rem;
height: 2rem;
padding: 0;
- color: #fff;
+ color: var(--fixed-white);
background: rgb(0 0 0 / 0.6);
opacity: 0.8;
transition: opacity 150ms ease;
diff --git a/services/site/src/component/site/css-variants.json b/services/site/src/component/site/css-variants.json
index b13fc092f1c1..2e50fa8722de 100644
--- a/services/site/src/component/site/css-variants.json
+++ b/services/site/src/component/site/css-variants.json
@@ -21,7 +21,7 @@
"data-docs-variants": "typography-4 lists-3 blockquote-2 callout-3 tabs-6 code-6 codeTitle-6 codeLines-6 codeDiff-6 terminal-6 fileTree-6 steps-2 cards-3 tables-5 badges-4 details-2 media-2 api-7 config-6 cli-6 pagination-4 breadcrumbs-3 search-4 switchers-2 editLink-4 feedback-5 inlineCode-6",
"data-status-bars": "4",
"data-logo-menu-hover": "blue",
- "data-light-bg": "fbfbfb",
+ "data-light-bg": null,
"data-sidebar": "column",
"data-console-height": "compact",
"data-console-label": "left",
diff --git a/services/site/src/component/site/docs-variants.css b/services/site/src/component/site/docs-variants.css
index 207d72ffc484..8c747e2bf234 100644
--- a/services/site/src/component/site/docs-variants.css
+++ b/services/site/src/component/site/docs-variants.css
@@ -576,7 +576,7 @@
/* On the red tint the code header label steps one shade darker, to keep a margin over 4.5:1. */
&[data-type="danger"] {
- --code-label: light-dark(#5e5e5e, #8f8f8f);
+ --code-label: light-dark(#5c5c5c, #8f8f8f);
}
/* The label in the mono font's bold, a confident semibold at 12px (the label only, not bold text
@@ -1184,9 +1184,9 @@
display: block;
margin: 0 -1rem 0.875rem;
padding: 0.5rem 1rem;
- border-bottom: 1px solid #2e2e2e;
+ border-bottom: 1px solid var(--fixed-dark-line);
font-size: var(--anno-size);
- color: #a0a0a0;
+ color: var(--fixed-dark-muted);
}
}
@@ -1199,12 +1199,12 @@
display: block;
height: 2rem;
margin: 0 -1rem 0.875rem;
- border-bottom: 1px solid #2e2e2e;
+ border-bottom: 1px solid var(--fixed-dark-line);
background:
- radial-gradient(circle, #555 3.5px, transparent 4px) 1rem center / 8px 8px no-repeat,
- radial-gradient(circle, #555 3.5px, transparent 4px) 1.75rem center / 8px 8px no-repeat,
- radial-gradient(circle, #555 3.5px, transparent 4px) 2.5rem center / 8px 8px no-repeat,
- #161616;
+ radial-gradient(circle, var(--fixed-dark-line-strong) 3.5px, transparent 4px) 1rem center / 8px 8px no-repeat,
+ radial-gradient(circle, var(--fixed-dark-line-strong) 3.5px, transparent 4px) 1.75rem center / 8px 8px no-repeat,
+ radial-gradient(circle, var(--fixed-dark-line-strong) 3.5px, transparent 4px) 2.5rem center / 8px 8px no-repeat,
+ var(--fixed-dark-raised);
}
}
@@ -2155,8 +2155,8 @@
}
[data-page="docs"][data-docs-variants~="cli-4"] [data-component="docs-article"] [data-component="cli-command"] pre {
- background: #0a0a0a;
- color: #eeeeee;
+ background: var(--fixed-dark);
+ color: var(--fixed-dark-text);
}
[data-page="docs"][data-docs-variants~="cli-5"] [data-component="docs-article"] [data-component="cli-command"] pre {
@@ -2745,20 +2745,20 @@
block type sits on it: a white body lifted off the off-white page (a step lighter than the page in
dark), a header row in the page's tone with the label (file mark and name, ">_ Terminal", Files,
Usage) and an always-visible Copy, a 1px border round the block and a divider under the header.
- Like Vercel, the header is the darker of the two in both themes (#fafafa over #fff, #000 over
- #0a0a0a there). The border is decorative (about 1.3:1); the marks that carry meaning (highlight
+ Like Vercel, the header is the darker of the two in both themes: the page colour over the raised
+ body. The border is decorative (about 1.3:1); the marks that carry meaning (highlight
and diff bars, the selected tab) are 3:1 or more, and all text is 4.5:1 or more. */
[data-page="docs"] {
- --code-body: light-dark(#ffffff, #161616);
- --code-head: light-dark(#f7f7f7, #111111);
- --code-border: light-dark(#e0e0e0, #2e2e2e);
- --code-text: light-dark(#141414, #f2f2f2);
- --code-label: light-dark(#666666, #8f8f8f);
+ --code-body: var(--grey-2);
+ --code-head: var(--grey-1);
+ --code-border: var(--grey-5);
+ --code-text: var(--grey-11);
+ --code-label: var(--grey-8);
/* Reference table heads (Tables 5, API, CLI): the label style in ink with the titles' faux medium
(the site serves no 500 weight); 12px uppercase keeps them reading as labels. */
--ref-head: var(--text-strong);
- --code-number: light-dark(#737373, #858585);
+ --code-number: var(--grey-8);
--code-mark: light-dark(#3b5cf6, #6b8fff);
--code-mark-tint: light-dark(#eff2fe, #1e2637);
--code-del: light-dark(#d61f1f, #f04c4c);
@@ -2770,7 +2770,7 @@
--token-flag: light-dark(#7a3fc4, #9d7cd8);
--token-string: light-dark(#2b7a3d, #7fd88f);
--token-operator: light-dark(#0f6e7a, #56b6c2);
- --token-output: light-dark(#666666, #8f8f8f);
+ --token-output: var(--grey-8);
}
/* Outside option 6 the frame folds away and its header hides, so the older options look as before. */
@@ -3277,9 +3277,9 @@
:is(p, li, td, th, dd, dt, h2, h3, h4, a, strong, em, small, span[data-slot])
> code {
padding: 0.1em 0.35em;
- border: 1px solid light-dark(#e6e6e6, #262626);
+ border: 1px solid var(--grey-5);
border-radius: 0;
- background: light-dark(#f2f2f2, #161616);
+ background: var(--grey-3);
color: var(--text-strong);
}
@@ -4211,7 +4211,7 @@
:not(pre) > code:not([data-component="code-frame"] *) {
padding: 0.1em 0.35em;
border: 1px solid var(--surface-chip-edge);
- background: linear-gradient(light-dark(#f2f2f2, #161616), light-dark(#f2f2f2, #161616)), var(--surface-layer);
+ background: linear-gradient(var(--grey-3), var(--grey-3)), var(--surface-layer);
background-blend-mode: var(--blend), normal;
color: var(--text-strong);
}
diff --git a/services/site/src/component/site/docs-version-notice.css b/services/site/src/component/site/docs-version-notice.css
index ae2efbf2332e..8c89ffdc4b6e 100644
--- a/services/site/src/component/site/docs-version-notice.css
+++ b/services/site/src/component/site/docs-version-notice.css
@@ -120,7 +120,7 @@
[data-slot="badge"] {
background: var(--link);
- color: light-dark(#ffffff, #0c0c0c);
+ color: var(--text-inverted);
}
}
diff --git a/services/site/src/component/site/home-order.css b/services/site/src/component/site/home-order.css
index d4860e36e299..5c7740c339bb 100644
--- a/services/site/src/component/site/home-order.css
+++ b/services/site/src/component/site/home-order.css
@@ -26,7 +26,7 @@
&[data-dragging] {
cursor: grabbing;
- color: #fff;
+ color: var(--on-accent);
background: var(--link);
border-color: var(--link);
}
diff --git a/services/site/src/component/site/nav-order.css b/services/site/src/component/site/nav-order.css
index 1f1e77ba8f6b..e95dd290057c 100644
--- a/services/site/src/component/site/nav-order.css
+++ b/services/site/src/component/site/nav-order.css
@@ -400,7 +400,7 @@ html:has(ul[data-sortable] > li[data-nav-lifted]) {
button[type="submit"] {
justify-content: center;
padding: 0.375rem;
- color: #fff;
+ color: var(--on-accent);
background: var(--link);
}
}
diff --git a/services/site/src/component/site/open-source-fork.css b/services/site/src/component/site/open-source-fork.css
index 078d8d6b8723..72d617d12c52 100644
--- a/services/site/src/component/site/open-source-fork.css
+++ b/services/site/src/component/site/open-source-fork.css
@@ -11,9 +11,9 @@
/* Under the section body, across the content columns: the terminal takes two cards and the points
the rest. Stacked sections (phones) put the points under the terminal. */
[data-page="home"][data-site] [data-component="oss-fork"] {
- --terminal-bg: hsl(0, 0%, 8%);
- --terminal-text: hsl(0, 0%, 86%);
- --terminal-dim: hsl(0, 0%, 56%);
+ --terminal-bg: var(--fixed-dark-raised);
+ --terminal-text: #dbdbdb;
+ --terminal-dim: var(--fixed-dark-weak);
grid-column: 2 / -1;
display: grid;
@@ -48,7 +48,7 @@
height: 2.25rem;
padding-block: 0;
padding-inline: 1rem 0.5rem;
- border-bottom: 1px solid hsl(0, 0%, 16%);
+ border-bottom: 1px solid var(--fixed-dark-line);
font-family: var(--font-mono);
font-size: var(--fs-micro);
color: var(--terminal-dim);
@@ -69,13 +69,13 @@
@media (hover: hover) and (pointer: fine) {
&:hover {
- background: hsl(0, 0%, 14%);
+ background: var(--fixed-dark-hover);
color: var(--terminal-text);
}
}
&:active {
- background: hsl(0, 0%, 14%);
+ background: var(--fixed-dark-hover);
color: var(--terminal-text);
}
@@ -113,7 +113,7 @@
}
[data-kind="comment"] {
- color: hsl(0, 0%, 44%);
+ color: var(--terminal-dim);
}
[data-kind="command"] + [data-kind="command"],
diff --git a/services/site/src/component/site/pair-panel.css b/services/site/src/component/site/pair-panel.css
index 614f910c2a3d..2ba1bd49c092 100644
--- a/services/site/src/component/site/pair-panel.css
+++ b/services/site/src/component/site/pair-panel.css
@@ -153,7 +153,7 @@
height: 100%;
object-fit: cover;
object-position: left top;
- background: #000;
+ background: var(--media-black);
}
}
@@ -162,8 +162,8 @@
margin: 0;
padding: 1rem;
overflow: hidden;
- background: #0a0a0a;
- color: #eeeeee;
+ background: var(--fixed-dark);
+ color: var(--fixed-dark-text);
font-family: var(--font-mono);
font-size: clamp(0.4rem, 0.55vw, 0.6rem);
line-height: 1.15;
@@ -179,29 +179,29 @@
max-width: 40rem;
padding: 1.5rem;
border-inline-start: 3px solid var(--link);
- background: #0c0c0c;
- color: #f2f2f2;
+ background: var(--fixed-dark);
+ color: var(--fixed-dark-text);
h3 {
- color: #fff;
+ color: var(--fixed-white);
}
[data-slot="intro"] {
- color: hsl(0, 0%, 78%);
+ color: var(--fixed-dark-muted);
}
[data-slot="command"] {
- border-color: hsl(0, 0%, 22%);
+ border-color: var(--fixed-dark-line);
code {
- color: #fff;
+ color: var(--fixed-white);
}
}
[data-slot="facts"] {
margin: 1rem 0 0;
padding-inline-start: 1.25rem;
- color: hsl(0, 0%, 72%);
+ color: var(--fixed-dark-muted);
font-size: var(--fs-small);
line-height: 1.5;
diff --git a/services/site/src/component/site/preload-settings.ts b/services/site/src/component/site/preload-settings.ts
index c345d662c71d..9c76f09fab24 100644
--- a/services/site/src/component/site/preload-settings.ts
+++ b/services/site/src/component/site/preload-settings.ts
@@ -68,7 +68,7 @@ const preloadRules: [string, string, (s: SiteSettings, el: HTMLElement, d: SiteS
],
["", "data-status-bars", (s) => s.statusBars],
["", "data-logo-menu-hover", (s) => s.logoMenuHover],
- ["", "data-light-bg", (s) => (s.lightBackground === "#ffffff" ? undefined : s.lightBackground.slice(1))],
+ ["", "data-light-bg", (s) => (s.lightBackground === "#fbfbfb" ? undefined : s.lightBackground.slice(1))],
["", "data-sidebar", (s) => (s.sidebar === "fifth column" ? "column" : undefined)],
['[data-slot="logo"]', "data-variant", (s) => s.logo],
// The architect print's label case; ?labels= on a legal page overrides it (legal.tsx).
diff --git a/services/site/src/component/site/product-list.css b/services/site/src/component/site/product-list.css
index 636b5d9d6c4e..9a5c1b451041 100644
--- a/services/site/src/component/site/product-list.css
+++ b/services/site/src/component/site/product-list.css
@@ -34,7 +34,7 @@
/* Square corners, like every other surface on the site. On the dark page every tile (Hex's
black icon too) gets a hairline edge, drawn over the artwork, so it doesn't vanish. */
border-radius: 0;
- outline: 1px solid light-dark(transparent, hsl(0, 0%, 26%));
+ outline: 1px solid light-dark(transparent, var(--border-strong));
outline-offset: -1px;
background: var(--bg-weaker);
font-family: var(--font-mono);
@@ -44,8 +44,8 @@
/* A blank tile (no icon yet) or a mark drawn in it: black on the light page; on the dark page a
lifted grey with a hairline edge, since black would vanish into the background. */
&:is([data-empty], [data-mark]) {
- background: light-dark(#000, hsl(0, 0%, 15%));
- color: #fff;
+ background: light-dark(var(--media-black), var(--bg-weaker));
+ color: var(--fixed-white);
}
/* The GitHub and GitLab marks, white in the tile. */
@@ -56,7 +56,7 @@
/* Black behind a product's own icon, so its rounded corners fill out to the square tile. */
&:has(img) {
- background: #000;
+ background: var(--media-black);
}
img {
diff --git a/services/site/src/component/site/product-page.css b/services/site/src/component/site/product-page.css
index c66aa1502980..64a15d938c4c 100644
--- a/services/site/src/component/site/product-page.css
+++ b/services/site/src/component/site/product-page.css
@@ -144,8 +144,10 @@
display: grid;
place-items: center;
overflow: hidden;
- /* The heroes' own backdrop in each theme (videos.ts), so the box matches them before they load. */
+ /* The heroes' own backdrop in each theme (videos.ts), so the box matches them before they load.
+ grey-ok: matches the encoded video backdrop */
background: light-dark(#161616, #1e1e1e);
+ /* grey-ok-end */
video,
img {
@@ -167,7 +169,7 @@
width: 2rem;
height: 2rem;
padding: 0;
- color: #fff;
+ color: var(--fixed-white);
background: rgb(0 0 0 / 0.6);
opacity: 0.8;
@@ -197,14 +199,16 @@
/* No real footage yet: plain black in both themes, with a hairline edge on the dark page so the
box still reads against the near-black background. */
[data-component="product-hero"][data-empty] {
- background: #000;
- box-shadow: inset 0 0 0 1px light-dark(transparent, hsl(0, 0%, 20%));
+ background: var(--media-black);
+ box-shadow: inset 0 0 0 1px light-dark(transparent, var(--border));
}
/* The phone recording has its own near-black backdrop, which fills the hero edge to edge in both
themes (edits/hero-mobile-*.json): the box matches it before the poster paints. */
[data-component="product-hero"][data-product="mobile"] {
+ /* grey-ok: matches the encoded video backdrop */
background: #0a0a0a;
+ /* grey-ok-end */
}
[data-component="product-hero"][data-product="sdk"] {
@@ -216,14 +220,14 @@
font-size: clamp(0.75rem, 2.2cqw, 1.5rem);
line-height: 1.55;
white-space: pre;
- color: #eeeeee;
+ color: var(--fixed-dark-text);
}
}
[data-slot="caption"] {
font-family: var(--font-mono);
font-size: var(--fs-meta);
- color: #808080;
+ color: var(--fixed-dark-weak);
}
/* Title and description across three columns, the main action at the right edge. */
@@ -488,7 +492,7 @@
[data-slot="media"] {
aspect-ratio: 16 / 10;
- background: #0a0a0a;
+ background: var(--fixed-dark);
position: relative;
overflow: hidden;
diff --git a/services/site/src/component/site/products.css b/services/site/src/component/site/products.css
index d216a1e33ba0..0735a96cbfa3 100644
--- a/services/site/src/component/site/products.css
+++ b/services/site/src/component/site/products.css
@@ -76,7 +76,7 @@
[data-component="products"]:not([data-layout="grid"])
[data-component="product-card"]
[data-component="site-button"]:not([aria-disabled="true"]):active {
- background: hsl(0, 0%, 84%);
+ background: var(--fixed-light-press);
}
}
@@ -247,8 +247,8 @@
line-height: 1.5;
text-transform: uppercase;
letter-spacing: 0.06em;
- background: #fff;
- color: hsl(0, 0%, 8%);
+ background: var(--fixed-white);
+ color: var(--fixed-ink);
}
[data-product="terminal"],
@@ -274,7 +274,7 @@
font-size: calc((100cqw - 3rem) / 32 / 0.6);
line-height: 1.55;
white-space: pre;
- color: #eeeeee;
+ color: var(--fixed-dark-text);
}
h3 {
@@ -427,7 +427,8 @@
}
}
- /* OpenCode dark theme syntax colors for the SDK snippet, in the card and on its page. */
+ /* OpenCode dark theme syntax colors for the SDK snippet, in the card and on its page.
+ grey-ok: the OpenCode theme's own syntax colours */
[data-product="sdk"] [data-slot="code"] {
[data-c] {
color: #808080;
@@ -457,13 +458,14 @@
color: #eeeeee;
}
}
+ /* grey-ok-end */
}
/* A store that is coming soon (the status flag in product-data.ts), in a menu or a sheet: grey and
inert like a disabled button, and still focusable, so keyboard focus keeps its tint. */
[data-site] [data-component="site-menu"] [data-slot="menu"] > [data-slot="store"][aria-disabled="true"],
[data-component="sheet"][data-sheet="product"] [data-slot="row"][aria-disabled="true"] {
- color: light-dark(hsl(0, 0%, 60%), hsl(0, 0%, 36%));
+ color: var(--text-disabled);
cursor: not-allowed;
&:not(:focus-visible) {
@@ -609,7 +611,7 @@
/* The covers' own flat backdrop (#161616 as browsers decode it) once the resting frame has
painted, so the space the moved cover leaves blends in; the tone stays until then. */
&:has(img[data-poster][data-loaded]) {
- background: #161616;
+ background: var(--card-media-bg);
}
/* The resting cover's subject (wordmark and prompt, orb, terminal, code) is centred in its
@@ -622,7 +624,7 @@
transform: translateY(round(-10cqw, 1px));
/* The backdrop below the moved frame, part of the layer, so it covers the hover video's
poster underneath and fades out with the cover when the hover cut plays. */
- box-shadow: 0 0 0 200cqw #161616;
+ box-shadow: 0 0 0 200cqw var(--card-media-bg);
}
/* The sizzle reel (the hover video, which plays by itself on phones) moves up too, by what
@@ -631,7 +633,7 @@
below, under the darkest part of the gradient. */
> video:not([data-slot]) {
transform: translateY(round(var(--reel-shift), 1px));
- box-shadow: 0 0 0 200cqw #161616;
+ box-shadow: 0 0 0 200cqw var(--card-media-bg);
}
&[data-product="desktop"] {
diff --git a/services/site/src/component/site/site.css b/services/site/src/component/site/site.css
index c11b757e0b45..dd52456b124b 100644
--- a/services/site/src/component/site/site.css
+++ b/services/site/src/component/site/site.css
@@ -5,11 +5,13 @@
}
/* The page behind the site (seen when you pull past the top or bottom) follows the site's
- theme, not the system one. */
+ theme, not the system one. The page step of the scale (--grey-1), written out because the tokens
+ live on [data-site], inside this element. grey-ok: outside the tokens' scope */
html:has([data-site]) {
color-scheme: light dark;
- background-color: light-dark(#fff, #0c0c0c);
+ background-color: light-dark(#fbfbfb, #0c0c0c);
}
+/* grey-ok-end */
html:has([data-site][data-theme="light"]) {
color-scheme: light;
@@ -51,46 +53,81 @@ html:has([data-site][data-theme="dark"]) {
/* Dark matches the Console landing page (#0c0c0c). */
/* Light follows Settings โบ Light background (pure white unless set). */
- --bg: light-dark(#fff, #0c0c0c);
- --bg-weak: light-dark(hsl(0, 0%, 96%), hsl(0, 0%, 10%));
+ /* The shared neutral scale (script/check-greys.ts keeps every stylesheet on it). A step is a
+ role, and the same step does the same job in light and dark: 1 page, 2 raised surfaces, 3 subtle
+ fills, 4 hover, 5 borders and press, 6 strong borders and decoration, 7 marks at 3:1, 8 muted
+ text at 4.5:1 on steps 1 to 4, 9 body text, 10 emphasis, 11 ink. Data, Console and Status use
+ the same values. Components use the role tokens below, never a step or a raw grey. */
+ --grey-1: light-dark(#fbfbfb, #0c0c0c);
+ --grey-2: light-dark(#ffffff, #161616);
+ --grey-3: light-dark(#f5f5f5, #1a1a1a);
+ --grey-4: light-dark(#eeeeee, #242424);
+ --grey-5: light-dark(#e0e0e0, #2e2e2e);
+ --grey-6: light-dark(#d2d2d2, #4b4b4b);
+ --grey-7: light-dark(#888888, #6a6a6a);
+ --grey-8: light-dark(#6b6b6b, #8f8f8f);
+ --grey-9: light-dark(#5c5c5c, #aeaeae);
+ --grey-10: light-dark(#3a3a3a, #dbdbdb);
+ --grey-11: light-dark(#161616, #fafafa);
+ /* Surfaces that keep one look in both themes: the dark and light tiles behind logos, media and
+ terminals, pure black behind video (letterboxing must match the frames), and white text on the
+ link blue or on images. */
+ --fixed-dark: #0c0c0c;
+ --fixed-dark-raised: #161616;
+ --fixed-dark-hover: #242424;
+ --fixed-dark-line: #2e2e2e;
+ --fixed-dark-line-strong: #4b4b4b;
+ --fixed-dark-weak: #8f8f8f;
+ --fixed-dark-muted: #aeaeae;
+ --fixed-dark-text: #fafafa;
+ --fixed-light: #f5f5f5;
+ --fixed-light-press: #d2d2d2;
+ --fixed-white: #ffffff;
+ --fixed-ink: #161616;
+ --media-black: #000000;
+ --on-accent: #ffffff;
+
+ --bg: var(--grey-1);
+ --bg-weak: var(--grey-3);
/* A pressed full-width row on phones (the docs' sticky rows, the Contents list, the DOCS menu): a
subtle surface tint, lighter than the chevrons' and menus' press fills. */
--row-press: var(--bg-weak);
/* The product cards' media backdrop (products.css), which their covers and reels are graded to in
both themes. */
- --card-media-bg: #161616;
+ --card-media-bg: var(--fixed-dark-raised);
/* The document rows' model (doc-list.css, and the product lists in product-list.css): a row's text
on the content edge with this padding outside it, so the hover fill and the bar at its start
edge bleed past the edge. */
--doc-row-pad: 1rem;
--doc-row-fill: var(--bg-weak);
- --doc-row-bar: light-dark(hsl(0, 0%, 50%), hsl(0, 0%, 46%));
- /* The home Console band (routes/index.css), dark in both themes: the panel grey in light, and in
- dark #121212, a muted step above the #0c0c0c page so it reads as a band, not a slab. A registered
- colour, so light-dark() resolves in the page's scheme here and not in the band's own forced-dark
- one. */
- --console-band-bg: light-dark(hsl(0, 0%, 10%), #121212);
- --bg-weaker: light-dark(hsl(0, 0%, 92%), hsl(0, 0%, 14%));
- --bg-strong: light-dark(hsl(0, 0%, 8%), hsl(0, 0%, 95%));
- --bg-strong-hover: light-dark(hsl(0, 0%, 20%), hsl(0, 0%, 82%));
- --text-strong: light-dark(hsl(0, 0%, 8%), hsl(0, 0%, 95%));
- --text: light-dark(hsl(0, 0%, 32%), hsl(0, 0%, 72%));
+ --doc-row-bar: var(--grey-7);
+ /* The home Console band (routes/index.css), dark in both themes: the subtle fill's dark step in
+ both, a step above the dark page so it reads as a band, not a slab. A registered colour, so
+ light-dark() resolves in the page's scheme here and not in the band's own forced-dark one. */
+ --console-band-bg: #1a1a1a;
+ --bg-weaker: var(--grey-4);
+ --bg-strong: var(--grey-11);
+ --bg-strong-hover: var(--grey-10);
+ --text-strong: var(--grey-11);
+ --text: var(--grey-9);
/* At least 4.5:1 on --bg-weaker too, so secondary text passes WCAG AA on raised surfaces. */
- --text-weak: light-dark(hsl(0, 0%, 40%), hsl(0, 0%, 56%));
- /* Muted labels that still carry meaning: the lightest grey with 4.5:1 on every light page
- background (#fbfbfb to #ffffff) and on dark. --text-weaker and below are for decoration only. */
- --text-muted: light-dark(hsl(0, 0%, 45%), hsl(0, 0%, 49%));
+ --text-weak: var(--grey-8);
+ /* Muted labels that still carry meaning: 4.5:1 on every page background and on hover fills, in
+ light and dark. The same step as --text-weak. --text-weaker and below are for decoration only. */
+ --text-muted: var(--grey-8);
/* Quiet marks that still need to be seen, like the nav's [01] shortcuts: 3:1 on the light page
backgrounds and on dark (WCAG 1.4.11). */
- --text-faint: light-dark(hsl(0, 0%, 55%), hsl(0, 0%, 38%));
+ --text-faint: var(--grey-7);
+ /* Switched-off controls and items: about 3:1, legible though WCAG exempts it. */
+ --text-disabled: var(--grey-7);
/* The nav's markers: the sidebar's "[1]" shortcuts and the footer's "[ ]" boxes share it, so they
always match. */
--nav-marker: var(--text-faint);
- --text-weaker: light-dark(hsl(0, 0%, 72%), hsl(0, 0%, 32%));
- --text-weakest: light-dark(hsl(0, 0%, 83%), hsl(0, 0%, 23%));
- --text-inverted: light-dark(hsl(0, 0%, 100%), #0c0c0c);
- --border: light-dark(hsl(0, 0%, 88%), hsl(0, 0%, 18%));
- --border-strong: light-dark(hsl(0, 0%, 78%), hsl(0, 0%, 28%));
+ --text-weaker: var(--grey-6);
+ --text-weakest: var(--grey-6);
+ --text-inverted: light-dark(#ffffff, #0c0c0c);
+ --border: var(--grey-5);
+ --border-strong: var(--grey-6);
/* The OpenCode Console accent blue; dark mode uses a lighter blue from Settings โบ Dark blue. */
--link-dark: #4f8bff;
--link: light-dark(#3b5cf6, var(--link-dark));
@@ -98,9 +135,9 @@ html:has([data-site][data-theme="dark"]) {
--status-degraded: light-dark(hsl(38, 92%, 48%), hsl(40, 90%, 58%));
--status-outage: light-dark(hsl(0, 72%, 50%), hsl(0, 80%, 64%));
--link-visited: light-dark(#6a4fd6, var(--link-dark));
- --popover-bg: light-dark(hsl(0, 0%, 100%), hsl(0, 0%, 10%));
+ --popover-bg: var(--grey-2);
/* Secondary text in pop-ups: at least 5.5:1 on the pop-up background (WCAG AA is 4.5:1). */
- --popover-text-weak: light-dark(hsl(0, 0%, 40%), hsl(0, 0%, 64%));
+ --popover-text-weak: var(--grey-9);
/* A 1px ring instead of a border, plus tight layered shadows. */
--popover-shadow:
0 0 0 1px light-dark(rgb(0 0 0 / 0.1), rgb(255 255 255 / 0.1)),
@@ -728,8 +765,8 @@ html:has([data-site][data-theme="dark"]) {
specific. aria-disabled buttons stay focusable, so they keep the keyboard focus ring (WCAG 2.4.7),
and their click handlers must check aria-disabled themselves. */
[data-component="site-button"]:is(:disabled, [aria-disabled="true"]) {
- --button-disabled-text: light-dark(hsl(0, 0%, 60%), hsl(0, 0%, 36%));
- --button-disabled-line: light-dark(hsl(0, 0%, 84%), hsl(0, 0%, 22%));
+ --button-disabled-text: var(--text-disabled);
+ --button-disabled-line: var(--grey-6);
background: transparent !important;
color: var(--button-disabled-text) !important;
box-shadow: inset 0 0 0 1px var(--button-disabled-line);
@@ -1607,11 +1644,11 @@ html:has([data-site][data-theme="dark"]) {
menu; the active bar stays clearly darker than the hover bar (light 40% vs 66%, dark 62% vs
34%), and text on the tint keeps well over 4.5:1. "blue" swaps the tints and the hover bar for
the link blue. Unregistered, so light-dark() resolves in each pop-up's own scheme. */
- --menu-hover: light-dark(hsl(0, 0%, 94.5%), hsl(0, 0%, 13.5%));
- --menu-press: light-dark(hsl(0, 0%, 91%), hsl(0, 0%, 17%));
+ --menu-hover: var(--grey-4);
+ --menu-press: var(--grey-5);
--menu-open: var(--menu-hover);
- --menu-hint: light-dark(hsl(0, 0%, 66%), hsl(0, 0%, 34%));
- --menu-bar: light-dark(hsl(0, 0%, 40%), hsl(0, 0%, 62%));
+ --menu-hint: var(--grey-7);
+ --menu-bar: var(--grey-9);
&[data-menu-color="blue"] {
/* Dark pop-ups need a stronger mix for the wash to read as blue rather than navy. */
@@ -2768,7 +2805,7 @@ html:has([data-site][data-theme="dark"]) {
keeping its own colour. */
[data-site] ::selection {
background: var(--link);
- color: #fff;
+ color: var(--on-accent);
}
[data-site][data-selection="muted"] ::selection {
@@ -3870,14 +3907,15 @@ html:has([data-site][data-theme="dark"]) {
}
}
-/* Settings โบ Light background: the off-white options. Pure white is the default. The page behind
- the site follows, so pulling past the top or bottom shows the same colour. */
-[data-site][data-light-bg="fbfbfb"] {
- --bg: light-dark(#fbfbfb, #0c0c0c);
+/* Settings โบ Light background: the other light page colours. The default is the scale's page step
+ (--grey-1). The page behind the site follows, so pulling past the top or bottom shows the same
+ colour. grey-ok: Settings options, a development tool */
+[data-site][data-light-bg="ffffff"] {
+ --bg: light-dark(#ffffff, #0c0c0c);
}
-html:has([data-site][data-light-bg="fbfbfb"]) {
- background-color: light-dark(#fbfbfb, #0c0c0c);
+html:has([data-site][data-light-bg="ffffff"]) {
+ background-color: light-dark(#ffffff, #0c0c0c);
}
[data-site][data-light-bg="fcfcfc"] {
@@ -3903,6 +3941,7 @@ html:has([data-site][data-light-bg="fdfdfd"]) {
html:has([data-site][data-light-bg="fefefe"]) {
background-color: light-dark(#fefefe, #0c0c0c);
}
+/* grey-ok-end */
/* Footer links that leave the site (Community) get the nav's corner arrow, revealed on hover. */
[data-site] [data-component="footer-columns"] a:has([data-slot="external"]) {
@@ -4164,7 +4203,7 @@ html [data-site][data-nav-numbers="1"][data-status-bars="6"] {
[data-site]:is([data-button-hover="blue"], [data-button-hover="blue-ring"])
[data-component="site-button"]:not([data-variant="neutral"]):hover {
background: var(--link);
- color: #fff;
+ color: var(--on-accent);
}
[data-site][data-button-hover="blue"] [data-component="site-button"]:hover {
@@ -4184,7 +4223,7 @@ html [data-site][data-nav-numbers="1"][data-status-bars="6"] {
[data-site]:is([data-button-hover="blue"], [data-button-hover="blue-ring"])
[data-component="site-button"][aria-expanded="true"]:not([data-variant="neutral"]) {
background: var(--link);
- color: #fff;
+ color: var(--on-accent);
}
[data-site][data-button-hover="blue"] [data-component="site-button"][aria-expanded="true"]:not(:focus-visible) {
@@ -4224,7 +4263,7 @@ html [data-site][data-nav-numbers="1"][data-status-bars="6"] {
[data-site]:is([data-button-hover="blue"], [data-button-hover="blue-ring"])
&[data-slot="split-toggle"][aria-expanded="true"] {
background: var(--link);
- color: #fff;
+ color: var(--on-accent);
}
@media (hover: hover) and (pointer: fine) {
diff --git a/services/site/src/component/site/site.tsx b/services/site/src/component/site/site.tsx
index d9553ebfe96d..b63efeb54453 100644
--- a/services/site/src/component/site/site.tsx
+++ b/services/site/src/component/site/site.tsx
@@ -1235,7 +1235,7 @@ export function Site(props: {
}
data-status-bars={siteSettings.statusBars}
data-logo-menu-hover={siteSettings.logoMenuHover}
- data-light-bg={siteSettings.lightBackground === "#ffffff" ? undefined : siteSettings.lightBackground.slice(1)}
+ data-light-bg={siteSettings.lightBackground === "#fbfbfb" ? undefined : siteSettings.lightBackground.slice(1)}
data-sidebar={siteSettings.sidebar === "fifth column" ? "column" : undefined}
data-layout={props.aside ? "docs" : undefined}
data-bare={props.bare ? "" : undefined}
diff --git a/services/site/src/component/site/voice/orb.css b/services/site/src/component/site/voice/orb.css
index 524fecf892e0..6e61ca438e5a 100644
--- a/services/site/src/component/site/voice/orb.css
+++ b/services/site/src/component/site/voice/orb.css
@@ -79,7 +79,7 @@
width: 16px;
height: 16px;
translate: -50% -50%;
- color: #fff;
+ color: var(--fixed-white);
opacity: 0;
pointer-events: none;
filter: drop-shadow(0 1px 2px rgb(0 0 0 / 0.5));
@@ -171,7 +171,7 @@
height: var(--disc);
translate: -50% -50%;
border-radius: 50%;
- background: light-dark(#000, #0f0f0f);
+ background: light-dark(var(--media-black), var(--fixed-dark));
box-shadow:
inset 0 0 0 1px light-dark(transparent, rgb(255 255 255 / 0.14)),
0 1px 2px light-dark(rgb(0 0 0 / calc(0.12 * var(--shadow))), rgb(0 0 0 / calc(0.7 * var(--shadow)))),
diff --git a/services/site/src/component/site/voice/voice-mode.css b/services/site/src/component/site/voice/voice-mode.css
index 7a86c273de63..300ad65afef9 100644
--- a/services/site/src/component/site/voice/voice-mode.css
+++ b/services/site/src/component/site/voice/voice-mode.css
@@ -359,8 +359,8 @@
grid-row: span 2;
/* Square like the product list tiles: black behind Hex's rounded artwork fills the corners. */
border-radius: 0;
- background: #000;
- outline: 1px solid light-dark(transparent, hsl(0, 0%, 26%));
+ background: var(--media-black);
+ outline: 1px solid light-dark(transparent, var(--border-strong));
outline-offset: -1px;
filter: grayscale(1);
}
@@ -558,8 +558,8 @@
place-items: center;
width: 28px;
height: 28px;
- background: #000;
- color: #fff;
+ background: var(--media-black);
+ color: var(--fixed-white);
svg {
width: 15px;
diff --git a/services/site/src/docs/styles/docs.css b/services/site/src/docs/styles/docs.css
index f424a0dfccdb..73b7bda6af78 100644
--- a/services/site/src/docs/styles/docs.css
+++ b/services/site/src/docs/styles/docs.css
@@ -769,7 +769,7 @@
have it on the screen's bottom edge instead (below). */
[data-site] [data-component="docs-version-notice"][data-placement="header"] {
/* The link's grey: 6.6:1 on the light theme's bar, 6.1:1 on the dark theme's. */
- --notice-muted: hsl(0, 0%, 64%);
+ --notice-muted: var(--fixed-dark-muted);
--notice-text: light-dark(var(--text-inverted), var(--text-strong));
position: fixed;
z-index: 7;
@@ -793,7 +793,7 @@
translate: 0 -50%;
margin: 0;
white-space: nowrap;
- background: light-dark(var(--bg-strong), hsl(0, 0%, 13%));
+ background: light-dark(var(--bg-strong), var(--bg-weaker));
box-shadow: inset 0 0 0 1px light-dark(transparent, var(--border-strong));
border-color: transparent;
color: var(--notice-text);
@@ -925,9 +925,11 @@
one dark area; the top still takes the top bar's page colour. The page ends above the bar, so the
footer stays reachable. Open menus and sheets sit over it. */
@media (max-width: 60rem) {
+ /* The bar's colours, written out because the tokens live inside this element. grey-ok: outside the tokens' scope */
html:has([data-component="docs-version-notice"][data-placement="header"]) {
- background: light-dark(hsl(0, 0%, 8%), hsl(0, 0%, 13%));
+ background: light-dark(#161616, #242424);
}
+ /* grey-ok-end */
[data-site]:has([data-component="docs-version-notice"][data-placement="header"]) {
padding-bottom: calc(3rem + env(safe-area-inset-bottom, 0px));
diff --git a/services/site/src/routes/brand/index.css b/services/site/src/routes/brand/index.css
index db18df901901..ed110d5042c0 100644
--- a/services/site/src/routes/brand/index.css
+++ b/services/site/src/routes/brand/index.css
@@ -71,7 +71,7 @@
theme instead of the tile's. */
&[data-tone="light"] {
color-scheme: only light;
- background: #f5f5f5;
+ background: var(--fixed-light);
--logo-code: #1f1f1f;
--logo-open: #626262;
--logo-inner: #d2d2d2;
@@ -79,7 +79,7 @@
&[data-tone="dark"] {
color-scheme: only dark;
- background: #0a0a0a;
+ background: var(--fixed-dark);
box-shadow: inset 0 0 0 1px var(--border);
--logo-code: #eeeeee;
--logo-open: #aeaeae;
@@ -355,7 +355,7 @@
> [data-variant="split"]
[data-slot="chevron-button"][aria-expanded="true"] {
background: var(--link);
- color: #fff;
+ color: var(--on-accent);
}
/* Icons: square buttons, named by their tooltips and labels. */
@@ -931,7 +931,7 @@
[data-slot="preview"] {
&[data-variant="standard"][data-tone="light"] {
- background: #f4f4f4;
+ background: var(--fixed-light);
}
/* Photo-like multicolor backgrounds: wide, heavily blurred color fields (the last listed field
@@ -1219,14 +1219,16 @@
&[data-tone="light"] {
color-scheme: only light;
- background: #f4f4f4;
+ background: var(--fixed-light);
--size-muted: #6b6b6b;
+ /* grey-ok: the logo's ink */
--size-strong: #1f1f1f;
+ /* grey-ok-end */
}
&[data-tone="dark"] {
color-scheme: only dark;
- background: #0a0a0a;
+ background: var(--fixed-dark);
box-shadow: inset 0 0 0 1px var(--border);
--size-muted: #8f8f8f;
--size-strong: #eeeeee;
@@ -1240,7 +1242,7 @@
/* Cells: the tiles step away from the badge's grey cells (#eeeeee, #1f1f1f) so the cell edges
and the gap between them read. */
- /* White, so a faint inset edge shows where the tile ends. */
+ /* White, so a faint inset edge shows where the tile ends. grey-ok: the badge's own cell colours */
&[data-badge="c"][data-tone="light"] {
background: #ffffff;
box-shadow: inset 0 0 0 1px rgb(0 0 0 / 0.1);
@@ -1252,6 +1254,7 @@
--size-muted: #d0d0d0;
--size-strong: #ffffff;
}
+ /* grey-ok-end */
}
/* The size switcher: plain mono text in the tile's top-left corner, shown while the tile is
@@ -1394,9 +1397,11 @@
height: 28px;
}
+ /* grey-ok: a deliberately wrong example */
&[data-example="low-contrast"] {
background: #b0b0b0;
}
+ /* grey-ok-end */
&[data-example="color"] {
background: var(--brand-dark-2);
diff --git a/services/site/src/routes/font/index.css b/services/site/src/routes/font/index.css
index 0dc63ba0486b..2b5d7c50703a 100644
--- a/services/site/src/routes/font/index.css
+++ b/services/site/src/routes/font/index.css
@@ -53,7 +53,8 @@
/* No backing behind the logo: over a dark or light surface it takes that scheme's artwork
instead (surface.ts, github-link.css). That artwork is the brand's transparent logo
(public/brand/files/opencode-logo-transparent-*.svg): the ink at 20% (light) or 28% (dark)
- for the inner square and 70% / 72% for the open letters, so they tint with what is behind. */
+ for the inner square and 70% / 72% for the open letters, so they tint with what is behind.
+ grey-ok: the brand's logo artwork */
[data-slot="logo"] {
[data-slot="inner"] {
fill: light-dark(rgb(31 31 31 / 0.2), rgb(238 238 238 / 0.28));
@@ -63,6 +64,7 @@
fill: light-dark(rgb(31 31 31 / 0.7), rgb(238 238 238 / 0.72));
}
}
+ /* grey-ok-end */
[data-slot="bare-theme"] {
position: fixed;
@@ -2122,6 +2124,7 @@
border: 1px solid currentColor;
}
+ /* grey-ok: the specimen's printed paper, ink and shade */
[data-swatch="paper"] {
background: light-dark(var(--bg), #fff);
}
@@ -2137,6 +2140,7 @@
[data-swatch="shade"] {
background: #cecece;
}
+ /* grey-ok-end */
[data-anno] {
margin-left: 1rem;
@@ -2297,9 +2301,9 @@
--link: var(--link-dark);
--glyph-ink: #fff;
--shade-alpha: 30%;
- --text-weak: hsl(0, 0%, 62%);
- background: #0c0c0c;
- color: hsl(0, 0%, 95%);
+ --text-weak: var(--fixed-dark-muted);
+ background: var(--fixed-dark);
+ color: var(--fixed-dark-text);
border-top: 1px solid hsl(0 0% 100% / 0.12);
}
@@ -2350,10 +2354,10 @@
inset: 0;
border-radius: 50%;
background:
- linear-gradient(#fff, #fff) center top / 1px 38% no-repeat,
- linear-gradient(#fff, #fff) center bottom / 1px 38% no-repeat,
- linear-gradient(#fff, #fff) left center / 38% 1px no-repeat,
- linear-gradient(#fff, #fff) right center / 38% 1px no-repeat;
+ linear-gradient(var(--fixed-white), var(--fixed-white)) center top / 1px 38% no-repeat,
+ linear-gradient(var(--fixed-white), var(--fixed-white)) center bottom / 1px 38% no-repeat,
+ linear-gradient(var(--fixed-white), var(--fixed-white)) left center / 38% 1px no-repeat,
+ linear-gradient(var(--fixed-white), var(--fixed-white)) right center / 38% 1px no-repeat;
opacity: 0.35;
}
@@ -2364,7 +2368,7 @@
transform: translateX(-50%);
padding: 0.125rem 0.375rem;
background: #3b5cf6;
- color: #fff;
+ color: var(--on-accent);
white-space: nowrap;
}
@@ -2594,7 +2598,7 @@
height: 100svh;
padding: var(--story-top) var(--pad) 0;
background: var(--universe-blue);
- color: #fff;
+ color: var(--on-accent);
overflow: hidden;
@media (max-width: 40rem) {
@@ -2745,7 +2749,7 @@
margin-inline: calc(-1 * var(--pad));
padding: 2rem var(--pad) clamp(5rem, 10vw, 9rem);
background: var(--universe-blue);
- color: #fff;
+ color: var(--on-accent);
}
[data-slot="universe-working"] {
diff --git a/services/site/src/routes/index.css b/services/site/src/routes/index.css
index 2cd8267563fa..9f072a12a43c 100644
--- a/services/site/src/routes/index.css
+++ b/services/site/src/routes/index.css
@@ -194,7 +194,7 @@
align-items: center;
padding: 1px 0.75rem 0;
background: light-dark(var(--link), color-mix(in srgb, var(--link) 65%, #000));
- color: #fff;
+ color: var(--on-accent);
font-weight: 700;
text-transform: uppercase;
}
@@ -288,7 +288,7 @@
&[data-style="chip"] [data-slot="new"] {
padding: 4px 8px;
background: light-dark(var(--link), color-mix(in srgb, var(--link) 65%, #000));
- color: #fff;
+ color: var(--on-accent);
line-height: 1;
}
diff --git a/services/site/src/routes/legal/legal.css b/services/site/src/routes/legal/legal.css
index 3f9e4839d529..3770ed2b0ed1 100644
--- a/services/site/src/routes/legal/legal.css
+++ b/services/site/src/routes/legal/legal.css
@@ -672,7 +672,7 @@
/* Print and Save as PDF: only the document. The site's sidebars, menus, corner controls and the
page's own buttons go; the text prints black on white at a book size, and each link prints its
- address after it. */
+ address after it. grey-ok: print, black on white whatever the theme */
@media print {
@page {
margin: 18mm 16mm;
@@ -773,6 +773,7 @@
}
}
}
+ /* grey-ok-end */
}
/* A document's title is a page title, the size docs and product pages use. The repeated attribute
diff --git a/services/site/src/routes/press/index.css b/services/site/src/routes/press/index.css
index eb8b22a87098..1d67786a75e1 100644
--- a/services/site/src/routes/press/index.css
+++ b/services/site/src/routes/press/index.css
@@ -89,7 +89,7 @@
bottom: 0;
inset-inline-start: 0;
width: 2px;
- background: light-dark(hsl(0, 0%, 50%), hsl(0, 0%, 46%));
+ background: var(--doc-row-bar);
opacity: 0;
transition: opacity 150ms ease;
}
@@ -836,11 +836,11 @@
aspect-ratio: 2 / 1;
&[data-tone="light"] {
- background: #f5f5f5;
+ background: var(--fixed-light);
}
&[data-tone="dark"] {
- background: #0a0a0a;
+ background: var(--fixed-dark);
box-shadow: inset 0 0 0 1px var(--border);
}
diff --git a/services/site/src/routes/press/media-gallery.css b/services/site/src/routes/press/media-gallery.css
index 02e3383fff0e..252870e454d0 100644
--- a/services/site/src/routes/press/media-gallery.css
+++ b/services/site/src/routes/press/media-gallery.css
@@ -80,7 +80,7 @@
width: 1.5rem;
height: 1.5rem;
background: rgb(0 0 0 / 0.7);
- color: #fff;
+ color: var(--fixed-white);
}
/* "products" (default): the four products side by side in the page's columns (2 ร 2 at medium
@@ -383,7 +383,7 @@
background: rgb(0 0 0 / 0.7);
font-family: var(--font-mono);
font-size: var(--fs-meta);
- color: #fff;
+ color: var(--fixed-white);
}
[data-slot="strip"] {
@@ -598,7 +598,7 @@
width: auto;
height: auto;
object-fit: contain;
- background: #0a0a0a;
+ background: var(--fixed-dark);
pointer-events: auto;
}
}
@@ -616,11 +616,11 @@
gap: 1rem;
font-family: var(--font-mono);
font-size: var(--mono-size);
- color: #fff;
+ color: var(--fixed-white);
}
[data-slot="counter"] {
- color: hsl(0, 0%, 64%);
+ color: var(--fixed-dark-muted);
}
[data-slot="actions"] {
diff --git a/services/site/src/routes/product/index.css b/services/site/src/routes/product/index.css
index 9feeeac4ca29..12d963641669 100644
--- a/services/site/src/routes/product/index.css
+++ b/services/site/src/routes/product/index.css
@@ -18,7 +18,7 @@
/* No real footage yet: plain black in both themes. */
[data-slot="media"][data-empty] {
- background: #000;
+ background: var(--media-black);
}
@media (max-width: 39.9375rem) {
From fd6a1167b4e196b313a233bf04f5c73630dd2a3d Mon Sep 17 00:00:00 2001
From: James Long
Date: Thu, 12 Nov 2026 15:09:20 -0600
Subject: [PATCH 14/42] fix(tui): give shell mode its own prompt color under
new designs (#63605)
---
packages/tui/src/component/prompt/index.tsx | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx
index f89ff5d63097..03d758467076 100644
--- a/packages/tui/src/component/prompt/index.tsx
+++ b/packages/tui/src/component/prompt/index.tsx
@@ -48,7 +48,7 @@ import { useConnected } from "../use-connected"
import { useToast } from "../../ui/toast"
import { createFadeIn } from "../../util/signal"
import { DialogSkill } from "../dialog-skill"
-import { useConfig, useCursorStyle } from "../../config"
+import { useConfig, useCursorStyle, useNewDesigns } from "../../config"
import { usePromptMove } from "./move"
import { promptFilesForServer, resolvePastedAttachments } from "./local-attachment"
import { locationKey, useData } from "../../context/data"
@@ -218,6 +218,7 @@ export function Prompt(props: PromptProps) {
const exit = useExit()
const dimensions = useTerminalDimensions()
const theme = useTheme()
+ const newDesigns = useNewDesigns()
const { currentSyntax: syntax } = useThemes()
const animationsEnabled = createMemo(() => config.animations ?? true)
const list = createMemo(() => props.placeholders?.normal ?? [])
@@ -1583,7 +1584,9 @@ export function Prompt(props: PromptProps) {
})
const highlight = createMemo(() => {
if (muted()) return theme.border.base
- if (store.mode === "shell") return theme.text.action.primary.selected
+ if (store.mode === "shell")
+ // The new designs' interactive color matches the first agent's, so shell takes the second categorical color.
+ return newDesigns() ? (theme.categorical[1] ?? theme.categorical[0])[400] : theme.text.action.primary.selected
return promptDisplay().agentColor ?? theme.border.base
})
const agentLabel = createMemo(() => (store.mode === "shell" ? "Shell" : promptDisplay().agentLabel))
From f179e6e5f0b5fcb51ba95713e5d1c4dbcce4dcf6 Mon Sep 17 00:00:00 2001
From: Adam <2363879+adamdotdevin@users.noreply.github.com>
Date: Thu, 12 Nov 2026 15:17:44 -0600
Subject: [PATCH 15/42] fix(tui): drop tool-result image bytes from the
transcript store unless image previews are on (#63577)
Co-authored-by: Aiden Cline
---
packages/client/src/solid/data.ts | 86 ++++++--
packages/client/test/solid-data.test.ts | 237 +++++++++++++++++++++-
packages/tui/src/context/data.tsx | 16 ++
packages/tui/src/routes/session/index.tsx | 3 +-
4 files changed, 324 insertions(+), 18 deletions(-)
diff --git a/packages/client/src/solid/data.ts b/packages/client/src/solid/data.ts
index a1c8805bc269..8b6d247dc965 100644
--- a/packages/client/src/solid/data.ts
+++ b/packages/client/src/solid/data.ts
@@ -84,9 +84,10 @@ export type CreateDataInput = {
readonly onError?: (error: unknown) => void
/**
* Drops the payload of inline `data:` files in tool results before they enter the store. For clients that never
- * render tool-result files: a session full of screenshots otherwise keeps hundreds of MB of base64 alive.
+ * render tool-result files: a session full of screenshots otherwise keeps hundreds of MB of base64 alive. A function
+ * is read for each message and event, so a client can follow a setting that changes while it runs.
*/
- readonly omitToolFileData?: boolean
+ readonly omitToolFileData?: boolean | (() => boolean)
}
const messagePageLimit = 20
@@ -182,8 +183,23 @@ function omitFileData(content: [ToolContent, ...ToolContent[]]): [ToolContent, .
return [omit(content[0]), ...content.slice(1).map(omit)]
}
+const hasFileData = (part: Extract["content"][number]) =>
+ part.type === "tool" &&
+ "content" in part.state &&
+ !!part.state.content?.some((item) => item.type === "file" && item.uri.startsWith("data:"))
+
+// A tool file whose `data:` payload `omitFileData` emptied.
+const isDroppedFile = (item: ToolContent) => item.type === "file" && item.uri === `data:${item.mime};base64,`
+
+const hasDroppedFileData = (message: SessionMessageInfo) =>
+ message.type === "assistant" &&
+ message.content.some(
+ (part) => part.type === "tool" && "content" in part.state && !!part.state.content?.some(isDroppedFile),
+ )
+
+// Returns the same message when there is nothing to drop, so the store keeps its objects.
function omitMessageFileData(message: SessionMessageInfo): SessionMessageInfo {
- if (message.type !== "assistant") return message
+ if (message.type !== "assistant" || !message.content.some(hasFileData)) return message
return {
...message,
content: message.content.map((part) =>
@@ -268,16 +284,35 @@ export function createData(config: CreateDataInput) {
function refresh(load: () => Promise) {
if (disposed || (config.connection && config.connection.status() !== "connected")) return
- void load().catch((error) => {
- if (disposed || (config.connection && config.connection.status() !== "connected")) return
- if (isSessionNotFoundError(error)) {
- markDeleted(error.sessionID)
- return
- }
- if (isMessageNotFoundError(error)) return
- if (config.onError) return config.onError(error)
- console.error("Failed to refresh client data", error)
- })
+ void load().catch(refreshFailed)
+ }
+
+ // Copies back only the emptied tool files: live events may have moved the message on since the server read it.
+ function restoreMessageFiles(sessionID: string, messageID: string) {
+ return api()
+ .session.message.get({ sessionID, messageID })
+ .then((item) => {
+ if (item.type !== "assistant" || omitFiles()) return
+ message.editAssistant(sessionID, item.id, (assistant) => {
+ assistant.content.forEach((part) => {
+ if (part.type !== "tool" || !("content" in part.state) || !part.state.content?.some(isDroppedFile)) return
+ const fetched = item.content.findLast((other) => other.type === "tool" && other.id === part.id)
+ if (fetched?.type === "tool" && "content" in fetched.state && fetched.state.content)
+ part.state.content = fetched.state.content
+ })
+ })
+ })
+ }
+
+ function refreshFailed(error: unknown) {
+ if (disposed || (config.connection && config.connection.status() !== "connected")) return
+ if (isSessionNotFoundError(error)) {
+ markDeleted(error.sessionID)
+ return
+ }
+ if (isMessageNotFoundError(error)) return
+ if (config.onError) return config.onError(error)
+ console.error("Failed to refresh client data", error)
}
// Runs `load` once a burst of same-key events goes quiet, so N events cost one refetch.
@@ -319,7 +354,9 @@ export function createData(config: CreateDataInput) {
Object.values(store.session.info).toSorted((a, b) => b.time.updated - a.time.updated),
)
const messageIndex = new Map>()
- const stored = (message: SessionMessageInfo) => (config.omitToolFileData ? omitMessageFileData(message) : message)
+ const omitFiles = () =>
+ typeof config.omitToolFileData === "function" ? config.omitToolFileData() : config.omitToolFileData === true
+ const stored = (message: SessionMessageInfo) => (omitFiles() ? omitMessageFileData(message) : message)
const sync = createSync()
let activeUpdates: Map | undefined
const pendingUpdates = new Map>()
@@ -1103,7 +1140,7 @@ export function createData(config: CreateDataInput) {
status: "completed",
input: tool.state.input,
metadata: event.data.metadata,
- content: config.omitToolFileData ? omitFileData(event.data.content) : [...event.data.content],
+ content: omitFiles() ? omitFileData(event.data.content) : [...event.data.content],
}
tool.executed = event.data.executed || tool.executed === true
if (event.data.native) tool.native = { ...tool.native, ...event.data.native }
@@ -1119,7 +1156,7 @@ export function createData(config: CreateDataInput) {
input: typeof tool.state.input === "string" ? {} : tool.state.input,
metadata: event.data.metadata,
content:
- config.omitToolFileData && event.data.content ? omitFileData(event.data.content) : event.data.content,
+ omitFiles() && event.data.content ? omitFileData(event.data.content) : event.data.content,
}
tool.executed = event.data.executed || tool.executed === true
if (event.data.native) tool.native = { ...tool.native, ...event.data.native }
@@ -1823,6 +1860,23 @@ export function createData(config: CreateDataInput) {
const position = messageIndex.get(sessionID)?.get(messageID)
return position === undefined ? undefined : messages?.[position]
},
+ /** Re-reads every loaded message whose tool file data was dropped, for a client that starts showing tool files. */
+ restoreFiles() {
+ const sessions = Object.entries(store.session.message).flatMap(([sessionID, messages]) => {
+ const ids = (messages ?? []).filter(hasDroppedFileData).map((item) => item.id)
+ return ids.length === 0 ? [] : [{ sessionID, ids }]
+ })
+ // Each session's messages are re-read one at a time, so many screenshots don't fan out at once.
+ return Promise.all(
+ sessions.map((session) =>
+ session.ids.reduce(
+ (previous, messageID) =>
+ previous.then(() => restoreMessageFiles(session.sessionID, messageID).catch(refreshFailed)),
+ Promise.resolve(),
+ ),
+ ),
+ )
+ },
sync(sessionID: string) {
return sync.run(`session.message:${sessionID}`, async () => {
const started = deletionEpoch
diff --git a/packages/client/test/solid-data.test.ts b/packages/client/test/solid-data.test.ts
index 69dea99a2455..b040e634d595 100644
--- a/packages/client/test/solid-data.test.ts
+++ b/packages/client/test/solid-data.test.ts
@@ -1,6 +1,6 @@
import { expect, test } from "bun:test"
import { getEventListeners } from "node:events"
-import { createRoot } from "solid-js"
+import { createRoot, createSignal } from "solid-js"
import { createData, type CreateDataInput } from "../src/solid"
import { OpenCode, type ModelInfo, type OpenCodeEvent, type Project, type SessionInfo } from "../src/promise"
@@ -330,6 +330,241 @@ test("omits inline tool-result file payloads from read and live tool results whe
}
})
+test("reads a function omitToolFileData for each live tool result", async () => {
+ const listeners = new Set[0]>()
+ const screenshot = `data:image/png;base64,${"A".repeat(4096)}`
+ const running = (id: string) => ({
+ type: "tool",
+ id,
+ name: "execute",
+ time: { created: 1, ran: 1 },
+ state: { status: "running", input: {}, metadata: {} },
+ })
+ const api = OpenCode.make({
+ baseUrl: "http://opencode.local",
+ fetch: async () =>
+ Response.json({
+ data: [
+ {
+ id: "msg_assistant",
+ type: "assistant",
+ agent: "build",
+ model: { providerID: "provider", id: "model" },
+ time: { created: 1 },
+ content: [running("call_off"), running("call_on")],
+ },
+ ],
+ cursor: {},
+ }),
+ })
+ const [omit, setOmit] = createSignal(true)
+ const setup = createRoot((dispose) => ({
+ data: createData({
+ api: () => api,
+ directory: "/project",
+ omitToolFileData: omit,
+ event: {
+ on: () => () => {},
+ listen(handler) {
+ listeners.add(handler)
+ return () => listeners.delete(handler)
+ },
+ },
+ }),
+ dispose,
+ }))
+ const succeed = (id: string, seq: number) => {
+ const event: OpenCodeEvent = {
+ id: `evt_${id}`,
+ created: 2,
+ type: "session.tool.success",
+ durable: { aggregateID: "ses_toggle", seq, version: 2 },
+ data: {
+ sessionID: "ses_toggle",
+ assistantMessageID: "msg_assistant",
+ id,
+ executed: true,
+ content: [{ type: "file", uri: screenshot, mime: "image/png" }],
+ },
+ }
+ listeners.forEach((listener) => listener({ name: event.type, details: event }))
+ }
+ try {
+ await setup.data.session.message.sync("ses_toggle")
+ succeed("call_off", 1)
+ setOmit(false)
+ succeed("call_on", 2)
+
+ expect(setup.data.session.message.get("ses_toggle", "msg_assistant")).toMatchObject({
+ content: [
+ { state: { content: [{ type: "file", uri: "data:image/png;base64,", mime: "image/png" }] } },
+ { state: { content: [{ type: "file", uri: screenshot, mime: "image/png" }] } },
+ ],
+ })
+ } finally {
+ setup.dispose()
+ }
+})
+
+test("restores dropped tool files from the server once they are shown again", async () => {
+ const listeners = new Set[0]>()
+ const screenshot = `data:image/png;base64,${"A".repeat(4096)}`
+ const assistant = (state: object) => ({
+ id: "msg_assistant",
+ type: "assistant",
+ agent: "build",
+ model: { providerID: "provider", id: "model" },
+ time: { created: 1 },
+ content: [{ type: "tool", id: "call_shot", name: "execute", time: { created: 1, ran: 1 }, state }],
+ })
+ const requests: string[] = []
+ const api = OpenCode.make({
+ baseUrl: "http://opencode.local",
+ fetch: async (input) => {
+ const url = new URL(input instanceof Request ? input.url : String(input))
+ requests.push(url.pathname)
+ if (url.pathname.endsWith("/message/msg_assistant"))
+ return Response.json({
+ data: assistant({
+ status: "completed",
+ input: {},
+ content: [{ type: "file", uri: screenshot, mime: "image/png" }],
+ }),
+ })
+ return Response.json({ data: [assistant({ status: "running", input: {}, metadata: {} })], cursor: {} })
+ },
+ })
+ const [omit, setOmit] = createSignal(true)
+ const setup = createRoot((dispose) => ({
+ data: createData({
+ api: () => api,
+ directory: "/project",
+ omitToolFileData: omit,
+ event: {
+ on: () => () => {},
+ listen(handler) {
+ listeners.add(handler)
+ return () => listeners.delete(handler)
+ },
+ },
+ }),
+ dispose,
+ }))
+ try {
+ await setup.data.session.message.sync("ses_restore")
+ const success: OpenCodeEvent = {
+ id: "evt_shot",
+ created: 2,
+ type: "session.tool.success",
+ durable: { aggregateID: "ses_restore", seq: 1, version: 2 },
+ data: {
+ sessionID: "ses_restore",
+ assistantMessageID: "msg_assistant",
+ id: "call_shot",
+ executed: true,
+ content: [{ type: "file", uri: screenshot, mime: "image/png" }],
+ },
+ }
+ listeners.forEach((listener) => listener({ name: success.type, details: success }))
+ expect(setup.data.session.message.get("ses_restore", "msg_assistant")).toMatchObject({
+ content: [{ state: { content: [{ uri: "data:image/png;base64," }] } }],
+ })
+
+ setOmit(false)
+ await setup.data.session.message.restoreFiles()
+
+ expect(requests.filter((path) => path.endsWith("/message/msg_assistant"))).toHaveLength(1)
+ expect(setup.data.session.message.get("ses_restore", "msg_assistant")).toMatchObject({
+ content: [{ state: { content: [{ type: "file", uri: screenshot, mime: "image/png" }] } }],
+ })
+ // Nothing is left to restore, so a second call reads nothing.
+ await setup.data.session.message.restoreFiles()
+ expect(requests.filter((path) => path.endsWith("/message/msg_assistant"))).toHaveLength(1)
+ } finally {
+ setup.dispose()
+ }
+})
+
+test("restoring dropped tool files keeps live progress made while the server read was in flight", async () => {
+ const listeners = new Set[0]>()
+ const screenshot = `data:image/png;base64,${"A".repeat(4096)}`
+ const tool = (id: string, state: object) => ({ type: "tool", id, name: "execute", time: { created: 1, ran: 1 }, state })
+ const running = { status: "running", input: {}, metadata: {} }
+ const assistant = (content: object[]) => ({
+ id: "msg_assistant",
+ type: "assistant",
+ agent: "build",
+ model: { providerID: "provider", id: "model" },
+ time: { created: 1 },
+ content,
+ })
+ const read = Promise.withResolvers()
+ const api = OpenCode.make({
+ baseUrl: "http://opencode.local",
+ fetch: async (input) => {
+ const url = new URL(input instanceof Request ? input.url : String(input))
+ if (url.pathname.endsWith("/message/msg_assistant")) return read.promise
+ return Response.json({ data: [assistant([tool("call_shot", running), tool("call_work", running)])], cursor: {} })
+ },
+ })
+ const [omit, setOmit] = createSignal(true)
+ const setup = createRoot((dispose) => ({
+ data: createData({
+ api: () => api,
+ directory: "/project",
+ omitToolFileData: omit,
+ event: {
+ on: () => () => {},
+ listen(handler) {
+ listeners.add(handler)
+ return () => listeners.delete(handler)
+ },
+ },
+ }),
+ dispose,
+ }))
+ const succeed = (
+ id: string,
+ seq: number,
+ content: Extract["data"]["content"],
+ ) => {
+ const event: OpenCodeEvent = {
+ id: `evt_${id}`,
+ created: 2,
+ type: "session.tool.success",
+ durable: { aggregateID: "ses_inflight", seq, version: 2 },
+ data: { sessionID: "ses_inflight", assistantMessageID: "msg_assistant", id, executed: true, content },
+ }
+ listeners.forEach((listener) => listener({ name: event.type, details: event }))
+ }
+ try {
+ await setup.data.session.message.sync("ses_inflight")
+ succeed("call_shot", 1, [{ type: "file", uri: screenshot, mime: "image/png" }])
+ setOmit(false)
+ const restoring = setup.data.session.message.restoreFiles()
+ // The second tool finishes while the read is in flight; the server's snapshot predates it.
+ succeed("call_work", 2, [{ type: "text", text: "done" }])
+ read.resolve(
+ Response.json({
+ data: assistant([
+ tool("call_shot", { status: "completed", input: {}, content: [{ type: "file", uri: screenshot, mime: "image/png" }] }),
+ tool("call_work", running),
+ ]),
+ }),
+ )
+ await restoring
+
+ expect(setup.data.session.message.get("ses_inflight", "msg_assistant")).toMatchObject({
+ content: [
+ { id: "call_shot", state: { status: "completed", content: [{ type: "file", uri: screenshot }] } },
+ { id: "call_work", state: { status: "completed", content: [{ type: "text", text: "done" }] } },
+ ],
+ })
+ } finally {
+ setup.dispose()
+ }
+})
+
test("refreshes a loaded session's execution start when it starts running", async () => {
const listeners = new Set[0]>()
const api = OpenCode.make({
diff --git a/packages/tui/src/context/data.tsx b/packages/tui/src/context/data.tsx
index 8c7668f9a77a..f9387658c2e7 100644
--- a/packages/tui/src/context/data.tsx
+++ b/packages/tui/src/context/data.tsx
@@ -1,9 +1,11 @@
import { createData } from "@opencode/client/solid"
import { withMediaRefs, type LocationRef } from "@opencode/client"
import type { Plugin } from "@opencode/plugin/tui"
+import { createEffect, on } from "solid-js"
import { createStore } from "solid-js/store"
import { createSimpleContext } from "./helper"
import { useClient } from "./client"
+import { useConfig } from "../config"
export { locationKey } from "@opencode/client/solid"
export type { FormWithLocation } from "@opencode/client/solid"
@@ -12,13 +14,27 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({
name: "Data",
init: (props: { directory: string }) => {
const client = useClient()
+ const config = useConfig()
const data = createData({
// Only the transcript store reads stored media as `media:` refs; plugins and other callers keep inline bytes.
api: () => withMediaRefs(client.api),
event: client.event,
connection: client.connection,
directory: props.directory,
+ // Live tool events carry screenshots as inline base64, which open tabs would otherwise hold for the whole run.
+ // Read per event, so toggling previews applies to new results without a restart.
+ omitToolFileData: () => !config.data.session?.image_preview,
})
+ // Turning previews on brings back the screenshots dropped while they were off.
+ createEffect(
+ on(
+ () => config.data.session?.image_preview === true,
+ (preview) => {
+ if (preview) void data.session.message.restoreFiles()
+ },
+ { defer: true },
+ ),
+ )
data satisfies Plugin.Context["data"]
const [generatingTitles, setGeneratingTitles] = createStore>({})
return {
diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx
index b8b4262ba884..b5b85321717e 100644
--- a/packages/tui/src/routes/session/index.tsx
+++ b/packages/tui/src/routes/session/index.tsx
@@ -2728,7 +2728,8 @@ function inlineToolImages(part: SessionMessageAssistantTool) {
return toolDisplayContent(part.state).flatMap((content) =>
content.type === "file" &&
content.mime.startsWith("image/") &&
- (content.uri.startsWith("data:image/") || mediaHashFromUri(content.uri))
+ // An emptied `data:` URI is a payload the store dropped while previews were off.
+ ((content.uri.startsWith("data:image/") && !content.uri.endsWith(",")) || mediaHashFromUri(content.uri))
? [{ uri: content.uri }]
: [],
)
From aed4cbc02445a0d8dade3ba2255978ec3c9719c9 Mon Sep 17 00:00:00 2001
From: Sara Kay <47927313+ssskay@users.noreply.github.com>
Date: Thu, 12 Nov 2026 16:24:52 -0600
Subject: [PATCH 16/42] fix(gui-plugins): keep the pairing QR code dark on
light in every theme (#63220)
Co-authored-by: ssskay
Co-authored-by: Claude Opus 5.5
---
packages/gui-plugins/src/pairing/page.tsx | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/packages/gui-plugins/src/pairing/page.tsx b/packages/gui-plugins/src/pairing/page.tsx
index b71412cf666a..0fa98180d1cc 100644
--- a/packages/gui-plugins/src/pairing/page.tsx
+++ b/packages/gui-plugins/src/pairing/page.tsx
@@ -373,7 +373,9 @@ function DialogPairing(props: {
if (!value) return
- return renderSVG(value, { border: 4, blackColor: "currentColor", whiteColor: "transparent" })
+ // Scanners expect dark modules on a light quiet zone, so the code keeps black on white in every theme. Following
+ // the theme drew light modules on a dark background, which the Android app's scanner can't read.
+ return renderSVG(value, { border: 4 })
})
// The QR code's frame, which also holds the setup progress and its failure, so the dialog keeps its size.
@@ -391,7 +393,7 @@ function DialogPairing(props: {
{(current) => (
<>