feat(opencode): migrate OpenCode Manager to OpenCode 2

Port the backend lifecycle, generated plugins, event aggregation,
schedules, worktrees, provider credentials, MCP, config handling, the
frontend chat model, and the ocm CLI to OpenCode 2.

Adopt @opencode/client 2.0.15 as the single typed V2 API contract,
require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every
V1-only code path.
This commit is contained in:
Chris Scott committed 2026-09-24 08:38:26 -04:00
1 parent 6c2ebd764b
commit 7351d5f002
313 files changed
+23848 -36801

No files matched your search

-62
View File
@@ -1,62 +0,0 @@
import { existsSync, readdirSync, statSync } from 'fs'
import { homedir } from 'os'
import { isAbsolute, join } from 'path'
import type { HistoryEventRow } from './session-move.js'
function opencodeDataDir(): string {
const xdg = process.env.XDG_DATA_HOME
return xdg ? join(xdg, 'opencode') : join(homedir(), '.local', 'share', 'opencode')
}
/**
* Resolves the opencode durable-event database path the same way
* `Database.path()` does in opencode core: an `OPENCODE_DB` override wins,
* then the default `opencode.db`, then the newest channel-suffixed variant
* (`opencode-<channel>.db`) for non-release channels.
*/
export function resolveOpencodeDbPath(): string | null {
const override = process.env.OPENCODE_DB
const dataDir = opencodeDataDir()
if (override) {
if (override === ':memory:' || isAbsolute(override)) return override
return join(dataDir, override)
}
const defaultPath = join(dataDir, 'opencode.db')
if (existsSync(defaultPath)) return defaultPath
if (!existsSync(dataDir)) return null
const variants = readdirSync(dataDir)
.filter((name) => name.startsWith('opencode-') && name.endsWith('.db'))
.map((name) => join(dataDir, name))
.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)
return variants[0] ?? null
}
export async function readSessionEvents(sessionID: string): Promise<HistoryEventRow[]> {
const dbPath = resolveOpencodeDbPath()
if (!dbPath) {
throw new Error('opencode database not found; is this machine running opencode with durable history?')
}
const { Database } = await import('bun:sqlite')
const db = new Database(dbPath, { readonly: true })
try {
const rows = db
.query<{ id: string; aggregate_id: string; seq: number; type: string; data: string }, [string]>(
'SELECT id, aggregate_id, seq, type, data FROM event WHERE aggregate_id = ? ORDER BY seq ASC',
)
.all(sessionID)
return rows.map((row) => ({
id: row.id,
aggregate_id: row.aggregate_id,
seq: row.seq,
type: row.type,
data: JSON.parse(row.data) as Record<string, unknown>,
}))
} finally {
db.close()
}
}
-34
View File
@@ -1,34 +0,0 @@
import type { ReplayEvent } from './session-move.js'
export function createManagerReplay(managerUrl: string, token: string) {
return async (remoteDirectory: string, events: ReplayEvent[]): Promise<{ sessionID: string }> => {
const url = `${managerUrl}/api/opencode-proxy/sync/replay?directory=${encodeURIComponent(remoteDirectory)}`
const res = await fetch(url, {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: JSON.stringify({ directory: remoteDirectory, events }),
})
if (!res.ok) {
const text = await res.text().catch(() => '')
throw new Error(`replay failed (${res.status}): ${text.slice(0, 200)}`)
}
return (await res.json()) as { sessionID: string }
}
}
export function createManagerPromptAsync(managerUrl: string, token: string) {
return async (remoteDirectory: string, sessionID: string, text: string): Promise<void> => {
const url = `${managerUrl}/api/opencode-proxy/session/${encodeURIComponent(sessionID)}/prompt_async?directory=${encodeURIComponent(remoteDirectory)}`
const res = await fetch(url, {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: JSON.stringify({ noReply: true, parts: [{ type: 'text', text, synthetic: true }] }),
})
if (!res.ok) {
const body = await res.text().catch(() => '')
throw new Error(`prompt_async failed (${res.status}): ${body.slice(0, 200)}`)
}
}
}
+21
View File
@@ -0,0 +1,21 @@
import { createOpenCodeApi } from '@opencode-manager/shared/opencode'
import type { SessionTransferData } from '@opencode-manager/shared/opencode'
export function createManagerSessionTransfer(managerUrl: string, token: string) {
const api = createOpenCodeApi({
baseUrl: `${managerUrl}/api/opencode-proxy`,
password: token,
})
return {
importSession: async (remoteDirectory: string, data: SessionTransferData): Promise<{ sessionID: string }> => {
const session = await api.session.import({
info: data.info,
messages: data.messages,
location: { directory: remoteDirectory },
})
return { sessionID: session.id }
},
addReminder: (sessionID: string, text: string) => api.session.synthetic({ sessionID, text }),
}
}
+57 -140
View File
@@ -1,82 +1,53 @@
export type HistoryEventRow = { id: string; aggregate_id: string; seq: number; type: string; data: Record<string, unknown> }
export type ReplayEvent = { id: string; aggregateID: string; seq: number; type: string; data: Record<string, unknown> }
export type CollectResult =
| { kind: 'ok'; events: ReplayEvent[] }
| { kind: 'empty' }
| { kind: 'gap'; missingSeq: number }
import { fileURLToPath, pathToFileURL } from 'node:url'
import type { SessionTransferData } from '@opencode-manager/shared/opencode'
export type RewriteContext = { localRoot: string; remoteRoot: string }
export function collectSessionEvents(rows: HistoryEventRow[], sessionID: string): CollectResult {
const filtered = rows.filter((r) => r.aggregate_id === sessionID)
if (filtered.length === 0) return { kind: 'empty' }
export function rewriteTransferForRemote(data: SessionTransferData, ctx: RewriteContext): SessionTransferData {
const cloned = structuredClone(data)
cloned.info.location.directory = relocatePath(cloned.info.location.directory, ctx)
relocateUris(cloned.messages, ctx)
return cloned
}
const sorted = [...filtered].sort((a, b) => a.seq - b.seq)
if (sorted[0]!.seq !== 0) return { kind: 'gap', missingSeq: 0 }
for (let i = 1; i < sorted.length; i++) {
if (sorted[i]!.seq !== sorted[i - 1]!.seq + 1) {
return { kind: 'gap', missingSeq: sorted[i - 1]!.seq + 1 }
}
function relocateUris(value: unknown, ctx: RewriteContext): void {
if (Array.isArray(value)) {
for (const item of value) relocateUris(item, ctx)
return
}
const events: ReplayEvent[] = sorted.map((r) => ({
id: r.id,
aggregateID: r.aggregate_id,
seq: r.seq,
type: r.type,
data: r.data,
}))
return { kind: 'ok', events }
if (!value || typeof value !== 'object') return
const record = value as Record<string, unknown>
if (typeof record.uri === 'string') record.uri = relocateUri(record.uri, ctx)
for (const child of Object.values(record)) relocateUris(child, ctx)
}
/**
* Rewrites collected replay events for replay on a remote Manager server.
*
* Coercion rule for `data.timestamp` matches the prior implementation in
* commit 686c820d (`coerceReplayBodyTimestamps`): ISO 8601 string timestamps
* are converted to epoch milliseconds via `Date.parse`; already-numeric values
* are left untouched.
*/
export function rewriteEventsForRemote(events: ReplayEvent[], ctx: RewriteContext): ReplayEvent[] {
return events.map((event) => {
const data = deepClone(event.data)
function relocateUri(uri: string, ctx: RewriteContext): string {
const fileUrl = parseLocalFileUrl(uri)
if (!fileUrl) return relocatePath(uri, ctx)
if (shouldRewriteDirectory(event.type)) {
rewriteDirectory(data, 'info', ctx)
stripWorkspaceID(data, 'info')
}
if (isMovedEvent(event.type)) {
rewriteDirectory(data, 'location', ctx)
stripWorkspaceID(data, 'location')
}
if (isMessageUpdated(event.type)) {
rewriteMessagePath(data, ctx)
}
coerceTimestamp(data)
return { ...event, data }
})
const relocated = relocatePath(fileUrl.path, ctx)
if (relocated === fileUrl.path) return uri
return `${pathToFileURL(relocated).href}${fileUrl.search}${fileUrl.hash}`
}
function shouldRewriteDirectory(type: string): boolean {
return type.startsWith('session.created') || type.startsWith('session.updated')
}
function parseLocalFileUrl(uri: string): { path: string; search: string; hash: string } | null {
if (!uri.startsWith('file:')) return null
function isMovedEvent(type: string): boolean {
return type.startsWith('session.next.moved')
}
let url: URL
try {
url = new URL(uri)
} catch {
return null
}
if (url.protocol !== 'file:' || (url.host !== '' && url.host !== 'localhost')) return null
function isMessageUpdated(type: string): boolean {
return type.startsWith('message.updated')
}
function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' ? (value as Record<string, unknown>) : null
let path: string
try {
path = fileURLToPath(url)
} catch {
return null
}
return { path, search: url.search, hash: url.hash }
}
function relocatePath(path: string, ctx: RewriteContext): string {
@@ -85,97 +56,43 @@ function relocatePath(path: string, ctx: RewriteContext): string {
return path
}
function relocateField(obj: Record<string, unknown>, key: string, ctx: RewriteContext): void {
const value = obj[key]
if (typeof value === 'string') obj[key] = relocatePath(value, ctx)
}
function rewriteDirectory(
data: Record<string, unknown>,
key: 'info' | 'location',
ctx: RewriteContext,
): void {
const container = asRecord(data[key])
if (container) relocateField(container, 'directory', ctx)
}
function rewriteMessagePath(data: Record<string, unknown>, ctx: RewriteContext): void {
const path = asRecord(asRecord(data.info)?.path)
if (!path) return
relocateField(path, 'cwd', ctx)
relocateField(path, 'root', ctx)
}
function stripWorkspaceID(data: Record<string, unknown>, key: 'info' | 'location'): void {
const container = asRecord(data[key])
if (container) delete container.workspaceID
}
/** Per commit 686c820d: coerce `data.timestamp` from ISO string to epoch ms. */
function coerceTimestamp(data: Record<string, unknown>): void {
const ts = data.timestamp
if (typeof ts !== 'string') return
const epoch = Date.parse(ts)
if (!Number.isFinite(epoch)) return
data.timestamp = epoch
}
export type TransferDeps = {
fetchLocalHistory: () => Promise<HistoryEventRow[]>
replayEvents: (remoteDirectory: string, events: ReplayEvent[]) => Promise<{ sessionID: string }>
onProgress?: (replayed: number, total: number) => void
exportSession: (sessionID: string) => Promise<SessionTransferData>
importSession: (remoteDirectory: string, data: SessionTransferData) => Promise<{ sessionID: string }>
onProgress?: (transferred: number, total: number) => void
}
export type TransferInput = { sessionID: string; localRoot: string; remoteDirectory: string }
export type TransferResult =
| { kind: 'moved'; sessionID: string; replayedEvents: number }
| { kind: 'not-found' }
| { kind: 'corrupt-history'; missingSeq: number }
| { kind: 'replay-failed'; message: string }
export function planReplayBatches(events: ReplayEvent[], batchSize = 10): ReplayEvent[][] {
const batches: ReplayEvent[][] = []
for (let i = 0; i < events.length; i += batchSize) {
batches.push(events.slice(i, i + batchSize))
}
return batches
}
export async function transferSession(input: TransferInput, deps: TransferDeps): Promise<TransferResult> {
const rows = await deps.fetchLocalHistory()
const collect = collectSessionEvents(rows, input.sessionID)
let data: SessionTransferData
try {
data = await deps.exportSession(input.sessionID)
} catch (err) {
return { kind: 'replay-failed', message: err instanceof Error ? err.message : String(err) }
}
if (collect.kind === 'empty') return { kind: 'not-found' }
if (collect.kind === 'gap') return { kind: 'corrupt-history', missingSeq: collect.missingSeq }
const rewritten = rewriteEventsForRemote(collect.events, {
const rewritten = rewriteTransferForRemote(data, {
localRoot: input.localRoot,
remoteRoot: input.remoteDirectory,
})
const total = rewritten.messages.length
deps.onProgress?.(0, total)
const batches = planReplayBatches(rewritten)
const total = rewritten.length
let replayed = 0
deps.onProgress?.(replayed, total)
for (const batch of batches) {
try {
await deps.replayEvents(input.remoteDirectory, batch)
replayed += batch.length
deps.onProgress?.(replayed, total)
} catch (err) {
return { kind: 'replay-failed', message: err instanceof Error ? err.message : String(err) }
}
try {
await deps.importSession(input.remoteDirectory, rewritten)
} catch (err) {
return { kind: 'replay-failed', message: err instanceof Error ? err.message : String(err) }
}
return { kind: 'moved', sessionID: input.sessionID, replayedEvents: replayed }
deps.onProgress?.(total, total)
return { kind: 'moved', sessionID: input.sessionID, replayedEvents: total }
}
export function moveReminderText(directory: string): string {
return `<system-reminder>The user has changed the current working directory to "${directory}". This is still the same project but at a possibly new location; take this into account when working with any files from now on.</system-reminder>`
}
function deepClone<T>(obj: T): T {
return JSON.parse(JSON.stringify(obj))
}
+6 -31
View File
@@ -1,38 +1,13 @@
import type { TuiPluginApi } from './tui-types.js'
import type { Context } from '@opencode/plugin/tui/context'
export function confirmDialog(api: TuiPluginApi, props: { title: string; message: string }): Promise<boolean> {
return new Promise<boolean>((resolve) => {
let settled = false
const settle = (value: boolean, clearDialog = true) => {
if (settled) return
settled = true
if (clearDialog) api.ui.dialog.clear()
resolve(value)
}
api.ui.dialog.replace(
() => api.ui.DialogConfirm({ ...props, onConfirm: () => settle(true), onCancel: () => settle(false) }),
() => settle(false, false),
)
})
export function confirmDialog(context: Context, props: { title: string; message: string }): Promise<boolean> {
return context.ui.dialog.confirm(props).then((value) => value === true)
}
export function selectDialog<Value>(
api: TuiPluginApi,
context: Context,
title: string,
options: { title: string; description?: string; value: Value }[],
): Promise<Value | undefined> {
return new Promise<Value | undefined>((resolve) => {
let settled = false
const settle = (value: Value | undefined, clearDialog = true) => {
if (settled) return
settled = true
if (clearDialog) api.ui.dialog.clear()
resolve(value)
}
const mapped = options.map((o) => ({ ...o, onSelect: () => settle(o.value) }))
api.ui.dialog.replace(
() => api.ui.DialogSelect({ title, options: mapped, onSelect: (o) => settle(o.value as Value) }),
() => settle(undefined, false),
)
})
}
return context.ui.dialog.select({ title, options })
}
+42 -50
View File
@@ -1,4 +1,4 @@
import type { TuiPluginApi } from './tui-types.js'
import type { Context } from '@opencode/plugin/tui/context'
import { readInstallNotice, readState } from './state.js'
import { getToken } from './internal-token-store.js'
import { TokenStoreError } from './token-store.js'
@@ -9,8 +9,7 @@ import { prepareMirror, checkPushDivergence, describePushDivergence, mirrorUpFas
import type { MirrorPlan, RemoteRepoSummary } from './mirror.js'
import { getBranchName } from './local-repo.js'
import { transferSession, moveReminderText } from './session-move.js'
import { createManagerReplay, createManagerPromptAsync } from './remote-replay.js'
import { readSessionEvents } from './local-history.js'
import { createManagerSessionTransfer } from './remote-session.js'
import { confirmDialog, selectDialog } from './tui-dialogs.js'
import { setPendingWarp, runPendingWarp } from './warp.js'
import { pushPhaseProgress, replayProgress } from './move-progress.js'
@@ -18,29 +17,29 @@ import type { MoveProgress } from './move-progress.js'
export type MoveProgressSetter = (progress: MoveProgress | null) => void
export async function setupOcm(api: TuiPluginApi, setMoveProgress: MoveProgressSetter): Promise<void> {
showInstallNotice(api)
api.keymap.registerLayer({
export async function setupOcm(context: Context, setMoveProgress: MoveProgressSetter): Promise<() => void> {
showInstallNotice(context)
context.keymap.layer(() => ({
commands: [
{
name: 'ocm.session.move',
id: 'ocm.session.move',
title: 'Move session to Manager',
desc: 'Push repo state and move this session to OpenCode Manager',
category: 'OpenCode Manager',
namespace: 'palette',
slashName: 'ocm-move',
run: () => runSessionMove(api, setMoveProgress),
description: 'Push repo state and move this session to OpenCode Manager',
group: 'OpenCode Manager',
palette: true,
slash: { name: 'ocm-move' },
run: () => runSessionMove(context, setMoveProgress),
},
],
})
api.lifecycle.onDispose(() => runPendingWarp())
}))
return () => runPendingWarp()
}
function showInstallNotice(api: TuiPluginApi): void {
function showInstallNotice(context: Context): void {
const notice = readInstallNotice()
if (!notice) return
api.ui.toast({
context.ui.toast.show({
variant: 'success',
title: 'ocm installed',
message: notice.pathMissing
@@ -83,24 +82,24 @@ async function resolveMoveTarget(managerApi: ManagerApi, matched: RemoteRepoSumm
return managerApi.mirrorTargetPlan(matched.repoId, localBranch)
}
async function runSessionMove(api: TuiPluginApi, setMoveProgress: MoveProgressSetter): Promise<void> {
async function runSessionMove(context: Context, setMoveProgress: MoveProgressSetter): Promise<void> {
try {
const current = api.route.current
if (current.name !== 'session' || !current.params) {
api.ui.toast({ variant: 'error', message: 'Not in a session' })
const current = context.ui.router.current()
if (current.type !== 'session') {
context.ui.toast.show({ variant: 'error', message: 'Not in a session' })
return
}
const sessionID = String(current.params.sessionID)
const sessionID = current.sessionID
const session = api.state.session.get(sessionID)
if (!session?.directory) {
api.ui.toast({ variant: 'error', message: 'Session has no directory' })
const session = context.data.session.get(sessionID)
if (!session?.location.directory) {
context.ui.toast.show({ variant: 'error', message: 'Session has no directory' })
return
}
const state = readState()
if (!state?.managerUrl) {
api.ui.toast({ variant: 'error', message: 'No manager configured. Run `ocm login <url>` first.' })
context.ui.toast.show({ variant: 'error', message: 'No manager configured. Run `ocm login <url>` first.' })
return
}
@@ -109,25 +108,25 @@ async function runSessionMove(api: TuiPluginApi, setMoveProgress: MoveProgressSe
token = await getToken(state.managerUrl)
} catch (err) {
const reason = err instanceof TokenStoreError ? err.message : String(err)
api.ui.toast({ variant: 'error', message: `Token store unavailable: ${reason}` })
context.ui.toast.show({ variant: 'error', message: `Token store unavailable: ${reason}` })
return
}
if (!token) {
api.ui.toast({ variant: 'error', message: `No token stored. Run \`ocm login ${state.managerUrl}\`.` })
context.ui.toast.show({ variant: 'error', message: `No token stored. Run \`ocm login ${state.managerUrl}\`.` })
return
}
const repos = await fetchRepos(state.managerUrl, token)
const plan = await prepareMirror(session.directory, toRemoteRepoSummaries(repos))
const plan = await prepareMirror(session.location.directory, toRemoteRepoSummaries(repos))
if (plan.matched.length === 0) {
api.ui.toast({ variant: 'error', message: 'No matching Manager repo; run `ocm push --create` first' })
context.ui.toast.show({ variant: 'error', message: 'No matching Manager repo; run `ocm push --create` first' })
return
}
const localBranch = getBranchName(plan.repoRoot)
const matched = pickMatchedRepo(plan.matched, localBranch)
?? await selectDialog(api, 'Move session to Manager repo', plan.matched.map((r) => ({ title: r.name, description: `id=${r.repoId} branch=${r.branch ?? '-'}`, value: r })))
?? await selectDialog(context, 'Move session to Manager repo', plan.matched.map((r) => ({ title: r.name, description: `id=${r.repoId} branch=${r.branch ?? '-'}`, value: r })))
if (!matched) return
const matchedRepoId = matched.repoId
const remoteRepo = repos.find((r) => r.repoId === matchedRepoId)!
@@ -136,7 +135,7 @@ async function runSessionMove(api: TuiPluginApi, setMoveProgress: MoveProgressSe
const target = await resolveMoveTarget(managerApi, matched, remoteRepo.directory, localBranch)
const discardReasons = target.repoId === null ? [] : await describeRemoteDiscard(plan.repoRoot, managerApi, target.repoId)
const proceed = await confirmDialog(api, {
const proceed = await confirmDialog(context, {
title: 'Move session to Manager',
message: moveConfirmMessage(matched.name, target, discardReasons),
})
@@ -156,45 +155,38 @@ async function runSessionMove(api: TuiPluginApi, setMoveProgress: MoveProgressSe
})
const remoteDirectory = pushed.fullPath
const transfer = createManagerSessionTransfer(state.managerUrl, token)
const result = await transferSession(
{ sessionID, localRoot: plan.repoRoot, remoteDirectory },
{
fetchLocalHistory: () => readSessionEvents(sessionID),
replayEvents: createManagerReplay(state.managerUrl, token),
onProgress: (replayed, total) => setMoveProgress(replayProgress(replayed, total)),
exportSession: (id) => context.client.session.export({ sessionID: id }),
importSession: transfer.importSession,
onProgress: (transferred, total) => setMoveProgress(replayProgress(transferred, total)),
},
)
switch (result.kind) {
case 'moved': {
setMoveProgress({ label: 'notifying moved session', fraction: null })
await createManagerPromptAsync(state.managerUrl, token)(remoteDirectory, result.sessionID, moveReminderText(remoteDirectory)).catch(() => undefined)
await transfer.addReminder(result.sessionID, moveReminderText(remoteDirectory)).catch(() => undefined)
setMoveProgress(null)
const warp = await confirmDialog(api, { title: 'Attach to moved session?', message: 'Exit this TUI and attach to the moved session on the Manager now?' })
const warp = await confirmDialog(context, { title: 'Attach to moved session?', message: 'Exit this TUI and attach to the moved session on the Manager now?' })
if (warp) {
await fetch(`${state.managerUrl}/api/opencode-proxy/session?directory=${encodeURIComponent(remoteDirectory)}`, { headers: { authorization: `Bearer ${token}` } }).catch(() => undefined)
setPendingWarp({ managerUrl: state.managerUrl, token, directory: remoteDirectory, sessionID: result.sessionID, repoName: matched.name })
api.keymap.dispatchCommand('app.exit')
await fetch(`${state.managerUrl}/api/opencode-proxy/repos/${pushed.repoId}/api/session?limit=1`, { headers: { authorization: `Bearer ${token}` } }).catch(() => undefined)
setPendingWarp({ managerUrl: state.managerUrl, token, repoId: pushed.repoId, sessionID: result.sessionID, repoName: matched.name })
context.keymap.dispatch('app.exit')
return
}
api.ui.toast({ variant: 'success', message: `Session moved to Manager (${result.replayedEvents} events). Local copy kept — run \`ocm\` to attach.` })
context.ui.toast.show({ variant: 'success', message: `Session moved to Manager (${result.replayedEvents} events). Local copy kept — run \`ocm\` to attach.` })
break
}
case 'not-found':
api.ui.toast({ variant: 'error', message: 'No durable history found for this session' })
break
case 'corrupt-history':
api.ui.toast({ variant: 'error', message: `Session history has a gap at sequence ${result.missingSeq}` })
break
case 'replay-failed':
api.ui.toast({ variant: 'error', message: `Replay failed: ${result.message}` })
context.ui.toast.show({ variant: 'error', message: `Replay failed: ${result.message}` })
break
}
} catch (err) {
api.ui.toast({ variant: 'error', message: err instanceof Error ? err.message : String(err) })
context.ui.toast.show({ variant: 'error', message: err instanceof Error ? err.message : String(err) })
} finally {
setMoveProgress(null)
}
}
export { readRemoteContext } from './remote-context.js'
-34
View File
@@ -1,34 +0,0 @@
import type { RGBA } from '@opentui/core'
export type TuiThemeColors = {
accent: RGBA
text: RGBA
textMuted: RGBA
backgroundElement: RGBA
}
export type TuiSlotContext = { theme: { readonly current: TuiThemeColors } }
export type TuiSlotRegistration = {
order?: number
slots: Record<string, (ctx: TuiSlotContext, props: Record<string, unknown>) => unknown>
}
export type TuiRouteCurrent = { name: 'session'; params: { sessionID: string } } | { name: string; params?: Record<string, unknown> }
export type TuiSessionInfo = { id: string; directory: string; title?: string }
export type TuiToast = { title?: string; message: string; variant?: 'info' | 'success' | 'error' | 'warning'; duration?: number }
export type TuiCommandDef = { name: string; title: string; desc?: string; category?: string; namespace?: string; slashName?: string; run: () => void | Promise<void> }
export type TuiDialogConfirmProps = { title: string; message: string; onConfirm?: () => void; onCancel?: () => void }
export type TuiDialogSelectOption<Value = unknown> = { title: string; value?: Value; description?: string; disabled?: boolean; onSelect?: () => void }
export type TuiDialogSelectProps<Value = unknown> = { title: string; placeholder?: string; options: TuiDialogSelectOption<Value>[]; onSelect?: (option: TuiDialogSelectOption<Value>) => void }
export type TuiDialogStack = { replace: (render: () => unknown, onClose?: () => void) => void; clear: () => void }
export type TuiLifecycle = { readonly signal: AbortSignal; onDispose: (fn: () => void | Promise<void>) => () => void }
export type TuiPluginApi = {
route: { readonly current: TuiRouteCurrent }
state: { session: { get: (sessionID: string) => TuiSessionInfo | undefined } }
ui: { toast: (input: TuiToast) => void; DialogConfirm: (props: TuiDialogConfirmProps) => unknown; DialogSelect: <Value = unknown>(props: TuiDialogSelectProps<Value>) => unknown; dialog: TuiDialogStack }
keymap: { registerLayer: (layer: { commands: TuiCommandDef[]; bindings?: Record<string, unknown> }) => unknown; dispatchCommand: (name: string) => unknown }
slots: { register: (registration: TuiSlotRegistration) => string }
lifecycle: TuiLifecycle
}
export type TuiPluginModule = { id?: string; tui: (api: TuiPluginApi, options?: Record<string, unknown>) => Promise<void> }
+37 -48
View File
@@ -1,60 +1,49 @@
/** @jsxImportSource @opentui/solid */
import { createSignal, createEffect, onCleanup, Show } from 'solid-js'
import { setupOcm, readRemoteContext } from './tui-plugin.js'
import { Plugin } from '@opencode/plugin/tui'
import { setupOcm } from './tui-plugin.js'
import { formatMoveProgress } from './move-progress.js'
import type { MoveProgress } from './move-progress.js'
import type { TuiPluginApi, TuiPluginModule, TuiSlotContext } from './tui-types.js'
import { readRemoteContext } from './remote-context.js'
const SPINNER_INTERVAL_MS = 80
const tui = async (api: TuiPluginApi): Promise<void> => {
const [moveProgress, setMoveProgress] = createSignal<MoveProgress | null>(null)
await setupOcm(api, setMoveProgress)
export default Plugin.define({
id: 'ocm',
async setup(context) {
const [moveProgress, setMoveProgress] = createSignal<MoveProgress | null>(null)
const moveIndicator = (ctx: TuiSlotContext) => {
const theme = ctx.theme.current
const [frame, setFrame] = createSignal(0)
createEffect(() => {
if (!moveProgress()) return
const timer = setInterval(() => setFrame((f) => f + 1), SPINNER_INTERVAL_MS)
onCleanup(() => clearInterval(timer))
})
return (
<box flexDirection="row" flexShrink={0}>
<Show when={moveProgress()}>
{(progress) => <text fg={theme.accent}>{formatMoveProgress(progress(), frame())}</text>}
</Show>
</box>
)
}
const moveIndicator = () => {
const [frame, setFrame] = createSignal(0)
createEffect(() => {
if (!moveProgress()) return
const timer = setInterval(() => setFrame((f) => f + 1), SPINNER_INTERVAL_MS)
onCleanup(() => clearInterval(timer))
})
return (
<box flexDirection="row" flexShrink={0}>
<Show when={moveProgress()}>
{(progress) => <text fg={context.theme.hue.accent[200]}>{formatMoveProgress(progress(), frame())}</text>}
</Show>
</box>
)
}
api.slots.register({
order: 290,
slots: { session_prompt_right: moveIndicator },
})
context.ui.slot({ append: 'prompt.footer.status', render: moveIndicator })
const remote = readRemoteContext(process.env)
if (!remote) return
const remote = readRemoteContext(process.env)
if (remote) {
const indicator = () => (
<box flexDirection="row" flexShrink={0} gap={1}>
<text fg={context.theme.hue.accent[200]}>{remote.managerHost}</text>
{remote.repoName && <text fg={context.theme.text.muted}> · {remote.repoName}</text>}
</box>
)
const indicator = (ctx: TuiSlotContext) => {
const theme = ctx.theme.current
return (
<box flexDirection="row" flexShrink={0} gap={1}>
<text fg={theme.accent}>{remote.managerHost}</text>
{remote.repoName && (
<text fg={theme.textMuted}> · {remote.repoName}</text>
)}
</box>
)
}
context.ui.slot({ append: 'prompt.footer.status', render: indicator })
context.ui.slot({ append: 'home.footer.status', render: indicator })
}
api.slots.register({
order: 300,
slots: {
session_prompt_right: indicator,
home_prompt_right: indicator,
},
})
}
export default { id: 'ocm', tui } satisfies TuiPluginModule
return setupOcm(context, setMoveProgress)
},
})
+7 -9
View File
@@ -4,7 +4,7 @@ import { buildRemoteAttachEnv } from './remote-context.js'
export type WarpTarget = {
managerUrl: string
token: string
directory: string
repoId: number
sessionID: string
repoName: string
}
@@ -29,12 +29,10 @@ export function takePendingWarp(): WarpTarget | undefined {
export function buildAttachArgs(target: WarpTarget): string[] {
return [
'attach',
`${target.managerUrl}/api/opencode-proxy`,
'--dir', target.directory,
'--session', target.sessionID,
'--password', target.token,
'--username', 'opencode',
'--server',
`${target.managerUrl}/api/opencode-proxy/repos/${target.repoId}`,
'--session',
target.sessionID,
]
}
@@ -44,9 +42,9 @@ export function runPendingWarp(spawn: WarpSpawn = spawnSync): void {
try {
spawn('opencode', buildAttachArgs(target), {
stdio: 'inherit',
env: { ...process.env, ...buildRemoteAttachEnv(target.managerUrl, target.repoName) },
env: { ...process.env, OPENCODE_PASSWORD: target.token, ...buildRemoteAttachEnv(target.managerUrl, target.repoName) },
})
} catch {
void 0
}
}
}