Compare commits

..

1 Commits

Author SHA1 Message Date
Aiden Cline c4cba53f67 fix(core): refresh Console auth before catalog load 2026-08-04 20:00:21 +00:00
6 changed files with 139 additions and 257 deletions
+12 -1
View File
@@ -89,14 +89,24 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Scope
const http = yield* HttpClient.HttpClient
const loading = Semaphore.makeUnsafe(1)
let connected = false
let savedConnection = false
let providers: typeof ConfigV1.Info.Type.provider | undefined
const load = Effect.fn("OpencodePlugin.load")(function* () {
const connection = yield* ctx.integration.connection.active("opencode")
const credential = connection
const resolved = connection
? yield* ctx.integration.connection.resolve(connection).pipe(Effect.catch(() => Effect.succeed(undefined)))
: undefined
// Plugin activation batches transforms, so the first resolve can precede this plugin's OAuth registration.
const credential =
connection && resolved?.type === "oauth" && resolved.expires <= Date.now() + Duration.toMillis(Duration.minutes(5))
? yield* ctx.integration.reload().pipe(
Effect.andThen(ctx.integration.connection.resolve(connection)),
Effect.catch(() => Effect.succeed(undefined)),
)
: resolved
connected = connection !== undefined
savedConnection = connection?.type === "credential"
providers = credential
? yield* fetchProviders(http, credential).pipe(
Effect.catch((cause) =>
@@ -116,6 +126,7 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Scope
yield* load()
yield* ctx.catalog.transform((catalog) => {
if (savedConnection && providers === undefined) catalog.provider.remove(Provider.ID.opencode)
for (const [providerID, item] of Object.entries(providers ?? {})) {
catalog.provider.update(providerID, (provider) => {
provider.integrationID = Integration.ID.make("opencode")
@@ -10,6 +10,7 @@ import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host"
import { OpencodePlugin } from "@opencode-ai/core/plugin/provider/opencode"
import { Provider } from "@opencode-ai/core/provider"
import { State } from "@opencode-ai/core/state"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -283,6 +284,96 @@ describe("OpencodePlugin", () => {
),
)
it.live("refreshes saved OAuth before loading the Console catalog on cold startup", () =>
Effect.acquireUseRelease(
Effect.sync(() => {
const requests: string[] = []
return {
requests,
server: Bun.serve({
port: 0,
fetch: (request) => {
const url = new URL(request.url)
if (url.pathname === "/auth/device/token") {
requests.push("refresh")
return Response.json({ access_token: "fresh", refresh_token: "next", expires_in: 600 })
}
if (url.pathname === "/api/config") {
requests.push(`config:${request.headers.get("authorization")}`)
return Response.json({
config: {
provider: {
console: {
name: "Console",
npm: "@ai-sdk/openai-compatible",
models: { current: { name: "Current" } },
},
},
},
})
}
return new Response("Not found", { status: 404 })
},
}),
}
}),
({ requests, server }) =>
Effect.gen(function* () {
yield* (yield* Credential.Service).create({
integrationID: Integration.ID.make("opencode"),
value: Credential.OAuth.make({
type: "oauth",
methodID: Integration.MethodID.make("device"),
access: "expired",
refresh: "refresh",
expires: 1,
metadata: { server: server.url.origin },
}),
})
yield* State.batch(addPlugin())
expect(requests).toEqual(["refresh", "config:Bearer fresh"])
expect(
yield* (yield* Catalog.Service).model.get(Provider.ID.make("console"), Model.ID.make("current")),
).toBeDefined()
}),
({ server }) => Effect.promise(() => server.stop(true)),
),
)
it.live("hides legacy fallback models when Console configuration fails", () =>
Effect.acquireUseRelease(
Effect.sync(() =>
Bun.serve({
port: 0,
fetch: () => new Response("Unauthorized", { status: 401 }),
}),
),
(server) =>
Effect.gen(function* () {
const catalog = yield* Catalog.Service
yield* catalog.transform((draft) => {
draft.provider.update(Provider.ID.opencode, () => {})
draft.model.update(Provider.ID.opencode, Model.ID.make("legacy"), () => {})
})
yield* (yield* Credential.Service).create({
integrationID: Integration.ID.make("opencode"),
value: Credential.Key.make({
type: "key",
key: "console-key",
metadata: { server: server.url.origin },
}),
})
yield* State.batch(addPlugin())
expect(yield* catalog.model.get(Provider.ID.opencode, Model.ID.make("legacy"))).toBeUndefined()
}),
(server) => Effect.promise(() => server.stop(true)),
),
)
it.effect("uses a public key and disables paid models without credentials", () =>
withEnv({ OPENCODE_API_KEY: undefined }, () =>
Effect.gen(function* () {
+36 -69
View File
@@ -53,7 +53,6 @@ import { useLocation } from "../../context/location"
import { Keymap, type KeymapCommand } from "../../context/keymap"
import { abbreviateHome } from "../../runtime"
import { PluginSlot } from "../../plugin/render"
import { createPromptSubmission } from "../../prompt/submission"
export type PromptProps = {
sessionID?: string
@@ -253,7 +252,6 @@ export function Prompt(props: PromptProps) {
const [cursorVersion, setCursorVersion] = createSignal(0)
const currentProviderLabel = createMemo(() => local.model.parsed().provider)
const connected = useConnected()
const promptSubmission = createPromptSubmission()
const hasRightContent = createMemo(() => Boolean(props.right))
function promptModelWarning() {
@@ -954,72 +952,27 @@ export function Prompt(props: PromptProps) {
}
const variant = local.model.variant.current()
const currentMode = store.mode
const prompt = {
text: store.prompt.text,
files: store.prompt.files?.map((file) => ({
...file,
mention: file.mention && { ...file.mention },
})),
agents: store.prompt.agents?.map((agent) => ({
...agent,
mention: agent.mention && { ...agent.mention },
})),
pasted: store.prompt.pasted.map((part) => ({
...part,
source: { ...part.source },
})),
} satisfies PromptInfo
const inputText = expandTrackedPastedText(
prompt.text,
input.extmarks.getAllForTypeId(promptPartTypeId).flatMap((extmark) => {
const ref = store.extmarkToPart.get(extmark.id)
if (ref?.type !== "pasted") return []
const part = prompt.pasted[ref.index]
if (!part) return []
return [{ start: extmark.start, end: extmark.end, text: part.text }]
}),
)
const directory = props.sessionID == null ? await move.getDirectory() : undefined
if (props.sessionID == null && move.pending() && !directory) return false
const sessionInput = {
location: directory ? { directory } : (currentLocation.ref ?? data.location.default()),
agent: agent.id,
model: {
providerID: selectedModel.providerID,
id: selectedModel.modelID,
variant,
},
}
const promptInput = {
text: inputText,
files: prompt.files,
agents: prompt.agents,
}
// Keep both IDs stable until the whole create/admit sequence succeeds. If the
// transport drops after either durable write, retry reconciles that write.
const sessionID = await promptSubmission.begin(
Bun.hash(
JSON.stringify({
sessionID: props.sessionID,
session: sessionInput,
prompt: promptInput,
mode: currentMode,
}),
),
props.sessionID,
)
let sessionID = props.sessionID
let session = sessionID ? data.session.get(sessionID) : undefined
let finishMoveProgress = false
if (props.sessionID == null) {
if (sessionID == null) {
const directory = await move.getDirectory()
if (move.pending() && !directory) return false
finishMoveProgress = Boolean(move.progress())
// The location context is where the next session is created: seeded by the home
// route (launch cwd, inherited session location, or picked project) and updated
// by /cd before a session exists.
const location = currentLocation.ref ?? data.location.default()
const created = await client.api.session
.create({
id: sessionID,
...sessionInput,
location: directory ? { directory } : location,
agent: agent.id,
model: {
providerID: selectedModel.providerID,
id: selectedModel.modelID,
variant,
},
})
.catch(() => undefined)
@@ -1033,13 +986,27 @@ export function Prompt(props: PromptProps) {
return true
}
sessionID = created.id
session = created
}
const inputText = expandTrackedPastedText(
store.prompt.text,
input.extmarks.getAllForTypeId(promptPartTypeId).flatMap((extmark) => {
const ref = store.extmarkToPart.get(extmark.id)
if (ref?.type !== "pasted") return []
const part = store.prompt.pasted[ref.index]
if (!part) return []
return [{ start: extmark.start, end: extmark.end, text: part.text }]
}),
)
// Capture mode before it gets reset
const currentMode = store.mode
const editorSelection = editorContext()
const pendingEditorSelection = editorSelection && editor.labelState() === "pending" ? editorSelection : undefined
if (currentMode === "shell") {
if (store.mode === "shell") {
move.startSubmit()
void client.api.session.shell({
sessionID,
@@ -1066,9 +1033,9 @@ export function Prompt(props: PromptProps) {
command: command.slice(1),
arguments: args,
agent: agent.id,
model: sessionInput.model,
files: promptInput.files,
agents: promptInput.agents,
model: { providerID: selectedModel.providerID, id: selectedModel.modelID, variant },
files: store.prompt.files,
agents: store.prompt.agents,
})
.catch((error) => {
toast.show({ title: "Failed to run command", message: errorMessage(error), variant: "error" })
@@ -1100,7 +1067,7 @@ export function Prompt(props: PromptProps) {
) {
await client.api.session.switchModel({
sessionID,
model: sessionInput.model,
model: { providerID: selectedModel.providerID, id: selectedModel.modelID, variant },
})
}
if (session?.revert) {
@@ -1133,8 +1100,9 @@ export function Prompt(props: PromptProps) {
const error = await client.api.session
.prompt({
sessionID,
id: await promptSubmission.message(),
...promptInput,
text: inputText,
files: store.prompt.files,
agents: store.prompt.agents,
})
.then(
() => undefined,
@@ -1146,9 +1114,8 @@ export function Prompt(props: PromptProps) {
}
if (pendingEditorSelection) editor.markSelectionSent()
}
promptSubmission.complete()
history.append({
...prompt,
...store.prompt,
mode: currentMode,
})
input.extmarks.clear()
-35
View File
@@ -1,35 +0,0 @@
type PromptSubmission = {
key: number | bigint
sessionID: string
messageID?: string
}
export function createPromptSubmission() {
let pending: PromptSubmission | undefined
return {
async begin(key: number | bigint, sessionID?: string) {
if (pending?.key === key && (sessionID === undefined || pending.sessionID === sessionID)) return pending.sessionID
if (sessionID !== undefined) {
pending = { key, sessionID }
return pending.sessionID
}
const { SessionID } = await import("@opencode-ai/schema/session-id")
pending = {
key,
sessionID: SessionID.create(),
}
return pending.sessionID
},
async message() {
if (!pending) throw new Error("Prompt submission has not started")
if (pending.messageID) return pending.messageID
const { SessionMessage } = await import("@opencode-ai/schema/session-message")
pending.messageID = SessionMessage.ID.create()
return pending.messageID
},
complete() {
pending = undefined
},
}
}
-120
View File
@@ -302,123 +302,3 @@ test("session startup prompt is submitted exactly once", async () => {
mock.restore()
}
})
test("home prompt retry reuses the accepted session and message IDs", async () => {
const setup = await createTestRenderer({ width: 80, height: 24, useThread: false })
const core = await import("@opentui/core")
mock.module("@opentui/core", () => ({ ...core, createCliRenderer: async () => setup.renderer }))
const ready = Promise.withResolvers<void>()
const sessionReady = Promise.withResolvers<void>()
const setTitle = setup.renderer.setTerminalTitle.bind(setup.renderer)
setup.renderer.setTerminalTitle = (title) => {
if (title === "OpenCode") ready.resolve()
if (title === "OC | New session") sessionReady.resolve()
setTitle(title)
}
const events = createEventStream()
const cwd = process.cwd()
const location = { directory: cwd, project: { id: "project", directory: cwd } }
const creates: unknown[] = []
const prompts: unknown[] = []
const modelLoaded = Promise.withResolvers<void>()
const firstPrompt = Promise.withResolvers<void>()
const secondPrompt = Promise.withResolvers<void>()
let createdID: string | undefined
const session = (id: string) => ({
id,
title: "New session",
projectID: "project",
location: { directory: cwd },
agent: "build",
model: { providerID: "provider", id: "model" },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 0, updated: 0 },
})
const calls = createFetch(async (url, request) => {
if (url.pathname === "/api/location") return json(location)
if (url.pathname === "/api/agent")
return json({
location,
data: [{ id: "build", mode: "primary", hidden: false, permissions: [] }],
})
if (url.pathname === "/api/model") {
modelLoaded.resolve()
return json({
location,
data: [{ id: "model", providerID: "provider", name: "Model", variants: [] }],
})
}
if (url.pathname === "/api/session" && request.method === "GET")
return json({ data: createdID ? [session(createdID)] : [], cursor: {} })
if (url.pathname === "/api/session" && request.method === "POST") {
const body = await request.json()
if (!body || typeof body !== "object" || !("id" in body) || typeof body.id !== "string") {
throw new Error("session create did not supply an ID")
}
creates.push(body)
createdID = body.id
return json({ data: session(body.id) })
}
if (createdID && url.pathname === `/api/session/${createdID}`) return json({ data: session(createdID) })
if (createdID && url.pathname === `/api/session/${createdID}/message`) return json({ data: [], cursor: {} })
if (createdID && url.pathname === `/api/session/${createdID}/pending`) return json({ data: [] })
if (createdID && url.pathname === `/api/session/${createdID}/permission`) return json({ data: [] })
if (createdID && url.pathname === `/api/session/${createdID}/prompt`) {
prompts.push(await request.json())
if (prompts.length === 1) {
firstPrompt.resolve()
return json({ error: "response lost after admission" }, { status: 500 })
}
secondPrompt.resolve()
return json({ data: {} })
}
}, events)
const server = Bun.serve({ port: 0, fetch: (request) => calls.fetch(request) })
try {
const { run } = await import("../src/app")
const task = Effect.runPromise(
run({
app: { name: "test", version: "test", channel: "test" },
server: { endpoint: { url: server.url.toString() } },
config: { get: async () => ({}), update: async () => ({}) },
packages: { resolve: async () => undefined },
args: {},
log: () => {},
}).pipe(Effect.provide(AppNodeBuilder.build(Global.node)), Effect.provide(FileSystem.layerNoop({}))),
)
await Promise.all([ready.promise, modelLoaded.promise])
await setup.mockInput.typeText("RETRY_READY")
setup.mockInput.pressEnter()
await Promise.race([
firstPrompt.promise,
Bun.sleep(2_000).then(() => {
throw new Error("first home prompt was not submitted")
}),
])
await setup.waitForFrame((frame) => frame.includes("Failed to send prompt"))
setup.mockInput.pressEnter()
await Promise.race([
secondPrompt.promise,
Bun.sleep(2_000).then(() => {
throw new Error("home prompt was not retried")
}),
])
await sessionReady.promise
setup.renderer.destroy()
await task
expect(creates).toHaveLength(2)
expect(prompts).toHaveLength(2)
expect(creates[1]).toEqual(creates[0])
expect(prompts[1]).toEqual(prompts[0])
expect(creates[0]).toMatchObject({ id: expect.stringMatching(/^ses_/) })
expect(prompts[0]).toMatchObject({ id: expect.stringMatching(/^msg_/), text: "RETRY_READY" })
} finally {
if (!setup.renderer.isDestroyed) setup.renderer.destroy()
await server.stop()
mock.restore()
}
})
@@ -1,32 +0,0 @@
import { describe, expect, test } from "bun:test"
import { Session } from "@opencode-ai/schema/session"
import { createPromptSubmission } from "../../src/prompt/submission"
describe("prompt submission identity", () => {
test("reuses identities while retrying the same submission", async () => {
const submission = createPromptSubmission()
const firstSession = await submission.begin(1n)
const firstMessage = await submission.message()
expect(await submission.begin(1n)).toBe(firstSession)
expect(await submission.message()).toBe(firstMessage)
expect(await submission.begin(2n)).not.toBe(firstSession)
expect(await submission.message()).not.toBe(firstMessage)
})
test("preserves an existing session while retrying its prompt", async () => {
const submission = createPromptSubmission()
const sessionID = Session.ID.create()
expect(await submission.begin(1n, sessionID)).toBe(sessionID)
expect(await submission.begin(1n, sessionID)).toBe(sessionID)
})
test("starts a new identity after completion", async () => {
const submission = createPromptSubmission()
const first = await submission.begin(1n)
submission.complete()
expect(await submission.begin(1n)).not.toBe(first)
})
})