feat(workspace): switch to local workspace targeting with TUI prewarming

This commit is contained in:
Chris Scott committed 2026-04-21 12:29:06 -04:00
1 parent 7870e97c38
commit 7a46fa27c5
19 files changed
+530 -479

No files matched your search

+31 -19
View File
@@ -1,6 +1,8 @@
# @opencode-manager/workspace-plugin
Connect your local OpenCode TUI to a running opencode-manager instance and use its projects as remote workspaces.
Connect your local OpenCode TUI to a running opencode-manager instance and use its projects as local workspaces.
The plugin queries the manager for the list of projects, then configures each workspace to use the project's local directory. The manager is only used for project discovery; all session operations run in-process against the local repository.
## Installation
@@ -21,19 +23,19 @@ Add the plugin to your `opencode.json` configuration:
### Options
- `url` (required): The base URL of your opencode-manager instance
- `token` (required): Bearer token created from the manager's Settings page
- `url` (required): Base URL of your opencode-manager instance. Used only to fetch the project list.
- `token` (required): Bearer token created from the manager's Settings page.
### Environment Variables
As an alternative to configuring in `opencode.json`, you can use:
As an alternative to configuring in `opencode.json`:
- `OPENCODE_MANAGER_URL`: The base URL of your opencode-manager instance
- `OPENCODE_MANAGER_TOKEN`: Bearer token for authentication
- `OPENCODE_MANAGER_URL`: Base URL of your opencode-manager instance
- `OPENCODE_MANAGER_TOKEN`: Bearer token for manager discovery
## Usage
Once configured, the plugin will automatically discover all projects in your opencode-manager instance and register them as remote workspaces. Each project will appear in the OpenCode TUI workspace picker as `manager:<slug>`.
Once configured, the plugin will discover all projects in your opencode-manager instance and register them as local workspaces. Each project appears in the OpenCode TUI workspace picker as `manager:<slug>`.
### Creating a Bearer Token
@@ -46,22 +48,32 @@ Once configured, the plugin will automatically discover all projects in your ope
### Token Scope
Tokens created for the workspace plugin have the `workspace-plugin` scope by default. This restricts their access to only the workspace plugin endpoints.
Tokens created for the workspace plugin have the `workspace-plugin` scope by default. This restricts their access to the `/api/workspace-plugin/projects` endpoint.
### Using the TUI
After starting the opencode-manager server, connect the TUI with:
```bash
opencode attach http://localhost:5551
```
Select a workspace from the manager's project list. Each workspace is rooted at the project's local repository directory.
## How It Works
1. On startup, the plugin calls `GET /api/workspace-plugin/projects` on the manager
2. For each project returned, it registers a `WorkspaceAdaptor` with type `manager:<slug>`
3. When you select a workspace in the TUI, the adaptor provides:
- Remote target URL: `<manager>/api/opencode`
- Authorization header: `Bearer <token>`
- Project slug header: `x-opencode-manager-project: <slug>`
1. On startup, the plugin calls `GET /api/workspace-plugin/projects` on the manager to enumerate projects.
2. For each project, it registers a `WorkspaceAdaptor` as `manager:<slug>`.
3. When the user selects a workspace, the adaptor returns a `type: "local"` target with the project's directory.
4. All session/message/event traffic flows through the in-process opencode server, scoped to the project's directory.
The manager then proxies requests to the embedded OpenCode server with the appropriate `?directory=` parameter.
### TUI pre-warming
The package also ships a TUI plugin (`./tui` subpath) that opencode loads alongside the server plugin. It listens for `session.created` and `workspace.status` events, and when a `manager:*` workspace becomes active it pre-fetches the workspace-scoped endpoints (`config`, `providers`, `agents`, `commands`, `vcs`, `session.status`, etc.) so that the TUI's own `sync.bootstrap` resolves from warm server-side state.
This avoids the race where a newly created workspace appears empty on the first session open and only renders correctly after navigating back and re-entering. No user configuration is required — the single `plugin` entry in `opencode.json` activates both halves.
## Security Notes
- Bearer tokens are stored hashed (SHA-256) in the manager database
- Tokens are shown only once on creation
- Tokens can be revoked at any time from the Settings page
- Tokens bypass CORS origin requirements (explicit opt-in authentication)
- The manager bearer token is only used for project discovery. It never reaches the opencode server.
- Manager bearer tokens are stored hashed (SHA-256) in the manager database and shown only once on creation.
+12 -1
View File
@@ -5,7 +5,18 @@
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": "./dist/index.js"
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"./server": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"./tui": {
"import": "./dist/tui.js",
"types": "./dist/tui.d.ts"
}
},
"peerDependencies": {
"@opencode-ai/plugin": ">=1.14.0",
+45 -31
View File
@@ -1,9 +1,14 @@
import type { Plugin, WorkspaceAdaptor, WorkspaceInfo } from "@opencode-ai/plugin"
import type { Plugin, PluginInput, WorkspaceAdaptor, WorkspaceInfo } from "@opencode-ai/plugin"
import { ManagerClient } from "./client.js"
import { pluginLogger } from "./logger.js"
import { PluginOptionsSchema, type ManagerProject } from "./types.js"
export function resolveConfig(options: unknown): { url: string; token: string } {
export interface ResolvedConfig {
url: string
token: string
}
export function resolveConfig(options: unknown): ResolvedConfig {
const parsed = PluginOptionsSchema.parse(options ?? {})
const url = parsed.url ?? process.env.OPENCODE_MANAGER_URL
const token = parsed.token ?? process.env.OPENCODE_MANAGER_TOKEN
@@ -12,55 +17,64 @@ export function resolveConfig(options: unknown): { url: string; token: string }
return { url, token }
}
export function makeAdaptor(cfg: { url: string; token: string }, project: ManagerProject): WorkspaceAdaptor {
export function makeAdaptor(cfg: ResolvedConfig, project: ManagerProject): WorkspaceAdaptor {
return {
name: `Manager: ${project.name}`,
description: `Connect to the "${project.name}" project on opencode-manager at ${cfg.url}`,
description: `Connect to the "${project.name}" project`,
configure(info: WorkspaceInfo) {
const result = { ...info, name: project.name, directory: project.directory, extra: { slug: project.slug } }
pluginLogger.info(
`adaptor.configure slug=${project.slug} input=${JSON.stringify(info)} output=${JSON.stringify(result)}`,
)
return result
pluginLogger.info(`adaptor.configure slug=${project.slug} workspaceID=${info.id} dir=${project.directory}`)
return {
...info,
name: project.name,
directory: project.directory,
extra: { slug: project.slug },
}
},
async create(info, env) {
pluginLogger.info(
`adaptor.create slug=${project.slug} info=${JSON.stringify(info)} env_keys=${Object.keys(env ?? {}).join(",")}`,
)
async create(info) {
pluginLogger.info(`adaptor.create slug=${project.slug} workspaceID=${info.id} dir=${project.directory}`)
},
async remove(info) {
pluginLogger.info(`adaptor.remove slug=${project.slug} info=${JSON.stringify(info)}`)
pluginLogger.info(`adaptor.remove slug=${project.slug} workspaceID=${info.id}`)
},
target(info) {
const base = cfg.url.replace(/\/$/, "")
const url = `${base}/api/workspace-plugin/opencode/${encodeURIComponent(project.slug)}`
const result = {
type: "remote" as const,
url,
headers: { Authorization: `Bearer ${cfg.token}` },
}
pluginLogger.info(
`adaptor.target slug=${project.slug} input=${JSON.stringify(info)} output=${JSON.stringify({ type: result.type, url: result.url })}`,
)
return result
pluginLogger.info(`adaptor.target slug=${project.slug} workspaceID=${info.id} dir=${project.directory}`)
return { type: "local" as const, directory: project.directory }
},
}
}
export const OpencodeManagerWorkspacePlugin: Plugin = async ({ experimental_workspace }, options) => {
const prewarmed = new Set<string>()
async function prewarmProject(input: PluginInput, project: ManagerProject): Promise<void> {
if (prewarmed.has(project.directory)) return
prewarmed.add(project.directory)
const start = Date.now()
try {
await input.client.project.current({ query: { directory: project.directory } })
pluginLogger.info(
`prewarm.ok slug=${project.slug} dir=${project.directory} elapsed_ms=${Date.now() - start}`,
)
} catch (error) {
prewarmed.delete(project.directory)
pluginLogger.warn(
`prewarm.failed slug=${project.slug} dir=${project.directory} elapsed_ms=${Date.now() - start}`,
error,
)
}
}
export const OpencodeManagerWorkspacePlugin: Plugin = async (input, options) => {
try {
const cfg = resolveConfig(options)
pluginLogger.info(
`plugin.init url=${cfg.url} env.OPENCODE_EXPERIMENTAL_WORKSPACES=${process.env.OPENCODE_EXPERIMENTAL_WORKSPACES ?? "unset"} env.OPENCODE_EXPERIMENTAL=${process.env.OPENCODE_EXPERIMENTAL ?? "unset"}`,
)
pluginLogger.info(`plugin.init url=${cfg.url}`)
const client = new ManagerClient(cfg.url, cfg.token)
const projects = await client.listProjects()
pluginLogger.info(`plugin.init loaded ${projects.length} project(s)`)
for (const project of projects) {
pluginLogger.info(`plugin.register slug=${project.slug} name=${project.name}`)
experimental_workspace.register(`manager:${project.slug}`, makeAdaptor(cfg, project))
input.experimental_workspace.register(`manager:${project.slug}`, makeAdaptor(cfg, project))
}
pluginLogger.info(`plugin.ready`)
void Promise.all(projects.map((project) => prewarmProject(input, project)))
return {}
} catch (error) {
pluginLogger.error(`plugin.init failed`, error)
+144
View File
@@ -0,0 +1,144 @@
import type { TuiPlugin, TuiPluginApi } from "@opencode-ai/plugin/tui"
import { pluginLogger } from "./logger.js"
const MANAGER_WORKSPACE_PREFIX = "manager:"
type WorkspaceRecord = {
id: string
type: string
}
type PrewarmResult = {
ok: number
failed: number
durationMs: number
}
async function prewarmWorkspace(api: TuiPluginApi, workspaceID: string): Promise<PrewarmResult> {
const started = Date.now()
const client = api.client
const scoped = { workspace: workspaceID }
const tasks: Array<{ name: string; run: () => Promise<unknown> }> = [
{ name: "config.get", run: () => client.config.get(scoped) },
{ name: "config.providers", run: () => client.config.providers(scoped) },
{ name: "provider.list", run: () => client.provider.list(scoped) },
{ name: "provider.auth", run: () => client.provider.auth(scoped) },
{ name: "app.agents", run: () => client.app.agents(scoped) },
{ name: "command.list", run: () => client.command.list(scoped) },
{ name: "vcs.get", run: () => client.vcs.get(scoped) },
{ name: "session.status", run: () => client.session.status(scoped) },
{ name: "lsp.status", run: () => client.lsp.status(scoped) },
{ name: "formatter.status", run: () => client.formatter.status(scoped) },
]
const outcomes = await Promise.all(
tasks.map(async (task) => {
try {
await task.run()
return true
} catch (error) {
pluginLogger.warn(`tui.prewarm task failed workspaceID=${workspaceID} task=${task.name}`, error)
return false
}
}),
)
const ok = outcomes.filter(Boolean).length
return { ok, failed: outcomes.length - ok, durationMs: Date.now() - started }
}
async function refreshWorkspaceIndex(api: TuiPluginApi, index: Map<string, WorkspaceRecord>): Promise<void> {
try {
const res = await api.client.experimental.workspace.list()
const list = res.data ?? []
index.clear()
for (const item of list) {
if (typeof item.id !== "string" || typeof item.type !== "string") continue
index.set(item.id, { id: item.id, type: item.type })
}
pluginLogger.info(`tui.workspaceIndex refreshed count=${index.size}`)
} catch (error) {
pluginLogger.warn(`tui.workspaceIndex refresh failed`, error)
}
}
function isManagerWorkspace(record: WorkspaceRecord | undefined): boolean {
return !!record && record.type.startsWith(MANAGER_WORKSPACE_PREFIX)
}
export const OpencodeManagerWorkspaceTuiPlugin: TuiPlugin = async (api) => {
pluginLogger.info(`tui.init`)
const workspaceIndex = new Map<string, WorkspaceRecord>()
const inflight = new Map<string, Promise<PrewarmResult>>()
const runPrewarm = (workspaceID: string, reason: string) => {
const existing = inflight.get(workspaceID)
if (existing) return existing
pluginLogger.info(`tui.prewarm start workspaceID=${workspaceID} reason=${reason}`)
const task = prewarmWorkspace(api, workspaceID)
.then((result) => {
pluginLogger.info(
`tui.prewarm done workspaceID=${workspaceID} reason=${reason} ok=${result.ok} failed=${result.failed} durationMs=${result.durationMs}`,
)
return result
})
.finally(() => {
inflight.delete(workspaceID)
})
inflight.set(workspaceID, task)
return task
}
await refreshWorkspaceIndex(api, workspaceIndex)
const offSessionCreated = api.event.on("session.created", (event) => {
const workspaceID = event.properties.info.workspaceID
if (!workspaceID) return
const record = workspaceIndex.get(workspaceID)
if (isManagerWorkspace(record)) {
void runPrewarm(workspaceID, "session.created")
return
}
void refreshWorkspaceIndex(api, workspaceIndex).then(() => {
const refreshed = workspaceIndex.get(workspaceID)
if (isManagerWorkspace(refreshed)) {
void runPrewarm(workspaceID, "session.created:after-refresh")
}
})
})
const offWorkspaceStatus = api.event.on("workspace.status", (event) => {
const { workspaceID, status } = event.properties
if (status !== "connected") return
const record = workspaceIndex.get(workspaceID)
if (isManagerWorkspace(record)) {
void runPrewarm(workspaceID, "workspace.status:connected")
return
}
void refreshWorkspaceIndex(api, workspaceIndex).then(() => {
const refreshed = workspaceIndex.get(workspaceID)
if (isManagerWorkspace(refreshed)) {
void runPrewarm(workspaceID, "workspace.status:connected:after-refresh")
}
})
})
api.lifecycle.onDispose(() => {
offSessionCreated()
offWorkspaceStatus()
pluginLogger.info(`tui.dispose`)
})
}
export default {
id: "opencode-manager-workspace",
tui: OpencodeManagerWorkspaceTuiPlugin,
}
+70 -25
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { PluginOptionsSchema } from '../src/types'
import { resolveConfig } from '../src/index'
import type { WorkspaceInfo } from '@opencode-ai/plugin'
@@ -14,6 +14,12 @@ describe('PluginOptionsSchema', () => {
expect(parsed.token).toBe('test-token')
})
it('ignores unknown fields', () => {
const parsed = PluginOptionsSchema.parse({ url: 'http://test.com', token: 'test', unknownField: 'ignored' })
expect(parsed.url).toBe('http://test.com')
expect(parsed.token).toBe('test')
})
it('requires token to be non-empty', () => {
expect(() => PluginOptionsSchema.parse({ token: '' })).toThrow()
})
@@ -40,8 +46,14 @@ describe('resolveConfig', () => {
})
it('uses options when provided', () => {
const cfg = resolveConfig({ url: 'http://options.com', token: 'options-token' })
expect(cfg).toEqual({ url: 'http://options.com', token: 'options-token' })
const cfg = resolveConfig({
url: 'http://options.com',
token: 'options-token',
})
expect(cfg).toEqual({
url: 'http://options.com',
token: 'options-token',
})
})
it('falls back to env vars when options omit fields', () => {
@@ -49,15 +61,24 @@ describe('resolveConfig', () => {
process.env.OPENCODE_MANAGER_TOKEN = 'env-token'
const cfg = resolveConfig({})
expect(cfg).toEqual({ url: 'http://env.com', token: 'env-token' })
expect(cfg).toEqual({
url: 'http://env.com',
token: 'env-token',
})
})
it('prefers options over env vars when both present', () => {
process.env.OPENCODE_MANAGER_URL = 'http://env.com'
process.env.OPENCODE_MANAGER_TOKEN = 'env-token'
const cfg = resolveConfig({ url: 'http://options.com', token: 'options-token' })
expect(cfg).toEqual({ url: 'http://options.com', token: 'options-token' })
const cfg = resolveConfig({
url: 'http://options.com',
token: 'options-token',
})
expect(cfg).toEqual({
url: 'http://options.com',
token: 'options-token',
})
})
it('throws when url missing from both options and env', () => {
@@ -78,32 +99,56 @@ describe('adaptor.target', () => {
extra: {},
}
it('returns { type: "remote", url, headers } with bearer auth when target is invoked', async () => {
const baseCfg = {
url: 'http://manager.test:5003',
token: 'tok-abc',
}
it('returns { type: "local", directory: project.directory }', async () => {
const { makeAdaptor } = await import('../src/index.js')
const cfg = { url: 'http://manager.test:5003', token: 'tok-abc' }
const project = { slug: '42', name: 'Test Project', directory: '/workspace/repos/test' }
const adaptor = makeAdaptor(cfg, project)
const adaptor = makeAdaptor(baseCfg, project)
const result = adaptor.target(sampleInfo)
expect(result.type).toBe('remote')
expect(result.url).toBe('http://manager.test:5003/api/workspace-plugin/opencode/42')
expect(result.headers).toEqual({ Authorization: 'Bearer tok-abc' })
expect(result.type).toBe('local')
expect(result.directory).toBe('/workspace/repos/test')
})
it('url-encodes special slug characters', async () => {
it('returns directory from project, not from info', async () => {
const { makeAdaptor } = await import('../src/index.js')
const cfg = { url: 'http://manager.test:5003', token: 'tok-abc' }
const project = { slug: 'a/b c', name: 'Test Project', directory: '/workspace/repos/test' }
const adaptor = makeAdaptor(cfg, project)
const result = adaptor.target(sampleInfo)
expect(result.url).toContain('a%2Fb%20c')
})
it('strips trailing slash from manager url', async () => {
const { makeAdaptor } = await import('../src/index.js')
const cfg = { url: 'http://manager.test:5003/', token: 'tok-abc' }
const project = { slug: '42', name: 'Test Project', directory: '/workspace/repos/test' }
const adaptor = makeAdaptor(cfg, project)
const adaptor = makeAdaptor(baseCfg, project)
const result = adaptor.target(sampleInfo)
expect(result.url).toBe('http://manager.test:5003/api/workspace-plugin/opencode/42')
expect(result.directory).toBe('/workspace/repos/test')
})
})
describe('adaptor.configure', () => {
const sampleInfo: WorkspaceInfo = {
name: 'Test Workspace',
directory: '/test/dir',
extra: {},
}
const cfg = {
url: 'http://manager.test:5003',
token: 'tok-abc',
}
it('returns project directory in configured workspace info', async () => {
const { makeAdaptor } = await import('../src/index.js')
const project = { slug: '42', name: 'Test Project', directory: '/workspace/repos/test' }
const adaptor = makeAdaptor(cfg, project)
const result = adaptor.configure(sampleInfo)
expect(result.directory).toBe('/workspace/repos/test')
})
it('returns extra with slug in configured workspace info', async () => {
const { makeAdaptor } = await import('../src/index.js')
const project = { slug: '42', name: 'Test Project', directory: '/workspace/repos/test' }
const adaptor = makeAdaptor(cfg, project)
const result = adaptor.configure(sampleInfo)
expect(result.extra).toEqual({ slug: '42' })
})
})