Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion packages/opencode/src/session/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1870,7 +1870,11 @@ const layer = Layer.effect(
}
if ((part.type === "text" || part.type === "reasoning") && part.time?.end === undefined) {
yield* sessions
.updatePart({ ...part, time: { start: part.time?.start ?? now, end: now } } as SessionV1.Part)
.updatePart({
...part,
recovery: "orphaned",
time: { start: part.time?.start ?? now, end: now },
} as SessionV1.Part)
.pipe(Effect.catch((error) => Effect.logWarning("failed to settle orphaned text part", { error })))
}
}
Expand Down
60 changes: 60 additions & 0 deletions packages/opencode/test/session/processor-effect.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { SessionV1 } from "@opencode-ai/core/v1/session"
import { applyPartDelta, applyPartUpdated } from "../../../tui/src/util/part"
import type { Part } from "@opencode-ai/sdk/v2"
import { pathToFileURL } from "url"
import { PermissionV1 } from "@opencode-ai/core/v1/permission"
import { Database } from "@opencode-ai/core/database/database"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
Expand Down Expand Up @@ -1246,6 +1249,63 @@ const runProcessor = Effect.fn("test.runProcessor")(function* (dir: string, text
return { value, handle, stored }
})


it.live("text-complete plugins can truncate or delete streamed text", () =>
provideTmpdirServer(
({ dir, llm }) =>
Effect.gen(function* () {
const file = path.join(dir, "rewrite-plugin.ts")
yield* Effect.promise(() =>
Bun.write(
file,
`export default async () => ({
"experimental.text.complete": async (_input, output) => {
output.text = output.text.endsWith("prefix") ? "Hello" : ""
},
})`,
),
)
yield* Effect.promise(() =>
Bun.write(
path.join(dir, "opencode.json"),
JSON.stringify({
...providerCfg(llm.url),
plugin: [pathToFileURL(file).href],
}),
),
)
const events = yield* EventV2Bridge.Service
const seen = new Map<string, Part[]>()
const off = yield* events.listen((event) => {
if (event.type === MessageV2.Event.PartUpdated.type) {
const data = event.data as typeof MessageV2.Event.PartUpdated.data.Type
seen.set(data.part.messageID, applyPartUpdated(seen.get(data.part.messageID), data.part as Part))
}
if (event.type === MessageV2.Event.PartDelta.type) {
const data = event.data as typeof MessageV2.Event.PartDelta.data.Type
const parts = applyPartDelta(seen.get(data.messageID), data.partID, data.field, data.delta)
if (parts) seen.set(data.messageID, parts)
}
return Effect.void
})
for (const [input, expected] of [
["Hello secret prefix", "Hello"],
["Hello secret deletion", ""],
]) {
yield* llm.text(input)
const result = yield* runProcessor(dir, "hi")
const stored = result.stored.parts.find((part) => part.type === "text")
expect(stored).toMatchObject({ text: expected, time: { end: expect.any(Number) } })
expect(seen.get(result.stored.info.id)?.find((part) => part.type === "text")).toMatchObject({
text: expected,
})
}
yield* off
}),
{ config: (url) => providerCfg(url) },
),
)

const itStreamingMetrics = processorWithLLM(() =>
delayedEvents([
[0, LLMEvent.stepStart({ index: 0 })],
Expand Down
82 changes: 81 additions & 1 deletion packages/opencode/test/session/prompt.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { ToolCatalog } from "@/tool/catalog"
import { applyPartDelta, applyPartUpdated } from "../../../tui/src/util/part"
import type { Part } from "@opencode-ai/sdk/v2"
import { ConfigV1 } from "@opencode-ai/core/v1/config/config"
import { SessionV1 } from "@opencode-ai/core/v1/session"
import { Database } from "@opencode-ai/core/database/database"
Expand All @@ -7,7 +9,7 @@ import { SessionProjector } from "@opencode-ai/core/session/projector"
import { eq } from "drizzle-orm"
import { EventV2Bridge } from "@/event-v2-bridge"
import { expect } from "bun:test"
import { Cause, Deferred, Duration, Effect, Exit, Fiber, Layer } from "effect"
import { Cause, Deferred, Duration, Effect, Exit, Fiber, Layer, Schema } from "effect"
import path from "path"
import { fileURLToPath } from "url"
import { readdir, readFile } from "node:fs/promises"
Expand Down Expand Up @@ -2019,6 +2021,84 @@ noLLMServer.instance(
{ config: { ...cfg, agent: { work: { finishTool: true } } } },
)

it.instance("settling durable orphans preserves streamed text in a live consumer", () =>
Effect.gen(function* () {
const { llm } = yield* useServerConfig(providerCfg)
const events = yield* EventV2Bridge.Service
const prompt = yield* SessionPrompt.Service
const sessions = yield* Session.Service
const chat = yield* sessions.create({ title: "Pinned" })
const seeded = yield* seed(chat.id, { finish: "tool-calls" })
let parts: Part[] | undefined
const off = yield* events.listen((event) => {
if (event.type === MessageV2.Event.PartUpdated.type) {
const data = event.data as typeof MessageV2.Event.PartUpdated.data.Type
if (data.part.messageID === seeded.assistant.id) parts = applyPartUpdated(parts, data.part as Part)
}
if (event.type === MessageV2.Event.PartDelta.type) {
const data = event.data as typeof MessageV2.Event.PartDelta.data.Type
if (data.messageID === seeded.assistant.id) parts = applyPartDelta(parts, data.partID, data.field, data.delta)
}
return Effect.void
})
const cases = (["text", "reasoning"] as const).flatMap((type) =>
["", "streamed "].map((durable) => ({ type, durable, id: PartID.ascending() })),
)
for (const item of cases) {
yield* sessions.updatePart({
id: item.id,
sessionID: chat.id,
messageID: seeded.assistant.id,
type: item.type,
text: item.durable,
time: { start: 1 },
metadata: { source: "provider" },
})
yield* sessions.updatePartDelta({
sessionID: chat.id,
messageID: seeded.assistant.id,
partID: item.id,
field: "text",
delta: item.durable ? item.type : `streamed ${item.type}`,
})
}
const before = yield* sessions.messages({ sessionID: chat.id })
const durable = before.find((msg) => msg.info.id === seeded.assistant.id)!
expect(
durable.parts
.filter((part) => cases.some((item) => item.id === part.id))
.map((part) => ("text" in part ? part.text : null)),
).toEqual(cases.map((item) => item.durable))
const identities = parts!.slice()
yield* llm.text("recovered")
yield* prompt.loop({ sessionID: chat.id })
yield* off
const after = yield* sessions.messages({ sessionID: chat.id })
const stored = after.find((msg) => msg.info.id === seeded.assistant.id)!
// Exercise the public schema's JSON encoding and decoding, not just the DB row.
const encoded = Schema.encodeSync(SessionV1.WithParts)(stored)
const decoded = Schema.decodeUnknownSync(SessionV1.WithParts)(JSON.parse(JSON.stringify(encoded)))
for (const [index, item] of cases.entries()) {
const current = parts!.find((part) => part.id === item.id)!
expect(current).toBe(identities[index])
expect(current).toMatchObject({
id: item.id,
type: item.type,
text: `streamed ${item.type}`,
time: { start: 1, end: expect.any(Number) },
recovery: "orphaned",
metadata: { source: "provider" },
})
expect(decoded.parts.find((part) => part.id === item.id)).toMatchObject({
text: item.durable,
recovery: "orphaned",
metadata: { source: "provider" },
time: { start: 1, end: expect.any(Number) },
})
}
}),
)

it.instance(
"run exit settles crash-orphaned running parts",
() =>
Expand Down
3 changes: 3 additions & 0 deletions packages/schema/src/v1/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ export const TextPart = Schema.Struct({
...partBase,
type: Schema.Literal("text"),
text: Schema.String,
// Orphan settlement closes a durable snapshot that may lag published deltas.
recovery: optional(Schema.Literal("orphaned")),
synthetic: Schema.optional(Schema.Boolean),
ignored: Schema.optional(Schema.Boolean),
time: Schema.optional(
Expand Down Expand Up @@ -148,6 +150,7 @@ export const ReasoningPart = Schema.Struct({
...partBase,
type: Schema.Literal("reasoning"),
text: Schema.String,
recovery: optional(Schema.Literal("orphaned")),
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)),
time: Schema.Struct({
start: NonNegativeInt,
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/js/src/v2/gen/types.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ export type TextPart = {
messageID: string
type: "text"
text: string
recovery?: "orphaned"
synthetic?: boolean
ignored?: boolean
time?: {
Expand Down Expand Up @@ -417,6 +418,7 @@ export type ReasoningPart = {
messageID: string
type: "reasoning"
text: string
recovery?: "orphaned"
metadata?: {
[key: string]: unknown
}
Expand Down
12 changes: 3 additions & 9 deletions packages/tui/src/context/sync.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import { batch, onMount } from "solid-js"
import path from "path"
import { useKV } from "./kv"
import { usePermission } from "./permission"
import { applyPartDelta, applyPartUpdated } from "../util/part"
import { applyPartDelta, applyPartUpdated, mergePartInPlace, mergePartText } from "../util/part"

const emptyConsoleState: ConsoleState = {
consoleManagedProviders: [],
Expand Down Expand Up @@ -645,14 +645,8 @@ export const {
const parts = message.parts.flatMap((part) => {
const current = currentParts.find((item) => item.id === part.id)
if (tracker.parts.has(part.id)) return current ? [current] : []
if (
current &&
(part.type === "text" || part.type === "reasoning") &&
(current.type === "text" || current.type === "reasoning") &&
part.text.length === 0 &&
current.text.length > 0
) {
return [current]
if (current && part.type === current.type && (part.type === "text" || part.type === "reasoning")) {
return [mergePartInPlace(current, mergePartText(current, part))]
}
return [part]
})
Expand Down
37 changes: 25 additions & 12 deletions packages/tui/src/util/part.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import type { Part, TextPart, ReasoningPart, ToolState } from "@opencode-ai/sdk/v2"

// This reconciler is coupled to the event-ordering guarantees produced by
// `packages/opencode/src/session/processor.ts` (append-only deltas, a single
// non-cumulative text write at `text-end`, one terminal tool transition,
// immutable `time.start`). There is no revision/sequence number on the wire,
// so those guarantees are the only source of causality. If the processor
// changes them (e.g. adds per-part revisions, re-publishes terminal rows, or
// introduces a new non-cumulative write), this reconciler must be updated and
// its invariants re-tested.
// Reconciliation relies on append-only deltas and the processor's terminal
// text-end rewrite, as well as prompt-loop orphan settlement, which publishes
// terminal snapshots from durable rows that may not include streamed deltas.
// There is no sequence number; changes to these publishers require retesting.

type PartTime = { start: number; end?: number }

Expand Down Expand Up @@ -41,11 +37,13 @@ function isTextLike(part: Part): part is TextPart | ReasoningPart {
// already rendered is older — keep the longer streamed text, except for
// the first terminal text snapshot described below;
// - a snapshot that extends the rendered text accumulated more deltas — adopt;
// - the only legitimate non-cumulative text write is the `text-end` snapshot
// - the legitimate non-cumulative text write is the `text-end` snapshot
// (the `experimental.text.complete` plugin rewrites the final text) and it
// is published together with `time.end`; adopt it even if it is a prefix or
// empty. Reasoning snapshots retain the existing prefix behavior;
// - a part reaches its terminal snapshot exactly once, so once `time.end` is
// empty. Orphan settlement instead marks a potentially incomplete durable
// snapshot; keep local content unless that snapshot extends it. Reasoning
// snapshots retain the existing prefix behavior;
// - after the first observed terminal snapshot, once `time.end` is
// set the part is a sink: a replayed row without `time.end` — even one that
// "extends" the final text — is older and must not reopen the part, and a
// second terminal row with different text cannot be causally newer either;
Expand All @@ -67,6 +65,12 @@ export function mergePartText(current: Part | undefined, incoming: Part): Part {
return { ...incoming, text: currentText }
}

// Settlement never observed the lost stream buffer; it cannot authorize a
// truncation or conflicting rewrite. A newer cumulative extension is safe.
if (incomingTerminal && incoming.recovery === "orphaned") {
return incomingText.startsWith(currentText) ? incoming : { ...incoming, text: currentText }
}

// text-end may rewrite text to a strict prefix or even an empty string.
// Reasoning has no corresponding plugin rewrite and keeps prefix protection.
if (current.type === "text" && incoming.type === "text" && incomingTerminal) return incoming
Expand Down Expand Up @@ -213,6 +217,12 @@ export function mergePartInPlace(target: Part, source: Part): Part {

if (isTextLike(target) && isTextLike(source)) {
target.text = source.text
// Provenance belongs to the first terminal snapshot, not to an earlier
// row or a later replay. In particular it cannot leak into text-end.
if (target.time?.end === undefined && source.time?.end !== undefined) {
if (source.recovery === "orphaned") target.recovery = source.recovery
else delete target.recovery
}
}
if (target.type === "tool" && source.type === "tool") {
target.state = mergeToolState(target.state, source.state)
Expand All @@ -228,6 +238,7 @@ export function mergePartInPlace(target: Part, source: Part): Part {
for (const key of Object.keys(incoming)) {
if (key === "type" || key === "id" || key === "sessionID" || key === "messageID") continue
if (key === "text" || key === "state" || key === "time") continue
if (key === "recovery" && isTextLike(target) && isTextLike(source)) continue
destination[key] = incoming[key]
}
return target
Expand Down Expand Up @@ -267,7 +278,9 @@ export function applyPartDelta(
if (!parts) return undefined
const result = searchPart(parts, partID)
if (!result.found) return undefined
const part = parts[result.index] as Record<string, unknown>
const found = parts[result.index]
if (isTextLike(found) && found.time?.end !== undefined && field === "text") return parts
const part = found as Record<string, unknown>
const current = part[field]
if (current !== undefined && typeof current !== "string") return parts
part[field] = ((current as string | undefined) ?? "") + delta
Expand Down
Loading
Loading