From 1950fb8fe4981d376c57458a0c08f47aa038d693 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:07:18 -0600 Subject: [PATCH 1/8] feat(core): durable video jobs (#64546) --- .../client/src/promise/generated/types.ts | 2 +- packages/core/src/blob-store.ts | 46 +-- packages/core/src/video-generation.ts | 354 +++++++++++++----- packages/core/test/video-generation.test.ts | 135 +++---- packages/protocol/openapi.json | 17 +- packages/protocol/src/groups/blob.ts | 2 +- packages/protocol/src/groups/generate.ts | 4 +- packages/schema/src/blob-store.ts | 23 +- packages/schema/src/generate.ts | 2 +- packages/server/src/handlers/blob.ts | 2 +- packages/server/test/video-generate.test.ts | 8 +- 11 files changed, 353 insertions(+), 242 deletions(-) diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index a6a62e36cc2..c7e7fc7f987 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -738,7 +738,7 @@ export type ModelCost = { export type GenerateVideoRunning = { id: GenerateVideoID; status: "running" } -export type BlobInfo = { id: BlobID; mime: string; bytes: number; expiresAt: number } +export type BlobInfo = { id: BlobID; mime: string; bytes: number } export type GenerateVideoError = { id: GenerateVideoID diff --git a/packages/core/src/blob-store.ts b/packages/core/src/blob-store.ts index 53e9d7685cc..ebecedcd3f2 100644 --- a/packages/core/src/blob-store.ts +++ b/packages/core/src/blob-store.ts @@ -6,8 +6,7 @@ import { BlobStore } from "@opencode/schema/blob-store" import { makeGlobalNode } from "@opencode/util/effect/app-node" import { FSUtil } from "@opencode/util/fs-util" import { Global } from "@opencode/util/global" -import { Context, Duration, Effect, Layer, Option, Schedule, Schema, Stream } from "effect" -import { FileRetention } from "./file-retention.js" +import { Context, Effect, Layer, Schema, Stream } from "effect" export const ID = BlobStore.ID export type ID = BlobStore.ID @@ -22,7 +21,6 @@ export class UnavailableError extends Schema.TaggedError()("Bl message: Schema.String, }) {} -export const RETENTION = Duration.days(7) /** Blobs are files named by their ID, with no extension; their type is read from their first bytes. */ export const DIRECTORY = "blobs" @@ -32,18 +30,15 @@ export interface Content extends Info { } export interface Interface { - /** Stores the stream as the blob `id`, replacing any earlier one. The file appears only once it's whole. */ - readonly write: (id: ID, stream: Stream.Stream) => Effect.Effect + /** Stores the stream as a new blob, flushed to disk before it returns. A failed write leaves no blob. */ + readonly write: (stream: Stream.Stream) => Effect.Effect readonly read: (id: ID) => Effect.Effect readonly remove: (id: ID) => Effect.Effect } export class Service extends Context.Service()("@opencode/BlobStore") {} -/** - * Files under `/blobs/`, deleted 7 days after they're written, at startup and hourly. Nothing tracks who uses a - * blob, so a caller that keeps one longer copies it. - */ +/** Files under `/blobs/`, kept until something removes them. */ const layer = Layer.effect( Service, Effect.gen(function* () { @@ -55,7 +50,6 @@ const layer = Layer.effect( const read = Effect.fn("BlobStore.read")(function* (id: ID) { const missing = new NotFoundError({ id, message: `Blob not found: ${id}` }) const info = yield* fs.stat(file(id)).pipe(Effect.mapError(() => missing)) - const written = Option.getOrUndefined(info.mtime)?.getTime() ?? 0 const head = yield* fs.stream(file(id), { bytesToRead: 64 }).pipe( Stream.runCollect, Effect.mapError(() => missing), @@ -65,46 +59,28 @@ const layer = Layer.effect( path: file(id), mime: Media.detectMediaType(Buffer.concat([...head])) ?? "application/octet-stream", bytes: Number(info.size), - expiresAt: written + Duration.toMillis(RETENTION), } }) - // Written to `.part`, synced, then renamed, so a stored blob is always whole. - const write = (id: ID, stream: Stream.Stream) => + const remove = (id: ID) => fs.remove(file(id), { force: true }).pipe(Effect.ignore) + + const write = (stream: Stream.Stream) => Effect.gen(function* () { - const part = `${file(id)}.part` + const id = ID.create() const unavailable = (cause: unknown) => new UnavailableError({ message: `Could not store blob ${id}: ${String(cause)}` }) yield* fs.makeDirectory(directory, { recursive: true }).pipe(Effect.mapError(unavailable)) yield* Effect.scoped( Effect.gen(function* () { - const handle = yield* fs.open(part, { flag: "w", mode: 0o600 }).pipe(Effect.mapError(unavailable)) + const handle = yield* fs.open(file(id), { flag: "w", mode: 0o600 }).pipe(Effect.mapError(unavailable)) yield* stream.pipe(Stream.runForEach((chunk) => handle.writeAll(chunk).pipe(Effect.mapError(unavailable)))) yield* handle.sync.pipe(Effect.mapError(unavailable)) }), - ).pipe(Effect.onError(() => fs.remove(part, { force: true }).pipe(Effect.ignore))) - yield* fs.rename(part, file(id)).pipe(Effect.mapError(unavailable)) + ).pipe(Effect.onError(() => remove(id))) const stored = yield* read(id).pipe(Effect.mapError(unavailable)) - return { id, mime: stored.mime, bytes: stored.bytes, expiresAt: stored.expiresAt } satisfies Info + return { id, mime: stored.mime, bytes: stored.bytes } satisfies Info }).pipe(Effect.withSpan("BlobStore.write")) - const remove = (id: ID) => fs.remove(file(id), { force: true }).pipe(Effect.ignore) - - // Blobs and leftover `.part` files are deleted once older than the retention. - yield* fs.readDirectory(directory).pipe( - Effect.orElseSucceed((): string[] => []), - Effect.flatMap((entries) => - FileRetention.cleanup( - fs, - entries.filter((entry) => entry.startsWith("video_")).map((entry) => path.join(directory, entry)), - RETENTION, - ), - ), - Effect.ignoreCause({ log: "Error", message: "Blob cleanup failed" }), - Effect.repeat(Schedule.spaced(Duration.hours(1))), - Effect.forkScoped, - ) - return Service.of({ write, read, remove }) }), ) diff --git a/packages/core/src/video-generation.ts b/packages/core/src/video-generation.ts index 3ded463ab4e..8582f3d5f66 100644 --- a/packages/core/src/video-generation.ts +++ b/packages/core/src/video-generation.ts @@ -1,13 +1,24 @@ export * as VideoGeneration from "./video-generation.js" +import { randomUUID } from "node:crypto" +import { and, eq, lte, sql } from "drizzle-orm" import { Media } from "@opencode/ai/effect" -import { VideoID, type VideoJob, type VideoRequest, type VideoRunning } from "@opencode/schema/generate" -import type { Model } from "@opencode/schema/model" +import { + VideoErrorReason, + VideoID, + type VideoJob, + type VideoRequest, + type VideoRunning, +} from "@opencode/schema/generate" +import { Model } from "@opencode/schema/model" import { makeGlobalNode } from "@opencode/util/effect/app-node" import { Global } from "@opencode/util/global" -import { Context, Deferred, Duration, Effect, Exit, FiberMap, Layer, Option, Schedule, Schema } from "effect" +import { Clock, Context, Deferred, Duration, Effect, Exit, FiberMap, Layer, Option, Schedule, Schema } from "effect" import { BlobStore } from "./blob-store.js" +import { Database } from "./database/database.js" import { Generate } from "./generate.js" +import { KV } from "./kv.js" +import { KVTable } from "./kv/sql.js" import { Location } from "./location.js" import { LocationServiceMap } from "./location-service-map.js" import { AbsolutePath } from "./schema.js" @@ -19,20 +30,62 @@ export class NotFoundError extends Schema.TaggedError()("VideoGen const INTERVAL = Duration.seconds(5) const DEADLINE = Duration.hours(2) +/** How long a finished job's record is kept. Its blobs keep their own retention. */ +const RETENTION = Duration.hours(24) +const PREFIX = "video:" +/** + * A server polls a job only while it holds the job's lease, so servers sharing a database never poll the same job, and + * one takes over the jobs of a server that stopped within about a minute. + */ +const LEASE = "video-lease:" +const TTL = Duration.minutes(1) + +export interface StartOptions { + /** Where the model and its credentials are resolved; defaults to the server's base configuration. */ + readonly location?: Location.Ref +} export interface Interface { - /** Returns once the provider accepted the job; the server then polls it and stores the video as a blob. */ - readonly start: (input: VideoRequest) => Effect.Effect + /** Returns once the provider accepted the job; the server then polls it and stores the videos as blobs. */ + readonly start: (input: VideoRequest, options?: StartOptions) => Effect.Effect readonly get: (id: VideoID) => Effect.Effect } export class Service extends Context.Service()("@opencode/VideoGeneration") {} +// `remote` is the provider's ID for the job; it never leaves this service. +const fields = { model: Model.Ref, location: Location.Ref, created: Schema.Finite } +const Job = Schema.Union([ + Schema.Struct({ status: Schema.Literal("submitting"), ...fields }), + Schema.Struct({ status: Schema.Literal("running"), remote: Schema.String, ...fields }), + Schema.Struct({ + status: Schema.Literal("completed"), + blobs: Schema.Array(BlobStore.ID), + finished: Schema.Finite, + ...fields, + }), + Schema.Struct({ + status: Schema.Literal("error"), + reason: VideoErrorReason, + error: Schema.String, + finished: Schema.Finite, + ...fields, + }), +]) +type Job = typeof Job.Type +type Running = Extract +type Outcome = + | { readonly status: "completed"; readonly blobs: readonly BlobStore.ID[] } + | { readonly status: "error"; readonly reason: VideoErrorReason; readonly error: string } + +const decode = Schema.decodeUnknownOption(Job) +const encode = Schema.encodeSync(Job) +const decodeID = Schema.decodeUnknownOption(VideoID) + /** - * Running and failed jobs live in memory only: a restart forgets them, and a running job's videos are never collected. - * A finished job is read from its blobs, so it outlives a restart until they expire. - * - * TODO: record jobs durably, so a restart resumes polling them. + * Each job is a record in kv under `video:`, written before the provider is called, so a restart resumes polling + * running jobs and fails the ones whose submission it interrupted. Records are deleted 24 hours after the job finished. + * Only the server holding a job's lease works on it. */ const layer = Layer.effect( Service, @@ -40,121 +93,159 @@ const layer = Layer.effect( const global = yield* Global.Service const locations = yield* LocationServiceMap.Service const blobs = yield* BlobStore.Service + const kv = yield* KV.Service + const db = (yield* Database.Service).db + const owner = randomUUID() // The same base-config Location the generate routes use. - const base = locations.get(Location.Ref.make({ directory: AbsolutePath.make(global.config) })) + const base = Location.Ref.make({ directory: AbsolutePath.make(global.config) }) const fibers = yield* FiberMap.make() - const jobs = new Map() - const generate = (run: (generate: Generate.Interface) => Effect.Effect) => + const save = (id: VideoID, job: Job) => kv.set(PREFIX + id, encode(job)) + + // Takes the lease if it's free, expired or already ours. + const claim = Effect.fnUntraced(function* (id: VideoID) { + const now = yield* Clock.currentTimeMillis + const value = { owner, until: now + Duration.toMillis(TTL) } + const claimed = yield* db + .insert(KVTable) + .values({ key: LEASE + id, value, time_created: now, time_updated: now }) + .onConflictDoUpdate({ + target: KVTable.key, + set: { value, time_updated: now }, + where: sql`json_extract(${KVTable.value}, '$.owner') = ${owner} or json_extract(${KVTable.value}, '$.until') <= ${now}`, + }) + .returning({ key: KVTable.key }) + .get() + .pipe(Effect.orDie) + return claimed !== undefined + }) + + const release = (id: VideoID) => + db + .delete(KVTable) + .where(and(eq(KVTable.key, LEASE + id), sql`json_extract(${KVTable.value}, '$.owner') = ${owner}`)) + .run() + .pipe(Effect.ignore) + + // Runs the work while renewing its lease, and stops it if another server took the lease over. + const hold = (id: VideoID, work: Effect.Effect) => + Effect.raceFirst( + work, + claim(id).pipe( + Effect.repeat({ schedule: Schedule.spaced(Duration.seconds(30)), while: (held) => held }), + Effect.andThen(Effect.logWarning("video lease lost", { id })), + Effect.andThen(Effect.interrupt), + ), + ).pipe(Effect.ensuring(release(id))) + + const finish = (id: VideoID, job: Job, outcome: Outcome) => + Clock.currentTimeMillis.pipe( + Effect.flatMap((finished) => + save(id, { model: job.model, location: job.location, created: job.created, ...outcome, finished }), + ), + ) + + const generate = ( + location: Location.Ref, + run: (generate: Generate.Interface) => Effect.Effect, + ) => Generate.Service.pipe( Effect.flatMap(run), - Effect.provide(base), + Effect.provide(locations.get(location)), Effect.catchTag("FileSystem.DirectoryNotFoundError", (error) => Effect.fail(new Generate.UnavailableError({ message: `Location not found: ${error.directory}` })), ), ) - // Each video becomes blob `_`, so a restarted server finds them from the job's ID alone. - const blobID = (id: VideoID, index: number) => BlobStore.ID.make(`${id}_${index}`) - - const store = Effect.fnUntraced(function* (id: VideoID, model: Model.Ref, providerID: string) { - const videos = yield* generate((service) => service.video.result(model, providerID)) - const stored = yield* Effect.forEach(videos, (video, index) => - blobs.write(blobID(id, index), video.stream).pipe( + // All or nothing: a job never reports only some of its videos. + const download = Effect.fnUntraced(function* (job: Running) { + const videos = yield* generate(job.location, (service) => service.video.result(job.model, job.remote)) + const written: BlobStore.ID[] = [] + yield* Effect.forEach(videos, (video) => + blobs.write(video.stream).pipe( + Effect.tap((blob) => Effect.sync(() => written.push(blob.id))), Effect.flatMap((blob) => blob.bytes > 0 - ? Effect.succeed(blob) + ? Effect.void : Effect.fail( new Generate.ProviderRequestError({ - providerID: model.providerID, + providerID: job.model.providerID, reason: "provider", message: "The provider returned an empty video", }), ), ), ), - ).pipe( - // All or nothing: a job never reports only some of its videos. - Effect.onError(() => Effect.forEach(videos, (_, index) => blobs.remove(blobID(id, index)), { discard: true })), - ) - return { id, status: "completed", blobs: stored } satisfies VideoJob + ).pipe(Effect.onError(() => Effect.forEach(written, blobs.remove, { discard: true }))) + return written }) - // A finished job outlives a restart through its blobs: `_0`, `_1`, … up to the first missing one. - const stored = (id: VideoID): Effect.Effect => - Effect.gen(function* () { - const found: BlobStore.Info[] = [] - while (true) { - const blob = yield* blobs.read(blobID(id, found.length)).pipe(Effect.option) - if (Option.isNone(blob)) return found - found.push({ - id: blob.value.id, - mime: blob.value.mime, - bytes: blob.value.bytes, - expiresAt: blob.value.expiresAt, - }) - } - }) - // A status read that fails is retried at the next interval: the provider may be briefly unavailable. - const poll = (id: VideoID, model: Model.Ref, providerID: string) => - generate((service) => service.video.status(model, providerID)).pipe( + const poll = (id: VideoID, job: Running, left: Duration.Duration) => + generate(job.location, (service) => service.video.status(job.model, job.remote)).pipe( Effect.map((status) => (status.status === "running" ? undefined : status)), Effect.catch((error) => Effect.logWarning("video status read failed", { id, error: error.message }).pipe(Effect.as(undefined)), ), Effect.repeat({ schedule: Schedule.spaced(INTERVAL), until: (status) => status !== undefined }), - Effect.timeoutOption(DEADLINE), + Effect.timeoutOption(left), + Effect.map((status) => Option.getOrUndefined(status)), ) - const settle = Effect.fnUntraced(function* (id: VideoID, model: Model.Ref, providerID: string) { - const settled = yield* poll(id, model, providerID) - if (Option.isNone(settled) || settled.value === undefined) - return { - id, + const settle = Effect.fnUntraced(function* (id: VideoID, job: Running) { + const left = job.created + Duration.toMillis(DEADLINE) - (yield* Clock.currentTimeMillis) + const settled = left > 0 ? yield* poll(id, job, Duration.millis(left)) : undefined + if (settled === undefined) + return yield* finish(id, job, { status: "error", reason: "unknown", error: `The provider had no result ${Duration.format(DEADLINE)} after submission`, - } satisfies VideoJob - if (settled.value.status === "error") { - const reason = settled.value.reason ?? "failed" - return { id, status: "error", reason, error: `The provider reported the job as ${reason}` } satisfies VideoJob + }) + if (settled.status === "error") { + const reason = settled.reason ?? "failed" + return yield* finish(id, job, { status: "error", reason, error: `The provider reported the job as ${reason}` }) } - return yield* store(id, model, providerID).pipe( + const outcome = yield* download(job).pipe( Effect.retry({ times: 2, schedule: Schedule.exponential("1 second") }), - Effect.catch((error) => - Effect.succeed({ id, status: "error", reason: "failed", error: error.message } satisfies VideoJob), - ), + Effect.map((written): Outcome => ({ status: "completed", blobs: written })), + Effect.catch((error) => Effect.succeed({ status: "error", reason: "failed", error: error.message })), ) + yield* finish(id, job, outcome) }) - const start = Effect.fn("VideoGeneration.start")(function* (input: VideoRequest) { + const start = Effect.fn("VideoGeneration.start")(function* (input: VideoRequest, options?: StartOptions) { const id = VideoID.create() const submitted = yield* Deferred.make() + const job = { + status: "submitting", + model: input.model, + location: options?.location ?? base, + created: yield* Clock.currentTimeMillis, + } satisfies Job // Runs in the server's fibers, so a client that disconnects can't interrupt a paid submission midway. + yield* claim(id) yield* FiberMap.run( fibers, id, - Effect.gen(function* () { - const started = yield* generate((service) => - service.video.start({ - ...input, - start: input.start && Media.image(Media.base64(input.start.data, input.start.mime)), - end: input.end && Media.image(Media.base64(input.end.data, input.end.mime)), - references: input.references?.map((file) => Media.base64(file.data, file.mime)), - }), - ) - const running = { id, status: "running" } as const - jobs.set(id, running) - yield* Deferred.succeed(submitted, running) - const settled = yield* settle(id, input.model, started.id) - // A finished job's blobs are its record from here on. - if (settled.status === "completed") return jobs.delete(id) - // A failure is kept as long as a blob would be, so the map holds at most one retention's worth of jobs. - jobs.set(id, settled) - yield* Effect.sleep(BlobStore.RETENTION) - jobs.delete(id) - }).pipe( + hold( + id, + Effect.gen(function* () { + yield* save(id, job) + // A rejected submission's ID is never returned, so its record is dropped. + const started = yield* generate(job.location, (service) => + service.video.start({ + ...input, + start: input.start && Media.image(Media.base64(input.start.data, input.start.mime)), + end: input.end && Media.image(Media.base64(input.end.data, input.end.mime)), + references: input.references?.map((file) => Media.base64(file.data, file.mime)), + }), + ).pipe(Effect.tapError(() => kv.remove(PREFIX + id))) + const running = { ...job, status: "running", remote: started.id } satisfies Running + yield* save(id, running) + yield* Deferred.succeed(submitted, { id, status: "running" } as const) + yield* settle(id, running) + }), + ).pipe( // Once the submission succeeded, this does nothing. Effect.onExit((exit) => (Exit.isFailure(exit) ? Deferred.failCause(submitted, exit.cause) : Effect.void)), Effect.ignore, @@ -164,17 +255,108 @@ const layer = Layer.effect( }) const get = Effect.fn("VideoGeneration.get")(function* (id: VideoID) { - const job = jobs.get(id) - if (job) return job - const found = yield* stored(id) - if (found.length === 0) return yield* new NotFoundError({ id, message: `Video not found: ${id}` }) - return { id, status: "completed", blobs: found } satisfies VideoJob + const missing = new NotFoundError({ id, message: `Video not found: ${id}` }) + const stored = yield* kv.get(PREFIX + id) + const job = stored === undefined ? undefined : Option.getOrUndefined(decode(stored)) + if (!job || expired(job, yield* Clock.currentTimeMillis)) return yield* missing + if (job.status === "submitting" || job.status === "running") return { id, status: "running" } satisfies VideoJob + if (job.status === "error") + return { id, status: "error", reason: job.reason, error: job.error } satisfies VideoJob + // A blob that expired or was deleted is dropped. + const found = yield* Effect.forEach(job.blobs, (blob) => blobs.read(blob).pipe(Effect.option)) + const infos = found.flatMap((blob) => + Option.isSome(blob) ? [{ id: blob.value.id, mime: blob.value.mime, bytes: blob.value.bytes }] : [], + ) + if (infos.length === 0) return yield* missing + return { id, status: "completed", blobs: infos } satisfies VideoJob }) + const rows = Effect.gen(function* () { + const found: KV.Entry[] = [] + let after: string | undefined + while (true) { + const page = yield* kv.scan({ prefix: PREFIX, after, limit: 500 }) + found.push(...page.entries) + if (!page.next) return found + after = page.next + } + }) + + // At startup and every minute, take over unfinished jobs nobody holds: a running job is polled again until its + // deadline. A submission the server stopped is never resent: it's paid and not idempotent, so whether the provider + // got it is unknown. + const adopt = Effect.gen(function* () { + yield* Effect.forEach( + yield* rows, + (row) => + Effect.gen(function* () { + const id = Option.getOrUndefined(decodeID(row.key.slice(PREFIX.length))) + const seen = Option.getOrUndefined(decode(row.value)) + if (!id || !seen || (seen.status !== "running" && seen.status !== "submitting")) return + if (yield* FiberMap.has(fibers, id)) return + if (!(yield* claim(id))) return + // Read again under the lease: the previous owner may have finished the job since the scan. + const stored = yield* kv.get(PREFIX + id) + const job = stored === undefined ? undefined : Option.getOrUndefined(decode(stored)) + if (!job || (job.status !== "running" && job.status !== "submitting")) return yield* release(id) + if (job.status === "running") + return yield* FiberMap.run(fibers, id, hold(id, settle(id, job)).pipe(Effect.ignore)) + yield* finish(id, job, { + status: "error", + reason: "unknown", + error: "The server stopped while submitting the job; its outcome is unknown", + }).pipe(Effect.ensuring(release(id))) + }), + { discard: true }, + ) + }) + yield* adopt + yield* adopt.pipe( + Effect.ignoreCause({ log: "Error", message: "Video job takeover failed" }), + Effect.repeat(Schedule.spaced(TTL)), + Effect.delay(TTL), + Effect.forkScoped, + ) + + // Records that can't be read are removed with the expired ones. + yield* Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis + yield* Effect.forEach( + yield* rows, + (row) => { + const job = Option.getOrUndefined(decode(row.value)) + return !job || expired(job, now) ? kv.remove(row.key) : Effect.void + }, + { discard: true }, + ) + // A lease outlives its job only when its server stopped after the job finished. + yield* db + .delete(KVTable) + .where( + and( + sql`${KVTable.key} like ${LEASE + "%"}`, + lte(sql`json_extract(${KVTable.value}, '$.until')`, now - Duration.toMillis(RETENTION)), + ), + ) + .run() + .pipe(Effect.ignore) + }).pipe( + Effect.ignoreCause({ log: "Error", message: "Video record cleanup failed" }), + Effect.repeat(Schedule.spaced(Duration.hours(1))), + Effect.forkScoped, + ) + return Service.of({ start, get }) }), ) +// A job that never recorded finishing is treated as finished at its deadline. +function expired(job: Job, now: number) { + const finished = + job.status === "completed" || job.status === "error" ? job.finished : job.created + Duration.toMillis(DEADLINE) + return finished + Duration.toMillis(RETENTION) <= now +} + /** Videos are stored as blobs, which need a local disk that Durable Objects don't have. */ export const unsupportedLayer = Layer.succeed( Service, @@ -188,5 +370,5 @@ export const unsupportedLayer = Layer.succeed( export const node = makeGlobalNode({ service: Service, layer, - deps: [BlobStore.node, Global.node, LocationServiceMap.node], + deps: [BlobStore.node, Database.node, Global.node, KV.node, LocationServiceMap.node], }) diff --git a/packages/core/test/video-generation.test.ts b/packages/core/test/video-generation.test.ts index 8e037a14240..2bd98e839c0 100644 --- a/packages/core/test/video-generation.test.ts +++ b/packages/core/test/video-generation.test.ts @@ -1,7 +1,6 @@ -import fs from "node:fs/promises" import path from "node:path" import { expect } from "bun:test" -import { type Duration, Effect, Layer, Stream } from "effect" +import { Effect, Layer, Stream } from "effect" import { TestClock } from "effect/testing" import type { VideoStatus } from "@opencode/ai/effect" import { Database } from "@opencode/core/database/database" @@ -9,6 +8,7 @@ import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { Watcher } from "@opencode/core/filesystem/watcher" import { Generate } from "@opencode/core/generate" import { BlobStore } from "@opencode/core/blob-store" +import { KV } from "@opencode/core/kv" import { VideoGeneration } from "@opencode/core/video-generation" import { LocationServiceMap } from "@opencode/core/location-service-map" import type { VideoID, VideoJob } from "@opencode/schema/generate" @@ -23,26 +23,21 @@ import { it } from "./lib/effect" import { eventually } from "./lib/eventually" const model = Model.Ref.make({ providerID: Provider.ID.make("test"), id: Model.ID.make("video") }) -const providerError = (message: string, status?: number) => - new Generate.ProviderRequestError({ providerID: "test", reason: "provider", message, status }) // The start of an MP4: a `ftyp` box, so its type is read from its bytes. const mp4 = Uint8Array.from([0, 0, 0, 0x14, ...new TextEncoder().encode("ftypmp42"), 0, 0, 0, 0, 1, 2, 3, 4]) -/** A provider the test drives. */ +/** A provider the test drives: each submission gets the next remote ID, whose status the test sets. */ const provider = () => ({ - status: { status: "running" } as VideoStatus, - /** The videos a finished job returns. */ - results: [Stream.make(mp4)] as Stream.Stream[], - start: Effect.succeed({ id: "provider_1" }) as Effect.Effect<{ readonly id: string }, Generate.Error>, - /** Status reads that fail before one succeeds. */ - failReads: 0, + submitted: 0, + hang: false, + status: new Map(), }) type State = ReturnType const app = (dir: string, state: State) => AppNodeBuilder.build( - LayerNode.group([VideoGeneration.node, BlobStore.node, Database.node, LocationServiceMap.node]), + LayerNode.group([VideoGeneration.node, BlobStore.node, Database.node, KV.node, LocationServiceMap.node]), [ Global.node.replace(Global.layerWith({ data: path.join(dir, "data"), config: path.join(dir, "config") })), Database.node.replace(Database.configured({ path: "opencode.db" })), @@ -58,12 +53,13 @@ const app = (dir: string, state: State) => image: () => Effect.die("unused"), decisions: () => Effect.die("unused"), video: { - start: () => Effect.suspend(() => state.start), - status: () => - Effect.suspend(() => - state.failReads-- > 0 ? Effect.fail(providerError("reset")) : Effect.succeed(state.status), - ), - result: () => Effect.sync(() => state.results.map((stream) => ({ mime: "video/mp4", stream }))), + start: () => (state.hang ? Effect.never : Effect.sync(() => ({ id: `remote_${++state.submitted}` }))), + status: (_, remote) => Effect.sync(() => state.status.get(remote) ?? { status: "running" }), + result: () => + Effect.succeed([ + { mime: "video/mp4", stream: Stream.make(mp4) }, + { mime: "video/mp4", stream: Stream.make(mp4, mp4) }, + ]), }, }), ), @@ -73,100 +69,57 @@ const app = (dir: string, state: State) => ], ) -const settled = (id: VideoID, step: Duration.Input = "5 seconds") => +const settled = (id: VideoID) => eventually( VideoGeneration.Service.pipe( - Effect.tap(() => TestClock.adjust(step)), + Effect.tap(() => TestClock.adjust("5 seconds")), Effect.flatMap((generations) => generations.get(id)), ), (job: VideoJob) => job.status !== "running", ) -const blobs = (dir: string) => path.join(dir, "data", "blobs") -const listed = (dir: string) => Effect.promise(() => fs.readdir(blobs(dir)).catch(() => [] as string[])) +const records = KV.Service.pipe(Effect.flatMap((kv) => kv.scan({ prefix: "video:" }))) -it.effect("stores each finished video as a blob, read back after a restart until it's 7 days old", () => +it.effect("keeps video jobs across restarts and forgets them a day after they finish", () => Effect.gen(function* () { const dir = (yield* tmpdirScoped("opencode-generation-")).path const state = provider() - state.results = [Stream.make(mp4), Stream.make(mp4, mp4)] - const job = yield* Effect.gen(function* () { + const first = yield* Effect.gen(function* () { const generations = yield* VideoGeneration.Service - const started = yield* generations.start({ model, prompt: "a cat" }) - expect(yield* generations.get(started.id)).toEqual({ id: started.id, status: "running" }) - - state.status = { status: "completed" } - // A failed status read is retried at the next interval. - state.failReads = 1 - const job = yield* settled(started.id) + const done = yield* generations.start({ model, prompt: "a cat" }) + const slow = yield* generations.start({ model, prompt: "a snail" }) + state.status.set("remote_1", { status: "completed" }) + const job = yield* settled(done.id) if (job.status !== "completed") throw new Error(`expected completed, got ${job.status}`) expect(job.blobs).toMatchObject([ - { id: `${started.id}_0`, mime: "video/mp4", bytes: mp4.length }, - { id: `${started.id}_1`, mime: "video/mp4", bytes: mp4.length * 2 }, + { mime: "video/mp4", bytes: mp4.length }, + { mime: "video/mp4", bytes: mp4.length * 2 }, ]) - expect(job.blobs[0].expiresAt).toBeGreaterThan(Date.now() + 6 * 24 * 60 * 60 * 1000) - expect( - new Uint8Array(yield* Effect.promise(() => fs.readFile(path.join(blobs(dir), `${started.id}_0`)))), - ).toEqual(mp4) - expect((yield* listed(dir)).toSorted()).toEqual([`${started.id}_0`, `${started.id}_1`]) - return job + expect(job.blobs.every((blob) => blob.id.startsWith("blob_"))).toBe(true) + expect(yield* generations.get(slow.id)).toEqual({ id: slow.id, status: "running" }) + // A submission the process stops in the middle of. + state.hang = true + yield* generations.start({ model, prompt: "a crab" }).pipe(Effect.forkChild({ startImmediately: true })) + yield* eventually(records, (page) => page.entries.length === 3) + return { job, slow: slow.id } }).pipe(Effect.provide(app(dir, state))) yield* Effect.gen(function* () { const generations = yield* VideoGeneration.Service - // A new process knows nothing of the job, but finds its blobs from its ID. - expect(yield* generations.get(job.id)).toEqual(job) - const old = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000) - yield* Effect.forEach(job.blobs, (blob) => - Effect.promise(() => fs.utimes(path.join(blobs(dir), blob.id), old, old)), - ) - yield* TestClock.adjust("1 hour") - yield* eventually(listed(dir), (files) => files.length === 0) - expect(yield* generations.get(job.id).pipe(Effect.flip)).toMatchObject({ _tag: "VideoGeneration.NotFoundError" }) - }).pipe(Effect.provide(app(dir, state))) - }), -) + expect(yield* generations.get(first.job.id)).toEqual(first.job) + const crab = (yield* records).entries + .map((entry) => entry.key.slice("video:".length) as VideoID) + .find((id) => id !== first.job.id && id !== first.slow)! + expect(yield* generations.get(crab)).toMatchObject({ status: "error", reason: "unknown" }) -it.effect("keeps none of a job's videos when one of their downloads keeps failing", () => - Effect.gen(function* () { - const dir = (yield* tmpdirScoped("opencode-generation-fail-")).path - const state = provider() - state.results = [ - Stream.make(mp4), - Stream.make(mp4).pipe(Stream.concat(Stream.fail(providerError("connection reset")))), - ] - yield* Effect.gen(function* () { - const generations = yield* VideoGeneration.Service - const started = yield* generations.start({ model, prompt: "a bird" }) - state.status = { status: "completed" } - expect(yield* settled(started.id, "1 second")).toEqual({ - id: started.id, - status: "error", - reason: "failed", - error: "connection reset", + state.status.set("remote_2", { status: "completed" }) + expect(yield* settled(first.slow)).toMatchObject({ status: "completed" }) + + yield* TestClock.adjust("25 hours") + yield* eventually(records, (page) => page.entries.length === 0) + expect(yield* generations.get(first.job.id).pipe(Effect.flip)).toMatchObject({ + _tag: "VideoGeneration.NotFoundError", }) - expect(yield* listed(dir)).toEqual([]) - }).pipe(Effect.provide(app(dir, state))) - }), -) - -it.effect("reports the provider's failure reason, a job past its deadline and a rejected submission", () => - Effect.gen(function* () { - const dir = (yield* tmpdirScoped("opencode-generation-errors-")).path - const state = provider() - yield* Effect.gen(function* () { - const generations = yield* VideoGeneration.Service - const expired = yield* generations.start({ model, prompt: "a fish" }) - state.status = { status: "error", reason: "expired" } - expect(yield* settled(expired.id)).toMatchObject({ status: "error", reason: "expired" }) - - state.status = { status: "running" } - const slow = yield* generations.start({ model, prompt: "a snail" }) - expect(yield* settled(slow.id, "30 minutes")).toMatchObject({ status: "error", reason: "unknown" }) - - state.start = Effect.fail(providerError("bad", 400)) - const rejected = yield* generations.start({ model, prompt: "a crab" }).pipe(Effect.flip) - expect(rejected).toMatchObject({ _tag: "Generate.ProviderRequestError", message: "bad" }) }).pipe(Effect.provide(app(dir, state))) }), ) diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 1e241a9bfa2..7ad34923c69 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -5567,7 +5567,7 @@ } } }, - "description": "Submit a video job to a video model using the server's base configuration and return its ID once the provider accepted it. The server polls the job and stores the finished video as a blob for 7 days; read the job with GET /api/experimental/generate/video/:id and the video with GET /api/experimental/blob/:id. Behind the video_generate flag. Experimental: may change without compatibility guarantees.", + "description": "Submit a video job to a video model using the server's base configuration and return its ID once the provider accepted it. The server polls the job and stores the finished videos as blobs; read the job with GET /api/experimental/generate/video/:id and the video with GET /api/experimental/blob/:id. Behind the video_generate flag. Experimental: may change without compatibility guarantees.", "summary": "Create a video generation", "requestBody": { "content": { @@ -5655,7 +5655,7 @@ } } }, - "description": "Read a video job: running, completed with the video's blob, or error with a reason. Jobs are kept in memory, so a server restart forgets them; a finished video's blob stays readable. Behind the video_generate flag. Experimental: may change without compatibility guarantees.", + "description": "Read a video job: running, completed with its videos' blobs, or error with a reason. Jobs survive a server restart, which resumes polling running ones. A job is not found 24 hours after it finished, or once none of its blobs remain. Behind the video_generate flag. Experimental: may change without compatibility guarantees.", "summary": "Read a video generation" } }, @@ -12335,7 +12335,7 @@ } } }, - "description": "Stream a stored blob's bytes, such as a generated video, with single byte Range, ETag and 304 Not Modified support. Blobs are deleted 7 days after they're written. Experimental: may change without compatibility guarantees.", + "description": "Stream a stored blob's bytes, such as a generated video, with single byte Range, ETag and 304 Not Modified support. Blobs are kept until removed. Experimental: may change without compatibility guarantees.", "summary": "Read a blob" } }, @@ -16674,7 +16674,8 @@ }, "Blob.ID": { "type": "string", - "pattern": "^video_[0-9a-f]{12}[0-9A-Za-z]{14}_(0|[1-9][0-9]{0,2})$" + "pattern": "^blob_[0-9a-f]{12}[0-9A-Za-z]{14}$", + "description": "A stored blob, such as a generated video, which outlives the job that made it" }, "Blob.Info": { "type": "object", @@ -16687,13 +16688,9 @@ }, "bytes": { "type": "number" - }, - "expiresAt": { - "type": "number", - "description": "Epoch milliseconds after which the blob may be deleted. Read it with GET /api/experimental/blob/:id" } }, - "required": ["id", "mime", "bytes", "expiresAt"], + "required": ["id", "mime", "bytes"], "additionalProperties": false }, "BlobNotFoundErrorEncoded": { @@ -19916,7 +19913,7 @@ "Generate.VideoErrorReason": { "type": "string", "enum": ["failed", "cancelled", "expired", "unknown"], - "description": "failed: the provider failed the job. cancelled: the provider cancelled it. expired: the provider expired it. unknown: the provider gave no result in time" + "description": "failed: the provider failed the job. cancelled: the provider cancelled it. expired: the provider expired it. unknown: the provider gave no result in time, or the server stopped while submitting the job" }, "Generate.VideoID": { "type": "string", diff --git a/packages/protocol/src/groups/blob.ts b/packages/protocol/src/groups/blob.ts index 3c4d76440cd..f90af50b0d2 100644 --- a/packages/protocol/src/groups/blob.ts +++ b/packages/protocol/src/groups/blob.ts @@ -13,7 +13,7 @@ export const BlobGetEndpoint = HttpApiEndpoint.get("blob.get", "/api/experimenta identifier: "experimental.blob.get", summary: "Read a blob", description: - "Stream a stored blob's bytes, such as a generated video, with single byte Range, ETag and 304 Not Modified support. Blobs are deleted 7 days after they're written. Experimental: may change without compatibility guarantees.", + "Stream a stored blob's bytes, such as a generated video, with single byte Range, ETag and 304 Not Modified support. Blobs are kept until removed. Experimental: may change without compatibility guarantees.", // The route shares the `server.experimental` group with the persistent PTY prototype; tag it on its own. transform: (operation) => ({ ...operation, tags: ["experimental"] }), }), diff --git a/packages/protocol/src/groups/generate.ts b/packages/protocol/src/groups/generate.ts index 388502dc040..d85d441a2b5 100644 --- a/packages/protocol/src/groups/generate.ts +++ b/packages/protocol/src/groups/generate.ts @@ -81,7 +81,7 @@ export const GenerateGroup = HttpApiGroup.make("server.generate") identifier: "experimental.generate.video.create", summary: "Create a video generation", description: - "Submit a video job to a video model using the server's base configuration and return its ID once the provider accepted it. The server polls the job and stores the finished video as a blob for 7 days; read the job with GET /api/experimental/generate/video/:id and the video with GET /api/experimental/blob/:id. Behind the video_generate flag. Experimental: may change without compatibility guarantees.", + "Submit a video job to a video model using the server's base configuration and return its ID once the provider accepted it. The server polls the job and stores the finished videos as blobs; read the job with GET /api/experimental/generate/video/:id and the video with GET /api/experimental/blob/:id. Behind the video_generate flag. Experimental: may change without compatibility guarantees.", }), ), ) @@ -95,7 +95,7 @@ export const GenerateGroup = HttpApiGroup.make("server.generate") identifier: "experimental.generate.video.get", summary: "Read a video generation", description: - "Read a video job: running, completed with the video's blob, or error with a reason. Jobs are kept in memory, so a server restart forgets them; a finished video's blob stays readable. Behind the video_generate flag. Experimental: may change without compatibility guarantees.", + "Read a video job: running, completed with its videos' blobs, or error with a reason. Jobs survive a server restart, which resumes polling running ones. A job is not found 24 hours after it finished, or once none of its blobs remain. Behind the video_generate flag. Experimental: may change without compatibility guarantees.", }), ), ) diff --git a/packages/schema/src/blob-store.ts b/packages/schema/src/blob-store.ts index eebe00161d4..6bc060129f7 100644 --- a/packages/schema/src/blob-store.ts +++ b/packages/schema/src/blob-store.ts @@ -1,14 +1,20 @@ export * as BlobStore from "./blob-store.js" import { Schema } from "effect" +import { descending } from "./identifier.js" +import { statics } from "./schema.js" -/** - * The ID of what made the blob and the blob's position among its outputs: `video__0` is a video job's first - * video. The prefix says what kind of blob it is. Strict, because the server names files after it. - */ -export const ID = Schema.String.check( - Schema.isPattern(/^video_[0-9a-f]{12}[0-9A-Za-z]{14}_(0|[1-9][0-9]{0,2})$/u), -).pipe(Schema.brand("Blob.ID"), Schema.annotate({ identifier: "Blob.ID" })) +// Strict, because the server names files after it. +export const ID = Schema.String.check(Schema.isPattern(/^blob_[0-9a-f]{12}[0-9A-Za-z]{14}$/u)).pipe( + Schema.brand("Blob.ID"), + Schema.annotate({ + identifier: "Blob.ID", + description: "A stored blob, such as a generated video, which outlives the job that made it", + }), + statics((schema) => ({ + create: () => schema.make("blob_" + descending()), + })), +) export type ID = typeof ID.Type export interface Info extends Schema.Schema.Type {} @@ -16,7 +22,4 @@ export const Info = Schema.Struct({ id: ID, mime: Schema.String, bytes: Schema.Finite, - expiresAt: Schema.Finite.annotate({ - description: "Epoch milliseconds after which the blob may be deleted. Read it with GET /api/experimental/blob/:id", - }), }).annotate({ identifier: "Blob.Info" }) diff --git a/packages/schema/src/generate.ts b/packages/schema/src/generate.ts index 89cf69c0b42..6c346da8661 100644 --- a/packages/schema/src/generate.ts +++ b/packages/schema/src/generate.ts @@ -131,7 +131,7 @@ export const VideoRequest = Schema.Struct({ export const VideoErrorReason = Schema.Literals(["failed", "cancelled", "expired", "unknown"]).annotate({ identifier: "Generate.VideoErrorReason", description: - "failed: the provider failed the job. cancelled: the provider cancelled it. expired: the provider expired it. unknown: the provider gave no result in time", + "failed: the provider failed the job. cancelled: the provider cancelled it. expired: the provider expired it. unknown: the provider gave no result in time, or the server stopped while submitting the job", }) export type VideoErrorReason = typeof VideoErrorReason.Type diff --git a/packages/server/src/handlers/blob.ts b/packages/server/src/handlers/blob.ts index 98d3bddb13b..7fa0ca21f53 100644 --- a/packages/server/src/handlers/blob.ts +++ b/packages/server/src/handlers/blob.ts @@ -19,7 +19,7 @@ export const makeBlobGet = Effect.gen(function* () { const etag = `"${id}"` const headers = { ...ContentHeaders.download({ mime: blob.mime }), - "cache-control": "private, max-age=604800, immutable", + "cache-control": "private, max-age=31536000, immutable", etag, "accept-ranges": "bytes", } diff --git a/packages/server/test/video-generate.test.ts b/packages/server/test/video-generate.test.ts index cb174eca88e..540cab7e723 100644 --- a/packages/server/test/video-generate.test.ts +++ b/packages/server/test/video-generate.test.ts @@ -79,12 +79,12 @@ it.live("generates a video in the background and serves its blob with Range and ), (body: { data: Record }) => body.data.status !== "running", ) - const blob = `${data.id}_0` expect(completed.data).toEqual({ id: data.id, status: "completed", - blobs: [{ id: blob, mime: "video/mp4", bytes: 20, expiresAt: expect.any(Number) }], + blobs: [{ id: expect.stringMatching(/^blob_/), mime: "video/mp4", bytes: 20 }], }) + const blob = (completed.data.blobs as { id: string }[])[0].id const route = `${base}/blob/${blob}` const full = yield* call(route) @@ -112,7 +112,7 @@ it.live("generates a video in the background and serves its blob with Range and expect(cached.status).toBe(304) expect((yield* Effect.promise(() => cached.arrayBuffer())).byteLength).toBe(0) - // A restarted server reads the finished job back from its blobs. + // A restarted server reads the finished job back from its record. const restarted = yield* serve(dir, true) const reread = yield* Effect.promise(() => restarted(new Request(`${base}/generate/video/${data.id}`))) expect(((yield* Effect.promise(() => reread.json())) as { data: unknown }).data).toEqual(completed.data) @@ -124,7 +124,7 @@ it.live("generates a video in the background and serves its blob with Range and expect((yield* call(`${base}/generate/video/${unknown}`)).status).toBe(404) // An ID that isn't one never reaches the disk. - expect((yield* call(`${base}/blob/video_..%2F..%2Fsecret`)).status).toBe(400) + expect((yield* call(`${base}/blob/blob_..%2F..%2Fsecret`)).status).toBe(400) }).pipe(Effect.scoped), ) From cf9d13072c4bb488bfa5352979e12f92c6751fda Mon Sep 17 00:00:00 2001 From: Brendan Allan <14191578+Brendonovich@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:12:50 +0800 Subject: [PATCH 2/8] feat(app): dispatch command shortcuts through @opentui/keymap (#64394) --- bun.lock | 1 + packages/app/component-tests/composer.spec.ts | 3 +- packages/app/package.json | 1 + .../app/src/composer/editor/interaction.ts | 25 -- packages/app/src/composer/model.ts | 20 +- packages/app/src/runtime/i18n/en.ts | 1 + .../app/src/shell/commands/command.test.ts | 31 --- packages/app/src/shell/commands/command.tsx | 146 ++-------- .../app/src/shell/commands/keymap.test.ts | 159 +++++++++++ packages/app/src/shell/commands/keymap.ts | 257 ++++++++++++++++++ .../app/test-browser/composer-ime.test.ts | 29 +- 11 files changed, 476 insertions(+), 197 deletions(-) create mode 100644 packages/app/src/shell/commands/keymap.test.ts create mode 100644 packages/app/src/shell/commands/keymap.ts diff --git a/bun.lock b/bun.lock index c34eb189eac..01aad3f8b35 100644 --- a/bun.lock +++ b/bun.lock @@ -66,6 +66,7 @@ "@opencode/session-ui": "workspace:*", "@opencode/ui": "workspace:*", "@opencode/util": "workspace:*", + "@opentui/keymap": "catalog:", "@pierre/highlights": "catalog:", "@pierre/trees": "1.0.0-beta.6", "@sentry/solid": "catalog:", diff --git a/packages/app/component-tests/composer.spec.ts b/packages/app/component-tests/composer.spec.ts index 974cd782497..3fb3fde481d 100644 --- a/packages/app/component-tests/composer.spec.ts +++ b/packages/app/component-tests/composer.spec.ts @@ -216,7 +216,8 @@ story( await input.fill("") await input.press("ArrowUp") await expect(input).toHaveText("Explain the latest changes") - await input.press("ControlOrMeta+u") + await component.getByRole("button", { name: "Add images and files", exact: true }).click() + await page.getByRole("menuitem", { name: /^Images and files/ }).click() await input.press("ArrowDown") await expect(input).toBeEmpty() }, diff --git a/packages/app/package.json b/packages/app/package.json index 6b76d843204..08fe999299d 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -67,6 +67,7 @@ "@opencode/session-ui": "workspace:*", "@opencode/ui": "workspace:*", "@opencode/util": "workspace:*", + "@opentui/keymap": "catalog:", "@pierre/highlights": "catalog:", "@pierre/trees": "1.0.0-beta.6", "@sentry/solid": "catalog:", diff --git a/packages/app/src/composer/editor/interaction.ts b/packages/app/src/composer/editor/interaction.ts index 41a149a0ded..bc73927b3d9 100644 --- a/packages/app/src/composer/editor/interaction.ts +++ b/packages/app/src/composer/editor/interaction.ts @@ -474,19 +474,6 @@ export function createComposerEditor(input: { flushFocus() - if ( - mode() === "normal" && - (event.metaKey || event.ctrlKey) && - !event.altKey && - !event.shiftKey && - event.key.toLowerCase() === "u" - ) { - event.preventDefault() - attach() - - return true - } - const ctrl = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey const open = isComposerPopoverOpen(readState()) @@ -537,18 +524,6 @@ export function createComposerEditor(input: { return true } - const stop = - (input.view.submit.working?.() || input.view.submit.held?.()) && - ((event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "g") || - event.key === "Escape") - - if (stop) { - event.preventDefault() - input.view.submit.onStop() - - return true - } - if ( !event.altKey && !event.ctrlKey && diff --git a/packages/app/src/composer/model.ts b/packages/app/src/composer/model.ts index c4c4a931c7c..9520c38c73b 100644 --- a/packages/app/src/composer/model.ts +++ b/packages/app/src/composer/model.ts @@ -2,7 +2,7 @@ import { ImagePreview } from "@opencode/ui/image-preview" import { useDialog } from "@opencode/ui/context/dialog" import type { ReferenceInfo } from "@opencode/client/promise" import type { Links, MountedSession } from "@opencode/plugin/gui" -import { createComponent, createEffect, createMemo, on, onCleanup } from "solid-js" +import { createComponent, createEffect, createMemo, createSignal, on, onCleanup } from "solid-js" import { Predicate } from "effect" import type { ComposerSuggestion } from "./types" import { createComposerEditor, type ComposerEditorModel } from "./editor/interaction" @@ -33,6 +33,7 @@ import type { PromptHistoryComment } from "./history/entry" import { createComposerHistory } from "./history/store" import { createComposerSubmit } from "./submit" import { composerSubmitView } from "./machine" +import { isComposerPopoverOpen } from "./suggestions/machine" import { useAttachmentDestination } from "./attachments/destination" import { parseClientSlashCommand } from "./client-slash-command" @@ -73,6 +74,8 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? ), ) let editor: HTMLDivElement | undefined + // The element `prompt.stop` binds its keys to. + const [editorElement, setEditorElement] = createSignal() // A path attachment's image is read through the server, which can see both local and uploaded paths. const pathImages = new Map>() const pathImageReads = new AbortController() @@ -457,6 +460,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? onEditor(element) { // SAFETY: the editor's only `setEditor` call passes its editable root, a `
` (`editor/editor.tsx`). editor = element as HTMLDivElement + setEditorElement(editor) if (adapter.kind === "active-session") adapter.setEditor(editor) }, @@ -607,6 +611,20 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? disabled: mode() === "normal", onSelect: () => void controller.dispatch({ type: "mode.normal" }), }, + { + id: "prompt.stop", + title: language.t("command.prompt.stop"), + category: language.t("command.category.session"), + keybind: "escape,ctrl+g", + editable: true, + target: editorElement, + disabled: !adapter.working() && !submitView().held, + // An open list, a queued prompt being edited and shell mode each take the key first in the editor. + skip: (event) => + isComposerPopoverOpen(controller.state) || + (event.key === "Escape" && (!!options?.queue?.editing() || mode() === "shell")), + onSelect: () => void submission.stop(), + }, ]) // SAFETY: the `model` getter defined on the controller above completes `ComposerModel`. diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index 5cde85e6411..9335b49977d 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -105,6 +105,7 @@ export const dict = { "command.prompt.mode.shell": "Shell", "command.prompt.mode.normal": "Prompt", "command.prompt.mode.toggle": "Toggle shell mode", + "command.prompt.stop": "Stop session", "command.permissions.autoaccept.enable": "Auto-accept permissions", "command.permissions.autoaccept.disable": "Stop auto-accepting permissions", "command.permissions.autoaccept.project": "Auto-accept permissions for this project", diff --git a/packages/app/src/shell/commands/command.test.ts b/packages/app/src/shell/commands/command.test.ts index 72ddf29c6e1..aee190e37fa 100644 --- a/packages/app/src/shell/commands/command.test.ts +++ b/packages/app/src/shell/commands/command.test.ts @@ -5,11 +5,9 @@ import { addCommandRegistration, commandPaletteOptions, CommandCatalog, - commandKeymap, formatKeybind, matchKeybind, parseKeybind, - resolveKeybindOption, type CommandOption, } from "./command" @@ -62,35 +60,6 @@ test("command registrations shadow keyed owners, restore the previous owner, and expect(unkeyed.map((entry) => entry.options)).toEqual([two, one]) }) -test.each([true, false])("resolveKeybindOption prefers a contextual command only in its context: %p", (inside) => { - const fallback = { id: "tab.close", title: "Close tab" } - const contextual = { id: "terminal.close", title: "Close terminal", when: () => inside } - - expect(resolveKeybindOption([fallback, contextual], new KeyboardEvent("keydown"))).toBe( - inside ? contextual : fallback, - ) -}) - -test("commandKeymap puts a user's binding before a default on the same keys", () => { - const rename = { id: "session.rename", title: "Rename session", keybind: "ctrl+r" } - const focus = { id: "input.focus", title: "Focus input", keybind: "ctrl+r" } - const event = new KeyboardEvent("keydown", { key: "r", ctrlKey: true }) - const keymap = (custom: string[]) => commandKeymap([rename, focus], (id) => custom.includes(id)).get("r:1") - - expect(resolveKeybindOption(keymap([]), event)).toBe(rename) - expect(resolveKeybindOption(keymap(["input.focus"]), event)).toBe(focus) - expect(commandKeymap([{ ...rename, disabled: true }], () => false).size).toBe(0) -}) - -test.each([true, false])("resolveKeybindOption leaves the key to a skipping command's target: %p", (inside) => { - const rename = { id: "session.rename", title: "Rename session", skip: () => inside } - const focus = { id: "input.focus", title: "Focus input" } - const event = new KeyboardEvent("keydown") - - expect(resolveKeybindOption([rename], event)).toBe(inside ? undefined : rename) - expect(resolveKeybindOption([rename, focus], event)).toBe(inside ? focus : rename) -}) - describe("command keybinds", () => { test("parseKeybind handles aliases, multiple combos, and disabled bindings", () => { const keybinds = parseKeybind("control+option+k, mod+shift+comma") diff --git a/packages/app/src/shell/commands/command.tsx b/packages/app/src/shell/commands/command.tsx index 7c916ee63a0..0b9e73091ba 100644 --- a/packages/app/src/shell/commands/command.tsx +++ b/packages/app/src/shell/commands/command.tsx @@ -4,15 +4,15 @@ import { type Accessor, batch, createEffect, createMemo, createSignal, onCleanup import { createStore, produce, reconcile } from "solid-js/store" import { Predicate, Schema } from "effect" import { Persistence } from "@/runtime/persistence/schema" -import { makeEventListener } from "@solid-primitives/event-listener" import { useLanguage } from "@/runtime/i18n/language" import { useSettings } from "@/settings/model" import { keybindRenames } from "@/settings/keybinds/migration" import en from "@/runtime/i18n/en" import { Persist, persisted } from "@/runtime/persistence/storage" import { INITIAL_KEYBIND_SUSPEND_STATE, selectKeybindsSuspended, transitionKeybindSuspend } from "./suspend-machine" +import { createAppKeymap, IS_MAC, keyFromKeyboardEvent, registerCommandLayers } from "./keymap" -const IS_MAC = typeof navigator !== "undefined" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform) +export { keyFromKeyboardEvent } const PALETTE_ID = "command.palette" @@ -50,51 +50,6 @@ function actionId(id: string) { return id.slice(SUGGESTED_PREFIX.length) } -function normalizeKey(key: string) { - if (key === ",") return "comma" - - if (key === "+") return "plus" - - if (key === " ") return "space" - - return key.toLowerCase() -} - -export function keyFromKeyboardEvent(event: KeyboardEvent) { - const key = normalizeKey(physicalKey(event)) - - if (!event.altKey || /^[a-z0-9]$/.test(key)) return key - - if (!event.code.startsWith("Key") || event.code.length !== 4) return key - - return event.code.slice(3).toLowerCase() -} - -// ⇧[ types { and ⌥. types ≥ on US layouts. Keep ASCII layout mappings; non-ASCII falls back to the physical key. -function physicalKey(event: Pick) { - if (event.key === "{" || event.key === "}") return event.key === "{" ? "[" : "]" - - if (!/^[^\x00-\x7f]$/u.test(event.key)) return event.key - - if (event.code === "BracketLeft") return "[" - - if (event.code === "BracketRight") return "]" - - if (event.code === "Period") return "." - - return event.key -} - -function signature(key: string, ctrl: boolean, meta: boolean, shift: boolean, alt: boolean) { - const mask = (ctrl ? 1 : 0) | (meta ? 2 : 0) | (shift ? 4 : 0) | (alt ? 8 : 0) - - return `${key}:${mask}` -} - -function signatureFromEvent(event: KeyboardEvent) { - return signature(keyFromKeyboardEvent(event), event.ctrlKey, event.metaKey, event.shiftKey, event.altKey) -} - type KeybindConfig = string export interface Keybind { @@ -134,6 +89,8 @@ export interface CommandOption { hidden?: boolean /** The keybind also fires while a text field has focus. */ editable?: boolean + /** The keybind fires only while focus is inside this element, ahead of keybinds without one. */ + target?: () => HTMLElement | undefined when?: (event: KeyboardEvent) => boolean /** The keybind leaves this event to its target, as if the command had no keybind. */ skip?: (event: KeyboardEvent) => boolean @@ -149,37 +106,6 @@ export function commandPaletteOptions(options: CommandOption[]) { ) } -/** Maps each keybind signature to its commands. A user's own binding comes before a default on the same keys. */ -export function commandKeymap(options: CommandOption[], custom: (id: string) => boolean) { - const map = new Map() - - for (const option of options) { - if (option.id.startsWith(SUGGESTED_PREFIX)) continue - - if (option.disabled) continue - - if (!option.keybind) continue - - const keybinds = parseKeybind(option.keybind) - - for (const kb of keybinds) { - if (!kb.key) continue - const sig = signature(kb.key, kb.ctrl, kb.meta, kb.shift, kb.alt) - const existing = map.get(sig) ?? [] - - map.set(sig, custom(actionId(option.id)) ? [option, ...existing] : [...existing, option]) - } - } - - return map -} - -export function resolveKeybindOption(candidates: CommandOption[] | undefined, event: KeyboardEvent) { - const live = candidates?.filter((option) => !option.skip?.(event)) - - return live?.find((option) => option.when?.(event)) ?? live?.find((option) => !option.when) -} - export type CommandSource = "palette" | "keybind" | "slash" const CommandCatalogItem = Persistence.struct({ @@ -398,8 +324,9 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex const [catalog, setCatalog, _, catalogReady] = persisted(Persist.global("command.catalog.v1"), CommandCatalog, {}) const bind = (id: string, def: KeybindConfig | undefined, follows?: string) => { - const custom = settings.keybinds.get(actionId(id)) ?? (follows ? settings.keybinds.get(follows) : undefined) - const config = custom ?? def + const base = actionId(id) + const custom = settings.keybinds.get(base) ?? (follows ? settings.keybinds.get(follows) : undefined) + const config = custom ?? (base === PALETTE_ID ? DEFAULT_PALETTE_KEYBIND : def) if (!config || config === "none") return @@ -467,6 +394,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex const resolved = registered().map((opt) => ({ ...opt, keybind: bind(opt.id, opt.keybind, opt.follows), + editable: opt.editable || opt.id === PALETTE_ID, })) const suggested = resolved.filter((x) => x.suggested && !x.disabled) @@ -483,15 +411,26 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex const suspended = () => selectKeybindsSuspended(suspendState()) - const palette = createMemo(() => { - const config = settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND - const keybinds = parseKeybind(config) + const app = createAppKeymap({ blocked: () => suspended() || !!dialog.active, editable: isEditableTarget }) - return new Set(keybinds.map((kb) => signature(kb.key, kb.ctrl, kb.meta, kb.shift, kb.alt))) + onCleanup(app.destroy) + + createEffect(() => { + const bound = options().filter((option) => !option.id.startsWith(SUGGESTED_PREFIX) && !option.disabled) + + // The palette's keys come first, so they win over any other command on the same keys. + onCleanup( + registerCommandLayers( + app.keymap, + [ + ...bound.filter((option) => option.id === PALETTE_ID), + ...bound.filter((option) => option.id !== PALETTE_ID), + ], + (id) => settings.keybinds.get(id) !== undefined, + ), + ) }) - const keymap = createMemo(() => commandKeymap(options(), (id) => settings.keybinds.get(id) !== undefined)) - const optionMap = createMemo(() => { const map = new Map() @@ -513,40 +452,6 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex run(PALETTE_ID, "palette") } - const handleKeyDown = (event: KeyboardEvent) => { - if (suspended() || dialog.active) return - - const sig = signatureFromEvent(event) - const isPalette = palette().has(sig) - const option = resolveKeybindOption(keymap().get(sig), event) - const modified = event.ctrlKey || event.metaKey || event.altKey - const isTab = event.key === "Tab" - - if (isEditableTarget(event.target) && !isPalette && !option?.editable && !modified && !isTab) return - - if (isPalette) { - event.preventDefault() - event.stopPropagation() - showPalette() - - return - } - - if (!option) return - - // A command that returns false declines the key, which goes on to its target. - const result = option.onSelect?.("keybind") - - if (result === false) return - event.preventDefault() - event.stopPropagation() - void result - } - - onMount(() => { - makeEventListener(document, "keydown", handleKeyDown, { capture: true }) - }) - function register(cb: () => CommandOption[]): void function register(key: string, cb: () => CommandOption[]): void function register(key: string | (() => CommandOption[]), cb?: () => CommandOption[]) { @@ -570,7 +475,6 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex } const keybindConfig = (id: string) => { - if (id === PALETTE_ID) return settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND const base = actionId(id) return ( diff --git a/packages/app/src/shell/commands/keymap.test.ts b/packages/app/src/shell/commands/keymap.test.ts new file mode 100644 index 00000000000..15c3cc934e3 --- /dev/null +++ b/packages/app/src/shell/commands/keymap.test.ts @@ -0,0 +1,159 @@ +import { afterEach, expect, test } from "bun:test" +import type { CommandOption } from "./command" +import { createAppKeymap, registerCommandLayers } from "./keymap" + +const cleanup: (() => void)[] = [] + +afterEach(() => { + cleanup.splice(0).forEach((dispose) => dispose()) + document.body.replaceChildren() +}) + +function setup(options: CommandOption[], input?: { custom?: string[]; blocked?: () => boolean }) { + const app = createAppKeymap({ + blocked: input?.blocked ?? (() => false), + editable: (target) => target instanceof HTMLElement && target.isContentEditable, + }) + + const layers = registerCommandLayers(app.keymap, options, (id) => input?.custom?.includes(id) ?? false) + + cleanup.push(() => { + layers() + app.destroy() + }) + + return app +} + +function press(target: HTMLElement, init: KeyboardEventInit) { + const event = new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init }) + target.dispatchEvent(event) + + return event +} + +function editor() { + const element = document.createElement("div") + element.contentEditable = "true" + document.body.append(element) + element.focus() + + return element +} + +function command(id: string, keybind: string, ran: string[], extra?: Partial): CommandOption { + return { id, title: id, keybind, onSelect: () => void ran.push(id), ...extra } +} + +// happy-dom never reports a Mac platform, so mod is Ctrl here. +test("a command with a when wins only in its context, then a user's binding, then the first registered", () => { + const ran: string[] = [] + const inside = { value: true } + setup( + [ + command("tab.close", "mod+w", ran), + command("file.close", "mod+w", ran), + command("terminal.close", "mod+w", ran, { when: () => inside.value }), + ], + { custom: ["file.close"] }, + ) + + press(document.body, { key: "w", ctrlKey: true }) + inside.value = false + press(document.body, { key: "w", ctrlKey: true }) + + expect(ran).toEqual(["terminal.close", "file.close"]) +}) + +test("a declining command passes the key to the next command, and finally to the focused element", () => { + const ran: string[] = [] + const skip = { value: true } + setup([ + command("session.rename", "ctrl+r", ran, { skip: () => skip.value }), + command("plugin.run", "ctrl+r", ran, { onSelect: () => (ran.push("plugin.run"), false) }), + ]) + + const declined = press(document.body, { key: "r", ctrlKey: true }) + skip.value = false + const handled = press(document.body, { key: "r", ctrlKey: true }) + + expect(ran).toEqual(["plugin.run", "session.rename"]) + expect(declined.defaultPrevented).toBe(false) + expect(handled.defaultPrevented).toBe(true) +}) + +test("a key that types a character fires in a text field only for an editable command", () => { + const ran: string[] = [] + setup([ + command("review.next", "j", ran), + command("prompt.stop", "escape", ran, { editable: true }), + command("model.choose", "mod+'", ran), + ]) + const field = editor() + + const typed = press(field, { key: "j" }) + press(field, { key: "Escape" }) + press(field, { key: "'", ctrlKey: true }) + field.blur() + press(document.body, { key: "j" }) + + expect(typed.defaultPrevented).toBe(false) + expect(ran).toEqual(["prompt.stop", "model.choose", "review.next"]) +}) + +test("a focus target's command wins inside the target and is absent outside it", () => { + const ran: string[] = [] + const field = editor() + const outside = document.createElement("button") + document.body.append(outside) + setup([ + command("dialog.close", "escape", ran, { editable: true }), + command("prompt.stop", "escape", ran, { editable: true, target: () => field }), + ]) + + press(field, { key: "Escape" }) + outside.focus() + press(outside, { key: "Escape" }) + + expect(ran).toEqual(["prompt.stop", "dialog.close"]) +}) + +test.each([ + { name: "composing", init: { key: "Escape", isComposing: true } }, + { name: "Safari's composition Enter", init: { key: "Escape", keyCode: 229 } }, +])("keys are left to the IME while it composes: $name", (row) => { + const ran: string[] = [] + setup([command("prompt.stop", "escape", ran, { editable: true })]) + + const event = press(editor(), row.init) + + expect(event.defaultPrevented).toBe(false) + expect(ran).toEqual([]) +}) + +test("keys are left alone while keybinds are blocked", () => { + const ran: string[] = [] + const blocked = { value: true } + setup([command("palette", "mod+k", ran)], { blocked: () => blocked.value }) + + press(document.body, { key: "k", ctrlKey: true }) + blocked.value = false + press(document.body, { key: "k", ctrlKey: true }) + + expect(ran).toEqual(["palette"]) +}) + +test.each([ + { keybind: "mod+alt+.", init: { key: "≥", code: "Period", ctrlKey: true, altKey: true } }, + { keybind: "mod+shift+[", init: { key: "{", code: "BracketLeft", ctrlKey: true, shiftKey: true } }, + { keybind: "alt+arrowup", init: { key: "ArrowUp", altKey: true } }, + { keybind: "mod+comma", init: { key: ",", ctrlKey: true } }, + { keybind: "shift+enter", init: { key: "Enter", shiftKey: true } }, +])("$keybind matches the key the layout types", (row) => { + const ran: string[] = [] + setup([command("run", row.keybind, ran)]) + + press(document.body, row.init) + + expect(ran).toEqual(["run"]) +}) diff --git a/packages/app/src/shell/commands/keymap.ts b/packages/app/src/shell/commands/keymap.ts new file mode 100644 index 00000000000..c8efe7ec954 --- /dev/null +++ b/packages/app/src/shell/commands/keymap.ts @@ -0,0 +1,257 @@ +import { Keymap, type KeymapHost } from "@opentui/keymap" +import { registerDefaultBindingParser } from "@opentui/keymap/addons" +import { createHtmlKeymapHost, type HtmlKeymapEvent } from "@opentui/keymap/html" +import type { CommandOption } from "./command" + +export const IS_MAC = typeof navigator !== "undefined" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform) + +export type AppKeymap = Keymap + +/** + * The keymap behind every command keybind. It reads keys in the capture phase on the document root, before the + * focused element sees them. + */ +export function createAppKeymap(input: { blocked: () => boolean; editable: (target: EventTarget | null) => boolean }) { + const host = createAppKeymapHost(document.documentElement, input.blocked) + const keymap: AppKeymap = new Keymap(host.host) + // Every binding is written by `keymapKey`: one `+`-joined combo. + keymap.prependBindingParser((ctx) => { + if (ctx.index !== 0) return + + return { + parts: [ctx.parseObjectKey(strokeInput(ctx.input.trim()), { display: ctx.input })], + nextIndex: ctx.input.length, + } + }) + registerDefaultBindingParser(keymap) + keymap.prependEventMatchResolver((event, ctx) => { + const original = event.originalEvent + + if (!original) return + + const name = keymapKeyName(keyFromKeyboardEvent(original)) + const alias = KEY_ALIASES.get(name) + + const stroke = { + name, + ctrl: original.ctrlKey, + shift: original.shiftKey, + meta: original.altKey, + super: original.metaKey, + } + + return (alias ? [name, alias] : [name]).flatMap((name) => [ + ctx.resolveKey({ ...stroke, name }), + // `shift+/` types `?`, so `?` binds the symbol whichever modifier the layout needs. + ...(stroke.shift && name.length === 1 && !/^[a-z0-9]$/.test(name) + ? [ctx.resolveKey({ ...stroke, name, shift: false })] + : []), + ]) + }) + // A binding whose key types a character stays out of text fields, so typing in them is never taken. + keymap.registerBindingFields({ + outsideText(value, ctx) { + if (value === true) ctx.activeWhen(() => !input.editable(document.activeElement)) + }, + }) + + return { keymap, destroy: host.destroy } +} + +/** + * Registers the keybinds of `options`: one global layer, plus one layer per focus target, which wins over the global + * one while focus is inside it. On the same keys a command with a `when` comes first, then a user's own binding, then + * the order given. A command declines a key by returning false from `onSelect`, or through `when` and `skip`; the key + * then goes to the next command, and finally to the focused element. + */ +export function registerCommandLayers(keymap: AppKeymap, options: CommandOption[], custom: (id: string) => boolean) { + const layers = new Map() + + options + .map((option, index) => ({ option, index, rank: (option.when ? 2 : 0) + (custom(option.id) ? 1 : 0) })) + .sort((a, b) => b.rank - a.rank || a.index - b.index) + .forEach(({ option }) => { + if (!option.keybind) return + const target = option.target?.() + + if (option.target && !target) return + layers.set(target, [...(layers.get(target) ?? []), option]) + }) + + const disposers = Array.from(layers, ([target, options]) => + keymap.registerLayer({ + target, + priority: target ? 1 : 0, + commands: options.map((option) => ({ + name: option.id, + run(ctx) { + const event = ctx.event.originalEvent + + if (event && option.skip?.(event)) return false + + if (event && option.when && !option.when(event)) return false + + return option.onSelect?.("keybind") !== false + }, + })), + bindings: options.flatMap((option) => + option + .keybind!.split(",") + .map((combo) => combo.trim()) + .filter((combo) => combo && combo !== "none") + .map((combo) => { + const key = keymapKey(combo) + + return { key, cmd: option.id, outsideText: !option.editable && typesCharacter(keymap, key) } + }), + ), + }), + ) + + return () => disposers.forEach((dispose) => dispose()) +} + +/** Translates one combo of the app's keybind syntax (`mod+shift+arrowup`) into the keymap's. */ +export function keymapKey(combo: string) { + return combo + .trim() + .split("+") + .map((part) => { + const lower = part.toLowerCase() + + if (lower === "mod") return IS_MAC ? "super" : "ctrl" + + if (lower === "meta" || lower === "cmd" || lower === "command") return "super" + + return MODIFIER_PARTS.has(lower) ? lower : keymapKeyName(lower) + }) + .join("+") +} + +// One stroke as `keymapKey` writes it, such as `super+shift+[`. +function strokeInput(stroke: string) { + const parts = stroke.split("+") + const has = (...names: string[]) => parts.some((part) => names.includes(part)) + + return { + name: parts.findLast((part) => !MODIFIER_PARTS.has(part)) ?? parts.at(-1)!, + ctrl: has("ctrl", "control"), + shift: has("shift"), + meta: has("alt", "option"), + super: has("super"), + hyper: has("hyper") || undefined, + } +} + +/** Whether a keymap key types a character, so it should stay out of text fields. */ +export function typesCharacter(keymap: AppKeymap, key: string) { + const first = keymap.parseKeySequence(key)[0]?.stroke + + if (!first) return false + + return !first.ctrl && !first.meta && !first.super && first.name !== "tab" +} + +export function keyFromKeyboardEvent(event: KeyboardEvent) { + const key = normalizeKey(physicalKey(event)) + + if (!event.altKey || /^[a-z0-9]$/.test(key)) return key + + if (!event.code.startsWith("Key") || event.code.length !== 4) return key + + return event.code.slice(3).toLowerCase() +} + +const MODIFIER_PARTS = new Set(["ctrl", "control", "shift", "alt", "option", "super", "hyper"]) + +const KEY_NAMES = new Map([ + ["arrowup", "up"], + ["arrowdown", "down"], + ["arrowleft", "left"], + ["arrowright", "right"], + ["esc", "escape"], + ["enter", "return"], +]) + +// The app writes these keys by name and the keymap parser reads both forms, so events resolve to each. +const KEY_ALIASES = new Map([ + ["comma", ","], + ["plus", "+"], +]) + +function keymapKeyName(key: string) { + return KEY_NAMES.get(key) ?? key +} + +function normalizeKey(key: string) { + if (key === ",") return "comma" + + if (key === "+") return "plus" + + if (key === " ") return "space" + + return key.toLowerCase() +} + +// ⇧[ types { and ⌥. types ≥ on US layouts. Keep ASCII layout mappings; non-ASCII falls back to the physical key. +function physicalKey(event: Pick) { + if (event.key === "{" || event.key === "}") return event.key === "{" ? "[" : "]" + + if (!/^[^\x00-\x7f]$/u.test(event.key)) return event.key + + if (event.code === "BracketLeft") return "[" + + if (event.code === "BracketRight") return "]" + + if (event.code === "Period") return "." + + return event.key +} + +// The HTML host, except that it drops keys while an IME composes or while command keybinds are blocked, and that +// its owner can destroy it, which disposes the keymap. +function createAppKeymapHost(root: HTMLElement, blocked: () => boolean) { + const host = createHtmlKeymapHost(root) + const destroyed = new Set<() => void>() + const state = { destroyed: false } + + const keymapHost: KeymapHost = { + metadata: host.metadata, + rootTarget: host.rootTarget, + get isDestroyed() { + return state.destroyed + }, + onDestroy(listener) { + destroyed.add(listener) + + return () => destroyed.delete(listener) + }, + getFocusedTarget: () => host.getFocusedTarget(), + getParentTarget: (target) => host.getParentTarget(target), + isTargetDestroyed: (target) => host.isTargetDestroyed(target), + onKeyPress: (listener) => + host.onKeyPress((event) => { + const original = event.originalEvent + + // Escape, Enter and Tab confirm or cancel IME candidates; Safari can report them as keyCode 229. + if (original && (original.isComposing || original.keyCode === 229)) return + + if (blocked()) return + + listener(event) + }), + onKeyRelease: (listener) => host.onKeyRelease(listener), + onFocusChange: (listener) => host.onFocusChange(listener), + onTargetDestroy: (target, listener) => host.onTargetDestroy(target, listener), + createCommandEvent: () => host.createCommandEvent(), + } + + return { + host: keymapHost, + destroy() { + if (state.destroyed) return + state.destroyed = true + destroyed.forEach((listener) => listener()) + }, + } +} diff --git a/packages/app/test-browser/composer-ime.test.ts b/packages/app/test-browser/composer-ime.test.ts index 02c5c3ebbb1..4cd2c3da848 100644 --- a/packages/app/test-browser/composer-ime.test.ts +++ b/packages/app/test-browser/composer-ime.test.ts @@ -5,18 +5,15 @@ import { createComposerEditor } from "../src/composer/editor/interaction" import type { ComposerPersistedState } from "../src/composer/types" test.each([ - { key: "Escape", isComposing: true, keyCode: 27, list: false, stops: 0, selections: 0, prevented: false }, - { key: "Escape", isComposing: false, keyCode: 229, list: false, stops: 0, selections: 0, prevented: false }, - { key: "Escape", isComposing: false, keyCode: 27, list: false, stops: 1, selections: 0, prevented: true }, - { key: "Tab", isComposing: true, keyCode: 9, list: true, stops: 0, selections: 0, prevented: false }, - { key: "Tab", isComposing: false, keyCode: 229, list: true, stops: 0, selections: 0, prevented: false }, - { key: "Enter", isComposing: false, keyCode: 229, list: true, stops: 0, selections: 0, prevented: false }, - { key: "Tab", isComposing: false, keyCode: 9, list: true, stops: 0, selections: 1, prevented: true }, + { key: "Tab", isComposing: true, keyCode: 9, selections: 0, prevented: false }, + { key: "Tab", isComposing: false, keyCode: 229, selections: 0, prevented: false }, + { key: "Enter", isComposing: false, keyCode: 229, selections: 0, prevented: false }, + { key: "Tab", isComposing: false, keyCode: 9, selections: 1, prevented: true }, ])("IME key ownership: $key, composing=$isComposing, keyCode=$keyCode", (row) => { const value = createRoot((dispose) => { const store = createStore({ prompt: [], context: { items: [] } }) - const [calls, setCalls] = createStore({ stops: 0, selections: 0 }) + const [calls, setCalls] = createStore({ selections: 0 }) const editor = createComposerEditor({ store, @@ -26,10 +23,9 @@ test.each([ onSuggestionSelect: () => () => setCalls("selections", (count) => count + 1), view: { submit: { - working: () => true, stopping: () => false, onSubmit() {}, - onStop: () => setCalls("stops", (count) => count + 1), + onStop() {}, }, }, }) @@ -38,12 +34,10 @@ test.each([ }) try { - if (row.list) { - value.editor.openCommands() - value.editor.dispatch({ type: "popover.results", ids: ["review"] }) - expect(value.editor.state.popover.type).toBe("command-inline") - expect(value.editor.suggestions().map((item) => item.id)).toEqual(["review"]) - } + value.editor.openCommands() + value.editor.dispatch({ type: "popover.results", ids: ["review"] }) + expect(value.editor.state.popover.type).toBe("command-inline") + expect(value.editor.suggestions().map((item) => item.id)).toEqual(["review"]) const event = new KeyboardEvent("keydown", { key: row.key, @@ -54,11 +48,10 @@ test.each([ // happy-dom does not initialize the legacy keyCode field from KeyboardEventInit. Object.defineProperty(event, "keyCode", { value: row.keyCode }) expect(value.editor.onKeyDown(event)).toBe(true) - expect(value.calls.stops).toBe(row.stops) expect(value.calls.selections).toBe(row.selections) expect(event.defaultPrevented).toBe(row.prevented) - if (row.list && !row.selections) expect(value.editor.state.popover.type).toBe("command-inline") + if (!row.selections) expect(value.editor.state.popover.type).toBe("command-inline") } finally { value.dispose() } From 852d5ed0b30ca84ed0a2cb0c9f68c9e99aeb4252 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:28:37 -0600 Subject: [PATCH 3/8] fix(app): keep code block borders under the action fill (#64576) --- .../markdown-code-wrap.spec.ts | 20 +++++++++++++++++++ .../session-ui/src/components/markdown.css | 7 ++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/packages/session-ui/component-tests/markdown-code-wrap.spec.ts b/packages/session-ui/component-tests/markdown-code-wrap.spec.ts index 20cd548f4bd..c96dfe7f657 100644 --- a/packages/session-ui/component-tests/markdown-code-wrap.spec.ts +++ b/packages/session-ui/component-tests/markdown-code-wrap.spec.ts @@ -72,3 +72,23 @@ story("code block actions sit in the block's top corner over the block's own bac await page.keyboard.press("Shift+Tab") await expect(toolbar(block)).toHaveCSS("opacity", "1") }) + +// The fill sits over the block's 0.5px border, and one that reaches the hairline paints over it while hovered. +story("the fill behind code block actions stays inside the block's border", async ({ mount, page }) => { + const root = await mount("current-session-code-blocks--long-lines") + const block = root.locator('[data-component="markdown-code"]').nth(2) + const toolbar = block.locator('[data-slot="markdown-code-toolbar"]') + const box = (await block.boundingBox())! + await page.mouse.move(box.x + 40, box.y + box.height / 2) + await expect(toolbar).toHaveCSS("opacity", "1") + + const fill = await toolbar.evaluate((element) => { + const bar = element.getBoundingClientRect() + const style = getComputedStyle(element, "::before") + + return { top: bar.top + parseFloat(style.top), right: bar.right - parseFloat(style.right) } + }) + + expect(fill.top - box.y).toBeGreaterThanOrEqual(1) + expect(box.x + box.width - fill.right).toBeGreaterThanOrEqual(1) +}) diff --git a/packages/session-ui/src/components/markdown.css b/packages/session-ui/src/components/markdown.css index cd734776702..c396bcb13a3 100644 --- a/packages/session-ui/src/components/markdown.css +++ b/packages/session-ui/src/components/markdown.css @@ -402,13 +402,14 @@ /* Like the shell output's Copy, the ghost buttons get the block's background behind them, so code under them doesn't show through. It fades out toward the start and the bottom, so a line it reaches softens instead of - being cut, and stops inside the block's border and rounded corner. */ + being cut. It stops a pixel inside the block's 0.5px border and rounded corner: ending flush against the + hairline paints over it once the block sits at a fractional position. */ &::before { content: ""; position: absolute; z-index: -1; - inset: -3.5px -3.5px -8px -24px; - border-start-end-radius: 5.5px; + inset: -3px -3px -8px -24px; + border-start-end-radius: 6px; background: var(--markdown-code-background); mask-image: linear-gradient(to right, transparent, #000 24px), linear-gradient(#000 calc(100% - 8px), transparent); From 54b4698a72b73b200501ebcb5eae8e2be3800f2a Mon Sep 17 00:00:00 2001 From: Adam <2363879+adamdotdevin@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:38:36 -0600 Subject: [PATCH 4/8] feat(core): read Console artifacts (#64555) --- .../src/plugin/provider/opencode-artifacts.ts | 35 +++++++++++-- .../provider-opencode-artifacts.test.ts | 51 +++++++++++++++++-- 2 files changed, 79 insertions(+), 7 deletions(-) diff --git a/packages/core/src/plugin/provider/opencode-artifacts.ts b/packages/core/src/plugin/provider/opencode-artifacts.ts index 96f25ef9d60..8775364f562 100644 --- a/packages/core/src/plugin/provider/opencode-artifacts.ts +++ b/packages/core/src/plugin/provider/opencode-artifacts.ts @@ -15,6 +15,12 @@ type Connection = NonNullable publish(slug, input, true)), Effect.map((published) => ({ url: published.url })), ), - // Console has no API that returns an artifact's files. - read: () => Effect.fail(new Error("OpenCode Console can't return an artifact's files yet")), + // Console inlines UTF-8 text files up to a limit; the rest download as blobs of the same revision. + read: (id) => + Effect.gen(function* () { + const slug = yield* slugOf(id) + const send = yield* sender(ctx, http, connection, slug) + const listing = yield* send("GET", `/api/artifacts/${slug}/files`).pipe( + Effect.flatMap(HttpClientResponse.schemaBodyJson(Files)), + ) + const files = yield* Effect.forEach( + listing.files, + (file) => + file.text !== undefined + ? Effect.succeed([file.path, new TextEncoder().encode(file.text)] as const) + : send("GET", `/api/artifacts/${slug}/blobs/${file.sha256}?revision=${listing.revision}`).pipe( + Effect.flatMap((response) => response.arrayBuffer), + Effect.map((bytes) => [file.path, new Uint8Array(bytes)] as const), + ), + { concurrency: 4 }, + ) + return Object.fromEntries(files) + }).pipe(Effect.scoped), delete: (id) => Effect.gen(function* () { const slug = yield* slugOf(id) @@ -151,7 +176,7 @@ const sender = Effect.fnUntraced(function* ( const credential = yield* ctx.integration.connection.resolve(connection) if (!credential || credential.type === "external") return yield* Effect.fail(new Error("OpenCode Console is not connected")) - return (method: "POST" | "PUT" | "DELETE", path: string, body?: Uint8Array | object) => { + return (method: "GET" | "POST" | "PUT" | "DELETE", path: string, body?: Uint8Array | object) => { const request = HttpClientRequest.make(method)(`${ConsoleAccess.server(credential)}${path}`).pipe( HttpClientRequest.acceptJson, HttpClientRequest.setHeaders(ConsoleAccess.headers(credential)), @@ -177,7 +202,9 @@ const sender = Effect.fnUntraced(function* ( problem?.owner !== undefined ? `${problem.owner} already shared an OpenCode Console artifact named ${slug}; give this one another title` : response.status === 404 - ? "Artifacts are off for this OpenCode Console workspace" + ? method === "GET" + ? `OpenCode Console has no artifact named ${slug}` + : "Artifacts are off for this OpenCode Console workspace" : (problem?.message ?? `OpenCode Console answered ${response.status}`), ), ), diff --git a/packages/core/test/plugin/provider-opencode-artifacts.test.ts b/packages/core/test/plugin/provider-opencode-artifacts.test.ts index 5e0b594f347..63cee258eae 100644 --- a/packages/core/test/plugin/provider-opencode-artifacts.test.ts +++ b/packages/core/test/plugin/provider-opencode-artifacts.test.ts @@ -21,11 +21,13 @@ function fakeConsole() { const state = { artifacts: true, watches: true, - blobs: new Set(), + blobs: new Map(), + blobReads: new Array(), uploads: new Array(), prepared: new Array>(), published: new Array<{ slug: string; body: Record }>(), deleted: new Array(), + gone: false, } const server = Bun.serve({ port: 0, @@ -48,9 +50,26 @@ function fakeConsole() { return Response.json({ missing: body.files.map((file) => file.sha256).filter((sha) => !state.blobs.has(sha)) }) } if (url.pathname.startsWith("/api/artifacts/blobs/")) { + const bytes = new Uint8Array(await request.arrayBuffer()) state.uploads.push(slug) - state.blobs.add(slug) - return Response.json({ sha256: slug, bytes: (await request.arrayBuffer()).byteLength }) + state.blobs.set(slug, bytes) + return Response.json({ sha256: slug, bytes: bytes.byteLength }) + } + // Lists the last published revision, inlining only index.html so other files download as blobs. + if (url.pathname.endsWith("/files")) { + if (state.gone) return new Response("Not found", { status: 404 }) + const published = state.published.at(-1)?.body as { files: { path: string; sha256: string }[] } + return Response.json({ + revision: state.published.length, + files: published.files.map((file) => ({ + ...file, + ...(file.path === "index.html" ? { text: new TextDecoder().decode(state.blobs.get(file.sha256)) } : {}), + })), + }) + } + if (url.pathname.includes("/blobs/")) { + state.blobReads.push(`${slug}?${url.searchParams}`) + return new Response(state.blobs.get(slug)) } if (url.pathname.startsWith("/api/artifacts/") && request.method === "PUT") { const body = (await request.json()) as Record @@ -162,6 +181,32 @@ describe("OpencodePlugin artifacts", () => { ), ) + it.effect("reads the files back, downloading the ones Console doesn't inline from the listed revision", () => + withConsole((console) => + Effect.gen(function* () { + const artifacts = yield* Artifact.Service + yield* start(console) + const created = yield* artifacts.create({ title: "Report", files }) + const content = yield* artifacts.get(created.id) + expect(content.files).toEqual(files) + expect(console.state.blobReads).toEqual([expect.stringMatching(/^[0-9a-f]{64}\?revision=1$/)]) + }), + ), + ) + + it.effect("says Console has no such artifact when it was deleted there", () => + withConsole((console) => + Effect.gen(function* () { + const artifacts = yield* Artifact.Service + yield* start(console) + const created = yield* artifacts.create({ title: "Report", files }) + console.state.gone = true + const error = yield* Effect.flip(artifacts.get(created.id)) + expect(String(error)).toContain(`OpenCode Console has no artifact named ${console.state.published[0]?.slug}`) + }), + ), + ) + it.effect("gives two artifacts with one title their own Console artifacts", () => withConsole((console) => Effect.gen(function* () { From aab2f85c863b8ac7ac327ca8201d59ae8ecc763f Mon Sep 17 00:00:00 2001 From: "opencode-agent[bot]" <219766164+opencode-agent[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:18:35 +0800 Subject: [PATCH 5/8] fix(app): don't show the Hex tip on touch devices (#64583) Co-authored-by: Brendan --- packages/app/src/tips/model.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/app/src/tips/model.ts b/packages/app/src/tips/model.ts index caf2c6e8c5b..14ea3a1d4af 100644 --- a/packages/app/src/tips/model.ts +++ b/packages/app/src/tips/model.ts @@ -1,3 +1,4 @@ +import { createMediaQuery } from "@solid-primitives/media" import { showToast, toaster } from "@opencode/ui/toast" import { Schema } from "effect" import { createEffect, createMemo, createSignal, onCleanup } from "solid-js" @@ -24,6 +25,7 @@ export function createTipToasts() { const servers = useServers() const language = useLanguage() const platform = usePlatform() + const touch = createMediaQuery("(hover: none)") const server = createMemo(() => { const conn = servers.visible.find(servers.current) ?? servers.visible[0] @@ -74,7 +76,7 @@ export function createTipToasts() { id: "hex", title: "tips.hex.title", description: "tips.hex.description", - when: () => hexInstalled() === false, + when: () => !touch() && hexInstalled() === false, action: { label: "tips.hex.install", // anoma.ly/hex 404s with a query string; the trailing slash is required. From a5533f7bdf0b87c6109793f13e7eaed2afd345c5 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:22:12 -0600 Subject: [PATCH 6/8] fix(ui): remove the fringe on project icon corners (#64582) --- .../project-avatar/project-avatar.css | 37 ++++++++++++++++++- .../project-avatar/project-avatar.tsx | 6 ++- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/packages/ui/src/data-display/project-avatar/project-avatar.css b/packages/ui/src/data-display/project-avatar/project-avatar.css index 28d5e83e979..317c4b1f459 100644 --- a/packages/ui/src/data-display/project-avatar/project-avatar.css +++ b/packages/ui/src/data-display/project-avatar/project-avatar.css @@ -112,16 +112,49 @@ height: 100%; } +/* + * The backing, the ring and the image composite as one group, and the surface's rounded clip cuts that group once. + * Clipped one by one, each gets its own antialiased corner and the backing shows through the image's corner pixels + * as a lighter fringe. The opaque mask is what makes the media a group. + */ [data-slot="project-avatar-surface"][data-has-image] { - background: var(--project-avatar-bg); + background: none; + box-shadow: none; } -[data-slot="project-avatar-surface"] [data-slot="project-avatar-image"] { +[data-slot="project-avatar-surface"] [data-slot="project-avatar-media"] { position: relative; display: block; width: 100%; height: 100%; border-radius: inherit; + -webkit-mask-image: linear-gradient(#000, #000); + mask-image: linear-gradient(#000, #000); +} + +[data-slot="project-avatar-surface"] [data-slot="project-avatar-media"]::before, +[data-slot="project-avatar-surface"] [data-slot="project-avatar-media"]::after { + content: ""; + position: absolute; + inset: 0; +} + +/* Square: the group clip is the only rounded edge the backing gets. */ +[data-slot="project-avatar-surface"] [data-slot="project-avatar-media"]::before { + background: var(--project-avatar-bg); +} + +[data-slot="project-avatar-surface"] [data-slot="project-avatar-media"]::after { + border-radius: inherit; + box-shadow: inset 0 0 0 0.5px var(--project-avatar-border); +} + +[data-slot="project-avatar-surface"] [data-slot="project-avatar-image"] { + position: relative; + z-index: 1; + display: block; + width: 100%; + height: 100%; object-fit: cover; user-select: none; -webkit-user-select: none; diff --git a/packages/ui/src/data-display/project-avatar/project-avatar.tsx b/packages/ui/src/data-display/project-avatar/project-avatar.tsx index 0f960dd5180..28e5509cfac 100644 --- a/packages/ui/src/data-display/project-avatar/project-avatar.tsx +++ b/packages/ui/src/data-display/project-avatar/project-avatar.tsx @@ -195,7 +195,11 @@ export function ProjectAvatar(props: ProjectAvatarProps) { } > - {(value) => } + {(value) => ( + + + + )} {(label) => ( From db8730ebcd192fe72e044c2286859d892cce2225 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:45:39 -0600 Subject: [PATCH 7/8] fix(codemode): say why an import can't be resolved (#64587) --- .../src/language/runtime/interpreter.ts | 17 ++++++++++------- .../codemode/src/language/runtime/modules.ts | 14 ++++++++++++++ packages/codemode/test/extensions.test.ts | 12 ++++++++++-- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/packages/codemode/src/language/runtime/interpreter.ts b/packages/codemode/src/language/runtime/interpreter.ts index 191b076f3d2..89f6c4021f6 100644 --- a/packages/codemode/src/language/runtime/interpreter.ts +++ b/packages/codemode/src/language/runtime/interpreter.ts @@ -4,7 +4,7 @@ import { globals } from "./globals.js" import type { Builtins } from "./intrinsics.js" import { IntrinsicNames } from "./intrinsic-names.js" import { type AstNode, type Binding, PendingThrow } from "./model.js" -import { moduleName, resolveModule } from "./modules.js" +import { isRuntimeModule, moduleName, resolveModule } from "./modules.js" import { define, entries, type HostNamespace, makingIntrinsics, nativeRule, Obj, type Value } from "./objects.js" import type { HostResult } from "../host.js" import { Prelude } from "../prelude/prelude.js" @@ -88,12 +88,7 @@ export class Interpreter { const cached = this.modules.get(name) if (cached !== undefined) return cached const module = resolveModule(name, (global) => this.globalScope.get(global)?.value, this.moduleGlobals) - if (module === undefined) - throw new PendingThrow( - "Error", - `Cannot import "${specifier}": it isn't available here, where packages and files can't be loaded. Use the provided globals.`, - site, - ) + if (module === undefined) throw new PendingThrow("Error", cannotImport(specifier), site) this.modules.set(name, module) return module } @@ -135,3 +130,11 @@ export class Interpreter { return this.sources.get(id.source)?.node(id) } } + +/** Why `specifier` can't be loaded, split so the error names the kind of import that failed. */ +function cannotImport(specifier: string): string { + if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("file:")) + return `Cannot import "${specifier}": local files can't be imported.` + if (isRuntimeModule(specifier)) return `Cannot import "${specifier}": this runtime doesn't provide it.` + return `Cannot import "${specifier}": packages can't be installed here.` +} diff --git a/packages/codemode/src/language/runtime/modules.ts b/packages/codemode/src/language/runtime/modules.ts index 1d9699c91c8..a89fc75e774 100644 --- a/packages/codemode/src/language/runtime/modules.ts +++ b/packages/codemode/src/language/runtime/modules.ts @@ -18,6 +18,20 @@ const aliases: Record Value) => Value> = { /** `node:fs` names the same module as `fs`. */ export const moduleName = (specifier: string) => (specifier.startsWith("node:") ? specifier.slice(5) : specifier) +// Node's core modules, fixed here so every host gives the same answer (Bun's `isBuiltin` also claims `ws` and `undici`). +const core = new Set( + "assert async_hooks buffer child_process cluster console constants crypto dgram diagnostics_channel dns domain events fs http http2 https inspector module net os path perf_hooks process punycode querystring readline repl stream string_decoder sys timers tls trace_events tty url util v8 vm wasi worker_threads zlib".split( + " ", + ), +) + +/** Whether a specifier names a module a runtime provides, as Node's and Bun's own modules are, rather than a package. */ +export const isRuntimeModule = (specifier: string) => + specifier.startsWith("node:") || + specifier === "bun" || + specifier.startsWith("bun:") || + core.has(specifier.split("/")[0]!) + /** `hosted` names the global a host's own module names load (`{ bun: "Bun" }`). */ export const resolveModule = ( specifier: string, diff --git a/packages/codemode/test/extensions.test.ts b/packages/codemode/test/extensions.test.ts index c6d263af960..a2694bf5415 100644 --- a/packages/codemode/test/extensions.test.ts +++ b/packages/codemode/test/extensions.test.ts @@ -630,7 +630,13 @@ describe("imports", () => { test("a module that isn't provided, or a missing export, fails at the import", async () => { const target = CodeMode.make({ extensions: [files] }) expect((await failure(`import yaml from "yaml"`, target)).message).toStartWith( - `Error: Cannot import "yaml": it isn't available here, where packages and files can't be loaded.`, + `Error: Cannot import "yaml": packages can't be installed here.`, + ) + expect((await failure(`import ws from "ws"`, target)).message).toStartWith( + `Error: Cannot import "ws": packages can't be installed here.`, + ) + expect((await failure(`import x from "./local.js"`, target)).message).toStartWith( + `Error: Cannot import "./local.js": local files can't be imported.`, ) expect(await value(`try { await import("child_process") } catch (e) { return e.message }`, target)).toStartWith( `Cannot import "child_process"`, @@ -638,7 +644,9 @@ describe("imports", () => { expect((await failure(`import { writeFile } from "fs"`, target)).message).toStartWith( `SyntaxError: "fs" has no export named "writeFile".`, ) - expect((await failure(`require("fs")`)).message).toStartWith(`Error: Cannot import "fs"`) + expect((await failure(`require("fs")`)).message).toStartWith( + `Error: Cannot import "fs": this runtime doesn't provide it.`, + ) }) }) From 7667ec40206230a76c9e285ee594a04c2173523d Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:48:33 -0600 Subject: [PATCH 8/8] feat(core): tell models about Bun's file APIs in Code Mode with full_codemode (#64589) --- packages/core/src/codemode/tool.ts | 26 ++++++++++++++----------- packages/core/test/tool-execute.test.ts | 8 ++++++++ 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/packages/core/src/codemode/tool.ts b/packages/core/src/codemode/tool.ts index 5fcbea149a3..4534660baa1 100644 --- a/packages/core/src/codemode/tool.ts +++ b/packages/core/src/codemode/tool.ts @@ -89,16 +89,20 @@ export type Inventory = { readonly namespaces?: ReadonlyMap } -// Invariant model-facing guidance; the changing tool catalog is delivered through Instructions. -const description = [ - "Run JavaScript in a confined Code Mode runtime to script tool calls and HTTP requests and compose their results.", - "Write plain JavaScript and send it exactly as written: no code fence, and no JSON or other wrapper around it.", - "`fetch` is available for HTTP requests. Imports, direct filesystem access, and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`.", - "Inside `execute`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by the `search` function. Ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.", - 'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.["tool-name"](input)`.', - "Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.", - "Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.allSettled`.", -].join("\n") +// Invariant model-facing guidance; the changing tool catalog is delivered through Instructions. With `full_codemode`, +// the runtime also has Bun's file APIs. +const description = (full: boolean) => + [ + "Run JavaScript in a confined Code Mode runtime to script tool calls and HTTP requests and compose their results.", + "Write plain JavaScript and send it exactly as written: no code fence, and no JSON or other wrapper around it.", + full + ? "`fetch` is available for HTTP requests, and Bun's file APIs (`Bun.file`, `Bun.write`, `Bun.Glob`) for files, in place of Node's `fs`. Imports and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`." + : "`fetch` is available for HTTP requests. Imports, direct filesystem access, and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`.", + "Inside `execute`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by the `search` function. Ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.", + 'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.["tool-name"](input)`.', + "Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.", + "Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.allSettled`.", + ].join("\n") export const create = ( inventory: Inventory, @@ -109,7 +113,7 @@ export const create = ( ) => { return { name: "execute", - description, + description: description(services !== undefined), input: CodeMode.Input, freeform: { type: "text" }, output: ExecuteOutput, diff --git a/packages/core/test/tool-execute.test.ts b/packages/core/test/tool-execute.test.ts index bc81f9c6bb8..01fd787736e 100644 --- a/packages/core/test/tool-execute.test.ts +++ b/packages/core/test/tool-execute.test.ts @@ -72,6 +72,14 @@ test("execute describes invariant Code Mode behavior", () => { ) }) +test("with full_codemode, execute names Bun's file APIs instead of ruling out filesystem access", () => { + const description = createCodeMode(new Map(), allowAll, codeModeServices(process.cwd())).description + expect(description).toContain( + "`fetch` is available for HTTP requests, and Bun's file APIs (`Bun.file`, `Bun.write`, `Bun.Glob`) for files, in place of Node's `fs`. Imports and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`.", + ) + expect(description).not.toContain("direct filesystem access") +}) + test("canonical execution distinguishes declared, model-only, and raw schema outputs", async () => { const declared: Info = { name: "declared",