From c69e3cefe478e58ba6fe6c041f44e651c209153c Mon Sep 17 00:00:00 2001 From: tomasvarga Date: Thu, 19 Nov 2026 13:06:06 +0100 Subject: [PATCH 1/2] feat(v2): open a box from OpenCode, in the browser or the OpenCode app - /e2b-attach (TUI plugin): suspends the TUI, runs the box's TUI in the same terminal, resumes on quit with a toast. Loaded from the ./tui export. - /e2b-box open and opencode-e2b box open: one-time sign-in link from opencode pair in the box; opens the browser and copies a second link. - The box runs OpenCode as its background service (pair needs it), opens the project for the web UI, and waits on the API with the password. - /e2b-box up shows progress, copies the link, and passes the local default model; the CLI takes --model. --- .changeset/box-web-attach.md | 5 +++ README.md | 33 ++++++++++++-- package.json | 4 ++ src/v2/box/attach.ts | 2 +- src/v2/box/local.ts | 48 +++++++++++++++++++++ src/v2/box/server.ts | 76 ++++++++++++++++++++++++++------- src/v2/box/up.ts | 12 +++++- src/v2/cli/box.ts | 20 +++++++-- src/v2/cli/main.ts | 7 +-- src/v2/opencode/box-commands.ts | 66 +++++++++++++++++++++++----- src/v2/tui.ts | 59 +++++++++++++++++++++++++ test/v2-box.test.ts | 21 +++++++++ 12 files changed, 316 insertions(+), 37 deletions(-) create mode 100644 .changeset/box-web-attach.md create mode 100644 src/v2/box/local.ts create mode 100644 src/v2/tui.ts diff --git a/.changeset/box-web-attach.md b/.changeset/box-web-attach.md new file mode 100644 index 0000000..5a4f76c --- /dev/null +++ b/.changeset/box-web-attach.md @@ -0,0 +1,5 @@ +--- +"@e2b/opencode": minor +--- + +Boxes without leaving OpenCode: `/e2b-attach` opens a box's TUI in the same terminal and comes back when you quit it, and `/e2b-box open` (or `opencode-e2b box open`) signs the browser or the OpenCode app in to a box with a one-time link. `/e2b-box up` shows its progress, copies the link, and starts the box with your default model. diff --git a/README.md b/README.md index d279475..8a046a5 100644 --- a/README.md +++ b/README.md @@ -100,29 +100,54 @@ Limits: the project must be a git repository; submodule contents and a linked wo A box is a sandbox with your project and an OpenCode 2 server in it. The agent keeps working when your laptop sleeps. Each box is one task. +From OpenCode: + +```text +/e2b-secrets set anthropic once: stores ANTHROPIC_API_KEY as an E2B secret +/e2b-box up start a box named after the branch; a sign-in link is copied +/e2b-attach open the box's TUI here; quit it (Ctrl+C) to come back, the box keeps working +/e2b-box open open the box in the browser (and copy a second link for the OpenCode app) +/e2b-box pull the box's work, uncommitted files too, as branch e2b/ +/e2b-box kill +``` + +Three ways to work in a box: + +| Where | How | +| --- | --- | +| This terminal | `/e2b-attach [name]` pauses your OpenCode and opens the box's TUI in its place. Quit it to come back. | +| Browser | `/e2b-box open [name]` opens the box's web UI, signed in. Works on a phone too: open the link there. | +| OpenCode app | Paste the copied link under Settings > Servers > Add server. The box shows next to your computer, with its own projects. | + +A sign-in link works once and expires in 5 minutes. `/e2b-box open` makes a new one any time, and wakes a paused box. + +From a shell: + ```bash npm install -g @e2b/opencode # the opencode-e2b command opencode-e2b secrets set anthropic # once: stores ANTHROPIC_API_KEY (or stdin) as an E2B secret opencode-e2b box up --attach # start a box named after the branch, open the TUI on it +opencode-e2b box open # open it in the browser instead opencode-e2b box pull # the box's work, uncommitted files too, as branch e2b/ opencode-e2b box kill ``` | Command | What it does | | --- | --- | -| `box up [name]` | Uploads the project (tracked and uncommitted files, and `.git`) to the same path in a new sandbox, and starts `opencode2 serve` there. Options: `--template`, `--hours` (default 1), `--attach`. | +| `box up [name]` | Uploads the project (tracked and uncommitted files, and `.git`) to the same path in a new sandbox, and starts OpenCode there as its background service. Prints a sign-in link. Options: `--template`, `--hours` (default 1), `--model `, `--attach`. | +| `box open [name]` | Wakes the box if it is paused and prints a new sign-in link. In a terminal it also opens the browser. | | `box attach [name]` | Wakes the box if it is paused, then runs your local `opencode2 --server `. | | `box pull [name]` | Commits the box's work in progress on a scratch ref (the agent's branch and index stay as they are) and fetches it as a git bundle into `e2b/`. No credentials go to the box. | | `box list`, `box stop`, `box kill` | List the boxes this machine started, pause one, delete one. | | `secrets set\|list\|remove ` | Model keys for boxes: `anthropic`, `openai`, `openrouter`. | -The name defaults to the current branch, or to the project's only box. In OpenCode, `/e2b-box up|pull|list|stop|kill` and `/e2b-secrets` do the same. `/e2b-secrets set` takes the key from OpenCode's environment, never from the prompt. +The name defaults to the current branch, or to the project's only box. In OpenCode, `/e2b-box up|open|pull|list|stop|kill`, `/e2b-attach` and `/e2b-secrets` do the same. `/e2b-secrets set` takes the key from OpenCode's environment, never from the prompt. A box started from OpenCode uses the same default model as your sessions, when its provider has a stored key. Model keys: a box gets a placeholder, and E2B's egress proxy puts the stored secret into requests to the provider's API. No process in the box holds the key. The box offers only the providers with a stored key, and commits with your git `user.name` and `user.email`. -Each box has a random server password. It is stored with the box record in `~/.local/state/opencode-e2b/boxes/` (readable only by you), and never sent to E2B as metadata. +Each box has a random server password. It is stored with the box record in `~/.local/state/opencode-e2b/boxes/` (readable only by you), and never sent to E2B as metadata. Sign-in links come from `opencode pair` in the box, so the password itself is never shown. -A box pauses after `--hours`; attach wakes it. E2B plans cap the run time (1 hour on the lower plans). +A box pauses after `--hours`; open or attach wakes it. E2B plans cap the run time (1 hour on the lower plans). ## Development diff --git a/package.json b/package.json index ab72ca2..f06be19 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,10 @@ "./server": { "types": "./dist/index.d.ts", "default": "./dist/index.js" + }, + "./tui": { + "types": "./dist/v2/tui.d.ts", + "default": "./dist/v2/tui.js" } }, "publishConfig": { diff --git a/src/v2/box/attach.ts b/src/v2/box/attach.ts index c8a0d16..d167c3a 100644 --- a/src/v2/box/attach.ts +++ b/src/v2/box/attach.ts @@ -13,7 +13,7 @@ import { waitHealthy } from "./server.js" */ export async function attachBox(record: BoxRecord, access: E2BAccess): Promise { await Sandbox.connect(record.sandboxId, access) - await waitHealthy(record.url) + await waitHealthy(record.url, record.password) const opencode = await localOpencode2() return new Promise((resolve, reject) => { const child = spawn(opencode, ["--server", record.url], { diff --git a/src/v2/box/local.ts b/src/v2/box/local.ts new file mode 100644 index 0000000..3c939aa --- /dev/null +++ b/src/v2/box/local.ts @@ -0,0 +1,48 @@ +/** + * Hand a box's sign-in link to this machine: the browser, or the clipboard for the + * OpenCode app. Both run where OpenCode's server runs, which is the user's machine. + * Best effort: callers print the link too. + */ + +import { spawn } from "node:child_process" + +export function openInBrowser(link: string): void { + const opener = + process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open" + const child = spawn(opener, [link], { detached: true, stdio: "ignore" }) + child.on("error", () => undefined) + child.unref() +} + +/** Resolves true when the text is on the clipboard. */ +export async function copyToClipboard(text: string): Promise { + for (const [command, ...args] of clipboardCommands()) { + if (await pipeTo(command, args, text)) { + return true + } + } + return false +} + +function clipboardCommands(): string[][] { + if (process.platform === "darwin") { + return [["pbcopy"]] + } + if (process.platform === "win32") { + return [["clip"]] + } + return [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"]] +} + +function pipeTo(command: string, args: string[], input: string): Promise { + return new Promise((resolve) => { + const child = spawn(command, args, { stdio: ["pipe", "ignore", "ignore"] }) + child.on("error", () => { + resolve(false) + }) + child.on("exit", (code) => { + resolve(code === 0) + }) + child.stdin.end(input) + }) +} diff --git a/src/v2/box/server.ts b/src/v2/box/server.ts index 2a21dcf..3a1ddb2 100644 --- a/src/v2/box/server.ts +++ b/src/v2/box/server.ts @@ -1,7 +1,9 @@ /** OpenCode 2 serving inside a box, behind a password. */ -import type { Sandbox } from "e2b" -import { sh } from "../sync/remote.js" +import { Sandbox } from "e2b" +import type { E2BAccess } from "../sandbox/create.js" +import { quote, sh } from "../sync/remote.js" +import type { BoxRecord } from "./registry.js" export const PORT = 4096 const HEALTH_TIMEOUT_MS = 90_000 @@ -20,37 +22,81 @@ export async function ensureOpencode(sandbox: Sandbox): Promise { } } -/** Start `opencode2 serve` in `root` and wait until it answers. Resolves with the public URL. */ +/** + * Start OpenCode as the box's background service and wait until its API answers. + * Resolves with the public URL. It must be the service, not `opencode serve`: + * `opencode pair` only makes sign-in links for the service. + */ export async function startServer( sandbox: Sandbox, root: string, password: string, env: Record, ): Promise { - await sandbox.commands.run( - `opencode2 serve --hostname 0.0.0.0 --port ${PORT} >/tmp/opencode-e2b-box.log 2>&1`, - { - background: true, - cwd: root, - envs: { ...env, OPENCODE_SERVER_PASSWORD: password }, - timeoutMs: 0, - }, + const settings = [ + "hostname 0.0.0.0", + `port ${PORT}`, + 'password "$OPENCODE_E2B_PASSWORD"', + ...Object.entries(env).map(([key, value]) => `env ${key} ${quote(value)}`), + ] + await sh( + sandbox, + [ + ...settings.map((setting) => `opencode2 service set ${setting} >/dev/null`), + `cd ${quote(root)}`, + "opencode2 service start >/dev/null", + ].join(" && "), + { OPENCODE_E2B_PASSWORD: password }, ) const url = `https://${sandbox.getHost(PORT)}` - await waitHealthy(url) + await waitHealthy(url, password) + await openProject(url, password, root) return url } -export async function waitHealthy(url: string): Promise { +/** Wait until the API answers with the password. The web page alone answers before the API is ready. */ +export async function waitHealthy(url: string, password: string): Promise { const deadline = Date.now() + HEALTH_TIMEOUT_MS while (Date.now() < deadline) { - const response = await fetch(`${url}/global/health`).catch(() => undefined) + const response = await fetch(`${url}/api/info`, { headers: authHeader(password) }).catch(() => undefined) if (response?.ok) { return } await new Promise((resolve) => setTimeout(resolve, 1000)) } throw new Error( - `OpenCode in the box did not start within ${HEALTH_TIMEOUT_MS / 1000} s (log: /tmp/opencode-e2b-box.log)`, + `OpenCode in the box did not start within ${HEALTH_TIMEOUT_MS / 1000} s (check with: opencode2 service status)`, ) } + +/** + * A one-time link that signs a browser or the OpenCode app in to the box. It works once + * and expires in 5 minutes. Wakes a paused box first. + */ +export async function webLink(record: BoxRecord, access: E2BAccess): Promise { + const sandbox = await Sandbox.connect(record.sandboxId, access) + await waitHealthy(record.url, record.password) + const link = parsePairLink(await sh(sandbox, `opencode2 pair --url ${quote(record.url)}`)) + if (!link) { + throw new Error("OpenCode in the box did not print a sign-in link") + } + return link +} + +/** The sign-in link in `opencode pair` output, which also holds a QR code. */ +export function parsePairLink(out: string): string | undefined { + return /https:\/\/\S+\/auth\/connect\/\S+/.exec(out)?.[0] +} + +/** The web UI lists the folders the server has opened. Open the project once, so it is one click away. */ +async function openProject(url: string, password: string, root: string): Promise { + const query = new URLSearchParams({ "location[directory]": root }) + const response = await fetch(`${url}/api/location?${query.toString()}`, { headers: authHeader(password) }) + if (!response.ok) { + throw new Error(`OpenCode in the box could not open ${root}: HTTP ${response.status}`) + } +} + +function authHeader(password: string) { + return { authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}` } +} diff --git a/src/v2/box/up.ts b/src/v2/box/up.ts index 5dbaf95..086547c 100644 --- a/src/v2/box/up.ts +++ b/src/v2/box/up.ts @@ -19,6 +19,8 @@ export interface UpRequest { template: string /** How long the box runs before E2B pauses it. Agents work without traffic from here. */ lifetimeMs: number + /** `provider/model` for the box's sessions. Used when that provider has a stored key. */ + model?: string access: E2BAccess network?: Network progress: (step: string) => void @@ -55,7 +57,10 @@ export async function upBox(request: UpRequest): Promise { const url = await startServer(sandbox, root, password, { ...placeholderEnv(providers), // Only the providers with a stored key. Otherwise OpenCode may pick a free default model instead. - OPENCODE_CONFIG_CONTENT: JSON.stringify({ enabled_providers: providers }), + OPENCODE_CONFIG_CONTENT: JSON.stringify({ + enabled_providers: providers, + ...(usableModel(request.model, providers) ? { model: request.model } : {}), + }), }) const record: BoxRecord = { name, @@ -101,3 +106,8 @@ async function headCommit(root: string): Promise { () => undefined, ) } + +/** A model the box can run: its provider has a stored key. */ +export function usableModel(model: string | undefined, providers: readonly string[]): boolean { + return model !== undefined && providers.includes(model.split("/")[0] ?? "") +} diff --git a/src/v2/cli/box.ts b/src/v2/cli/box.ts index 84bb173..26d7160 100644 --- a/src/v2/cli/box.ts +++ b/src/v2/cli/box.ts @@ -4,12 +4,14 @@ import { parseArgs } from "node:util" import { attachBox } from "../box/attach.js" import { defaultBoxName, describeBoxes, findBox, killBox, listWithState, stopBox } from "../box/manage.js" import { pullBox, pullSummary } from "../box/pull.js" +import { openInBrowser } from "../box/local.js" +import { webLink } from "../box/server.js" import { upBox } from "../box/up.js" import type { E2BAccess } from "../sandbox/create.js" import { gitRoot } from "../sync/files.js" import { UsageError } from "./usage-error.js" -const ACTIONS = new Set(["up", "attach", "pull", "list", "stop", "kill"]) +const ACTIONS = new Set(["up", "open", "attach", "pull", "list", "stop", "kill"]) export async function boxCommand(args: string[]): Promise { const { values, positionals } = parseArgs({ @@ -20,6 +22,7 @@ export async function boxCommand(args: string[]): Promise { hours: { type: "string", default: "1" }, domain: { type: "string" }, attach: { type: "boolean", default: false }, + model: { type: "string" }, }, }) const [action, given, ...extra] = positionals @@ -53,6 +56,7 @@ export async function boxCommand(args: string[]): Promise { name: await defaultBoxName(root, given), template: values.template, lifetimeMs: hours * 3_600_000, + model: values.model, access, progress: (step) => { console.error(`[e2b] ${step}`) @@ -62,7 +66,9 @@ export async function boxCommand(args: string[]): Promise { if (values.attach) { return attachBox(record, recordAccess(record, access)) } - console.log(`Attach with: opencode-e2b box attach ${record.name}`) + const link = await webLink(record, recordAccess(record, access)) + console.log(`Open it in the browser or the OpenCode app (one-time link, 5 minutes):\n ${link}`) + console.log(`Or open the TUI on it: opencode-e2b box attach ${record.name}`) return 0 } @@ -71,13 +77,21 @@ export async function boxCommand(args: string[]): Promise { if (action === "attach") { return attachBox(record, boxAccess) } + if (action === "open") { + const link = await webLink(record, boxAccess) + console.log(`One-time sign-in link for box "${record.name}" (5 minutes):\n ${link}`) + if (process.stdout.isTTY) { + openInBrowser(link) + } + return 0 + } if (action === "pull") { console.log(pullSummary(record.name, await pullBox(record, boxAccess))) return 0 } if (action === "stop") { await stopBox(record, boxAccess) - console.log(`Box "${record.name}" is paused. Attach wakes it.`) + console.log(`Box "${record.name}" is paused. Open or attach wakes it.`) return 0 } await killBox(record, boxAccess) diff --git a/src/v2/cli/main.ts b/src/v2/cli/main.ts index 1c12db3..78fae01 100644 --- a/src/v2/cli/main.ts +++ b/src/v2/cli/main.ts @@ -2,7 +2,7 @@ /** * opencode-e2b: boxes (OpenCode running in an E2B sandbox) and the model keys they use. * - * opencode-e2b box up|attach|pull|list|stop|kill [name] + * opencode-e2b box up|open|attach|pull|list|stop|kill [name] * opencode-e2b secrets set|list|remove [provider] */ @@ -13,12 +13,13 @@ import { secretsCommand } from "./secrets.js" import { UsageError } from "./usage-error.js" const USAGE = `Usage: - opencode-e2b box up [name] [--template ] [--hours ] [--attach] + opencode-e2b box up [name] [--template ] [--hours ] [--model ] [--attach] Start a box with this project and OpenCode in it + opencode-e2b box open [name] Open a box in the browser (prints a one-time sign-in link) opencode-e2b box attach [name] Open the OpenCode TUI on a box opencode-e2b box pull [name] Bring the box's work home as branch e2b/ opencode-e2b box list The boxes this machine started - opencode-e2b box stop [name] Pause a box. Attach wakes it. + opencode-e2b box stop [name] Pause a box. Open or attach wakes it. opencode-e2b box kill [name] Delete a box. Pull first. opencode-e2b secrets set Store a model key as an E2B secret opencode-e2b secrets list The providers with a stored key diff --git a/src/v2/opencode/box-commands.ts b/src/v2/opencode/box-commands.ts index 87c47e5..9c8946f 100644 --- a/src/v2/opencode/box-commands.ts +++ b/src/v2/opencode/box-commands.ts @@ -1,11 +1,14 @@ /** * Slash commands for boxes: /e2b-box and /e2b-secrets. They do what the CLI does, - * except attach, which needs its own terminal. Replies never show a box password or a key. + * except attach: that is /e2b-attach, from the TUI plugin (tui.ts), because it takes over + * the terminal. /e2b-box open gives a sign-in link for the browser or the OpenCode app. Replies never show a box password or a key. */ import type { Plugin } from "@opencode/plugin" import { defaultBoxName, describeBoxes, findBox, killBox, listWithState, stopBox } from "../box/manage.js" import { pullBox, pullSummary } from "../box/pull.js" +import { copyToClipboard, openInBrowser } from "../box/local.js" +import { webLink } from "../box/server.js" import { upBox } from "../box/up.js" import { networkFor } from "../options.js" import { @@ -23,8 +26,8 @@ import type { PluginContext } from "./context.js" type SessionID = Parameters[0]["sessionID"] const BOX_USAGE = - "Usage: /e2b-box up|pull|list|stop|kill [name]. The name defaults to the current branch, or the project's only box." -const BOX_ACTIONS = new Set(["up", "pull", "list", "stop", "kill"]) + "Usage: /e2b-box up|open|pull|list|stop|kill [name]. The name defaults to the current branch, or the project's only box. To open a box in this TUI: /e2b-attach [name]." +const BOX_ACTIONS = new Set(["up", "open", "pull", "list", "stop", "kill"]) const SECRETS_USAGE = `Usage: /e2b-secrets set|remove , or /e2b-secrets list. Providers: ${PROVIDER_IDS.join(", ")}.` export async function registerBoxCommands(plugin: PluginContext): Promise { @@ -40,8 +43,33 @@ export async function registerBoxCommands(plugin: PluginContext): Promise }) } + /** The model new sessions use here, so the box's sessions use it too. */ + const defaultModel = async (): Promise => { + const model = await opencode.model.default().then( + (response) => response.data, + () => undefined, + ) + return model ? `${model.providerID}/${model.id}` : undefined + } + + /** The TUI shows only the first line of a reply, so it says where the link is. */ + const linkText = async (status: string, name: string, link: string): Promise => { + const copied = await copyToClipboard(link) + return [ + copied + ? `${status} Sign-in link copied: paste it in the browser, or in the OpenCode app under Settings > Servers > Add server.` + : `${status} Open it in the browser, or paste it in the OpenCode app under Settings > Servers > Add server: ${link}`, + link, + `The link works once, for 5 minutes. /e2b-box open ${name} opens the browser and copies a new one. /e2b-attach ${name} opens the box here in the TUI.`, + ].join("\n") + } + /** The text of the reply to `/e2b-box [name]`. */ - const box = async (action: string | undefined, given: string | undefined): Promise => { + const box = async ( + action: string | undefined, + given: string | undefined, + progress: (step: string) => void, + ): Promise => { if (action === undefined || !BOX_ACTIONS.has(action)) { return BOX_USAGE } @@ -52,25 +80,38 @@ export async function registerBoxCommands(plugin: PluginContext): Promise return "Boxes need a git repository, and this folder is not in one." } if (action === "up") { + const name = await defaultBoxName(root, given) const record = await upBox({ root, - name: await defaultBoxName(root, given), + name, template: opts.template, lifetimeMs: opts.boxLifetimeMs, + model: await defaultModel(), access, network: networkFor(opts), - progress: () => undefined, + progress: (step) => { + progress(`Box "${name}": ${step}...`) + }, }) - return `Box "${record.name}" is up with this project and OpenCode in it. Open it in a terminal with: opencode-e2b box attach ${record.name}` + return linkText(`Box "${record.name}" is up.`, record.name, await webLink(record, access)) } const record = await findBox(root, given) const boxAccess = { ...access, domain: record.domain ?? access.domain } + if (action === "open") { + // A link works once, so the browser and the clipboard each get their own. + openInBrowser(await webLink(record, boxAccess)) + return linkText( + `Opened box "${record.name}" in the browser.`, + record.name, + await webLink(record, boxAccess), + ) + } if (action === "pull") { return pullSummary(record.name, await pullBox(record, boxAccess)) } if (action === "stop") { await stopBox(record, boxAccess) - return `Box "${record.name}" is paused. Attach wakes it.` + return `Box "${record.name}" is paused. /e2b-box open wakes it.` } await killBox(record, boxAccess) return `Box "${record.name}" is deleted.` @@ -104,10 +145,15 @@ export async function registerBoxCommands(plugin: PluginContext): Promise await opencode.command.transform((commands) => { commands.add({ name: "e2b-box", - description: "Run OpenCode in an E2B box: /e2b-box up|pull|list|stop|kill [name]", + description: "Run OpenCode in an E2B box: /e2b-box up|open|pull|list|stop|kill [name]", execute: async ({ sessionID, prompt }) => { const [action, name] = words(prompt.text) - const text = await box(action, name) + // Starting a box takes about half a minute. Each step is a message, in order, before the result. + let shown = Promise.resolve() + const text = await box(action, name, (step) => { + shown = shown.then(() => reply(sessionID, step)) + }) + await shown await reply(sessionID, text, text.split("\n")[0]) }, }) diff --git a/src/v2/tui.ts b/src/v2/tui.ts new file mode 100644 index 0000000..237ffdf --- /dev/null +++ b/src/v2/tui.ts @@ -0,0 +1,59 @@ +/** + * The TUI part of the OpenCode 2 plugin: /e2b-attach [name] opens the box's TUI in this + * terminal. It suspends this TUI the way /editor does, and resumes it when you quit the box's + * TUI. Quitting only closes that view: the box and its agent keep working. + */ + +import type { Plugin } from "@opencode/plugin/tui" + +async function attach(context: Plugin.Context, given: string | undefined): Promise { + const [{ attachBox }, { findBox }, { parseOptions }, { gitRoot }] = await Promise.all([ + import("./box/attach.js"), + import("./box/manage.js"), + import("./options.js"), + import("./sync/files.js"), + ]) + const record = await findBox(await gitRoot(process.cwd()), given) + const access = { + apiKey: process.env.E2B_API_KEY, + domain: record.domain ?? parseOptions(context.options).domain, + } + await context.renderer.suspend() + try { + await attachBox(record, access) + } finally { + await context.renderer.resume() + } + context.ui.toast.show({ + message: `Back from box "${record.name}". It keeps working. /e2b-attach ${record.name} to go back.`, + variant: "info", + }) +} + +const tui: Plugin.Definition = { + id: "e2b", + setup: (context) => { + context.keymap.layer(() => ({ + // The prompt has its own input mode; global keeps the command reachable from it, like OpenCode's own. + mode: "global", + commands: [ + { + id: "e2b.attach", + title: "Attach to an E2B box", + description: "Open the box's TUI here. Quit it (Ctrl+C) to come back; the box keeps working.", + palette: true, + slash: { name: "e2b-attach", arguments: true }, + run: async (input) => { + const name = input?.trim().split(/\s+/)[0] || undefined + await attach(context, name).catch(async (err) => { + const { errorText } = await import("./shell/runner.js") + context.ui.toast.show({ message: errorText(err), variant: "error" }) + }) + }, + }, + ], + })) + }, +} + +export default tui diff --git a/test/v2-box.test.ts b/test/v2-box.test.ts index c731f3c..86ae302 100644 --- a/test/v2-box.test.ts +++ b/test/v2-box.test.ts @@ -6,6 +6,8 @@ import path from "node:path" import { afterAll, test } from "bun:test" import { PULL_REF, bundleScript, pullSummary } from "../dist/v2/box/pull.js" import { boxName, listBoxes, readBox, removeBox, saveBox } from "../dist/v2/box/registry.js" +import { parsePairLink } from "../dist/v2/box/server.js" +import { usableModel } from "../dist/v2/box/up.js" const temp = mkdtempSync(path.join(os.tmpdir(), "opencode-e2b-box-")) afterAll(() => { @@ -75,6 +77,25 @@ test("the pull summary counts commits", () => { assert.match(pullSummary("b", { branch: "e2b/b", log: "abc one\ndef two" }), /\(2 commits\)/) }) +test("the sign-in link is read from opencode pair output", () => { + const out = [ + "", + " Open a link to connect. Links work once and expire in 5 minutes.", + "", + " https://4096-abc.e2b.app/auth/connect/Q1DpTDp6iRXvPWAaeyzzRw", + "", + " ██ ▄▄▄▄▄ █ ██▀▀▀█▄ ▄▄▀▀█", + ].join("\n") + assert.equal(parsePairLink(out), "https://4096-abc.e2b.app/auth/connect/Q1DpTDp6iRXvPWAaeyzzRw") + assert.equal(parsePairLink("Error: no service running"), undefined) +}) + +test("the box uses the local model only when its provider has a key", () => { + assert.equal(usableModel("anthropic/claude-haiku-5-5", ["anthropic"]), true) + assert.equal(usableModel("openai/gpt-6", ["anthropic"]), false) + assert.equal(usableModel(undefined, ["anthropic"]), false) +}) + test("records are private to the user and round-trip", async () => { process.env.XDG_STATE_HOME = path.join(temp, "state") const record = { From 83ac53ef30563c9f9853654e5b975092e03ea27a Mon Sep 17 00:00:00 2001 From: tomasvarga Date: Mon, 23 Nov 2026 15:57:26 +0100 Subject: [PATCH 2/2] fix(v2): keep the first line of a box link reply short The OpenCode app folds plugin replies into rows that show about 80 characters, so the first line only says the link is copied. --- src/v2/opencode/box-commands.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/v2/opencode/box-commands.ts b/src/v2/opencode/box-commands.ts index 9c8946f..1c7cec0 100644 --- a/src/v2/opencode/box-commands.ts +++ b/src/v2/opencode/box-commands.ts @@ -52,15 +52,14 @@ export async function registerBoxCommands(plugin: PluginContext): Promise return model ? `${model.providerID}/${model.id}` : undefined } - /** The TUI shows only the first line of a reply, so it says where the link is. */ + /** The TUI and the app show only the first line of a reply at first, so it stays short. */ const linkText = async (status: string, name: string, link: string): Promise => { const copied = await copyToClipboard(link) return [ - copied - ? `${status} Sign-in link copied: paste it in the browser, or in the OpenCode app under Settings > Servers > Add server.` - : `${status} Open it in the browser, or paste it in the OpenCode app under Settings > Servers > Add server: ${link}`, + copied ? `${status} Sign-in link copied.` : `${status} Sign-in link: ${link}`, + `Paste it in the browser, or in the OpenCode app under Settings > Servers > Add server. It works once, for 5 minutes:`, link, - `The link works once, for 5 minutes. /e2b-box open ${name} opens the browser and copies a new one. /e2b-attach ${name} opens the box here in the TUI.`, + `/e2b-box open ${name} opens the browser and copies a new one. /e2b-attach ${name} opens the box here in the TUI.`, ].join("\n") }