mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
perf(core): project assistant message parts into session_part rows
This commit is contained in:
parent
e09af4cc33
commit
de7dde7d98
9 changed files with 811 additions and 213 deletions
|
|
@ -12,6 +12,23 @@ export interface Adapter {
|
|||
readonly getShell: (shellID: SessionMessage.Shell["shellID"]) => Effect.Effect<SessionMessage.Shell | undefined>
|
||||
readonly getCompaction: () => Effect.Effect<SessionMessage.Compaction | undefined>
|
||||
readonly updateAssistant: (assistant: SessionMessage.Assistant) => Effect.Effect<void>
|
||||
readonly appendAssistantPart: (
|
||||
messageID: SessionMessage.ID,
|
||||
part: SessionMessage.AssistantContent,
|
||||
) => Effect.Effect<void>
|
||||
readonly updateAssistantPart: <T extends SessionMessage.AssistantContent["type"]>(
|
||||
messageID: SessionMessage.ID,
|
||||
match: {
|
||||
readonly type: T
|
||||
readonly callID?: string
|
||||
readonly incompleteReasoning?: boolean
|
||||
},
|
||||
recipe: (draft: WritableDraft<Extract<SessionMessage.AssistantContent, { readonly type: T }>>) => void,
|
||||
) => Effect.Effect<void>
|
||||
readonly replaceAssistantParts: (
|
||||
messageID: SessionMessage.ID,
|
||||
parts: ReadonlyArray<SessionMessage.AssistantContent>,
|
||||
) => Effect.Effect<void>
|
||||
readonly updateShell: (shell: SessionMessage.Shell) => Effect.Effect<void>
|
||||
readonly updateCompaction: (compaction: SessionMessage.Compaction) => Effect.Effect<void>
|
||||
readonly appendMessage: (message: SessionMessage.Info) => Effect.Effect<void>
|
||||
|
|
@ -31,20 +48,8 @@ const projectTerminalSnapshot = (draft: DraftAssistant, event: SessionEvent.Step
|
|||
}
|
||||
|
||||
export function update(adapter: Adapter, event: SessionEvent.DurableEvent) {
|
||||
type DraftTool = WritableDraft<SessionMessage.AssistantTool>
|
||||
type DraftText = WritableDraft<SessionMessage.AssistantText>
|
||||
type DraftReasoning = WritableDraft<SessionMessage.AssistantReasoning>
|
||||
const created = DateTime.makeUnsafe(event.created)
|
||||
|
||||
const latestTool = (assistant: DraftAssistant, id: string) =>
|
||||
assistant.content.findLast((item): item is DraftTool => item.type === "tool" && item.id === id)
|
||||
|
||||
const latestText = (assistant: DraftAssistant) =>
|
||||
assistant.content.findLast((item): item is DraftText => item.type === "text")
|
||||
|
||||
const latestReasoning = (assistant: DraftAssistant) =>
|
||||
assistant.content.findLast((item): item is DraftReasoning => item.type === "reasoning" && !item.time?.completed)
|
||||
|
||||
const updateOwnedAssistant = (messageID: SessionMessage.ID, recipe: (draft: DraftAssistant) => void) =>
|
||||
Effect.gen(function* () {
|
||||
const assistant = yield* adapter.getAssistant(messageID)
|
||||
|
|
@ -86,9 +91,7 @@ export function update(adapter: Adapter, event: SessionEvent.DurableEvent) {
|
|||
"session.archived": () => Effect.void,
|
||||
"session.unarchived": () => Effect.void,
|
||||
"session.message.content.updated": (event) =>
|
||||
updateOwnedAssistant(event.data.messageID, (draft) => {
|
||||
draft.content = castDraft(decodeAssistantContent(event.data.content))
|
||||
}),
|
||||
adapter.replaceAssistantParts(event.data.messageID, decodeAssistantContent(event.data.content)),
|
||||
"session.usage.recorded": () => Effect.void,
|
||||
"session.agent.selected": (event) =>
|
||||
Effect.gen(function* () {
|
||||
|
|
@ -289,44 +292,43 @@ export function update(adapter: Adapter, event: SessionEvent.DurableEvent) {
|
|||
})
|
||||
},
|
||||
"session.text.started": (event) => {
|
||||
return updateOwnedAssistant(event.data.assistantMessageID, (draft) => {
|
||||
draft.content.push(castDraft(SessionMessage.AssistantText.make({ type: "text", text: "" })))
|
||||
})
|
||||
return adapter.appendAssistantPart(
|
||||
event.data.assistantMessageID,
|
||||
SessionMessage.AssistantText.make({ type: "text", text: "" }),
|
||||
)
|
||||
},
|
||||
"session.text.ended": (event) => {
|
||||
return updateOwnedAssistant(event.data.assistantMessageID, (draft) => {
|
||||
const match = latestText(draft)
|
||||
if (match) {
|
||||
match.text = event.data.text
|
||||
match.native = castDraft(event.data.native)
|
||||
}
|
||||
return adapter.updateAssistantPart(event.data.assistantMessageID, { type: "text" }, (match) => {
|
||||
match.text = event.data.text
|
||||
match.native = castDraft(event.data.native)
|
||||
})
|
||||
},
|
||||
"session.tool.input.started": (event) => {
|
||||
return updateOwnedAssistant(event.data.assistantMessageID, (draft) => {
|
||||
draft.content.push(
|
||||
castDraft(
|
||||
SessionMessage.AssistantTool.make({
|
||||
type: "tool",
|
||||
id: event.data.id,
|
||||
name: event.data.name,
|
||||
time: { created },
|
||||
state: SessionMessage.ToolStateStreaming.make({ status: "streaming", input: "" }),
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
return adapter.appendAssistantPart(
|
||||
event.data.assistantMessageID,
|
||||
SessionMessage.AssistantTool.make({
|
||||
type: "tool",
|
||||
id: event.data.id,
|
||||
name: event.data.name,
|
||||
time: { created },
|
||||
state: SessionMessage.ToolStateStreaming.make({ status: "streaming", input: "" }),
|
||||
}),
|
||||
)
|
||||
},
|
||||
"session.tool.input.ended": (event) => {
|
||||
return updateOwnedAssistant(event.data.assistantMessageID, (draft) => {
|
||||
const match = latestTool(draft, event.data.id)
|
||||
if (match && match.state.status === "streaming") match.state.input = event.data.text
|
||||
})
|
||||
return adapter.updateAssistantPart(
|
||||
event.data.assistantMessageID,
|
||||
{ type: "tool", callID: event.data.id },
|
||||
(match) => {
|
||||
if (match.state.status === "streaming") match.state.input = event.data.text
|
||||
},
|
||||
)
|
||||
},
|
||||
"session.tool.called": (event) => {
|
||||
return updateOwnedAssistant(event.data.assistantMessageID, (draft) => {
|
||||
const match = latestTool(draft, event.data.id)
|
||||
if (match) {
|
||||
return adapter.updateAssistantPart(
|
||||
event.data.assistantMessageID,
|
||||
{ type: "tool", callID: event.data.id },
|
||||
(match) => {
|
||||
match.executed = event.data.executed
|
||||
match.native = event.data.native
|
||||
match.time.ran = created
|
||||
|
|
@ -337,71 +339,75 @@ export function update(adapter: Adapter, event: SessionEvent.DurableEvent) {
|
|||
metadata: {},
|
||||
}),
|
||||
)
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
},
|
||||
// Terminal tool events are self-contained; projection is a direct copy and
|
||||
// never reaches into ephemeral progress history.
|
||||
"session.tool.success": (event) => {
|
||||
return updateOwnedAssistant(event.data.assistantMessageID, (draft) => {
|
||||
const match = latestTool(draft, event.data.id)
|
||||
if (match && match.state.status === "running") {
|
||||
match.executed = event.data.executed || match.executed === true
|
||||
if (event.data.native) match.native = { ...match.native, ...event.data.native }
|
||||
match.time.completed = created
|
||||
match.state = castDraft(
|
||||
SessionMessage.ToolStateCompleted.make({
|
||||
status: "completed",
|
||||
input: match.state.input,
|
||||
content: event.data.content,
|
||||
...(event.data.metadata === undefined ? {} : { metadata: event.data.metadata }),
|
||||
}),
|
||||
)
|
||||
}
|
||||
})
|
||||
return adapter.updateAssistantPart(
|
||||
event.data.assistantMessageID,
|
||||
{ type: "tool", callID: event.data.id },
|
||||
(match) => {
|
||||
if (match.state.status === "running") {
|
||||
match.executed = event.data.executed || match.executed === true
|
||||
if (event.data.native) match.native = { ...match.native, ...event.data.native }
|
||||
match.time.completed = created
|
||||
match.state = castDraft(
|
||||
SessionMessage.ToolStateCompleted.make({
|
||||
status: "completed",
|
||||
input: match.state.input,
|
||||
content: event.data.content,
|
||||
...(event.data.metadata === undefined ? {} : { metadata: event.data.metadata }),
|
||||
}),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
"session.tool.failed": (event) => {
|
||||
return updateOwnedAssistant(event.data.assistantMessageID, (draft) => {
|
||||
const match = latestTool(draft, event.data.id)
|
||||
if (match && (match.state.status === "streaming" || match.state.status === "running")) {
|
||||
match.executed = event.data.executed || match.executed === true
|
||||
if (event.data.native) match.native = { ...match.native, ...event.data.native }
|
||||
match.time.completed = created
|
||||
match.state = castDraft(
|
||||
SessionMessage.ToolStateError.make({
|
||||
status: "error",
|
||||
error: event.data.error,
|
||||
input: typeof match.state.input === "string" ? {} : match.state.input,
|
||||
...(event.data.content === undefined ? {} : { content: event.data.content }),
|
||||
...(event.data.metadata === undefined ? {} : { metadata: event.data.metadata }),
|
||||
}),
|
||||
)
|
||||
}
|
||||
})
|
||||
return adapter.updateAssistantPart(
|
||||
event.data.assistantMessageID,
|
||||
{ type: "tool", callID: event.data.id },
|
||||
(match) => {
|
||||
if (match.state.status === "streaming" || match.state.status === "running") {
|
||||
match.executed = event.data.executed || match.executed === true
|
||||
if (event.data.native) match.native = { ...match.native, ...event.data.native }
|
||||
match.time.completed = created
|
||||
match.state = castDraft(
|
||||
SessionMessage.ToolStateError.make({
|
||||
status: "error",
|
||||
error: event.data.error,
|
||||
input: typeof match.state.input === "string" ? {} : match.state.input,
|
||||
...(event.data.content === undefined ? {} : { content: event.data.content }),
|
||||
...(event.data.metadata === undefined ? {} : { metadata: event.data.metadata }),
|
||||
}),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
"session.reasoning.started": (event) => {
|
||||
return updateOwnedAssistant(event.data.assistantMessageID, (draft) => {
|
||||
draft.content.push(
|
||||
castDraft(
|
||||
SessionMessage.AssistantReasoning.make({
|
||||
type: "reasoning",
|
||||
text: "",
|
||||
native: event.data.native,
|
||||
time: { created },
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
return adapter.appendAssistantPart(
|
||||
event.data.assistantMessageID,
|
||||
SessionMessage.AssistantReasoning.make({
|
||||
type: "reasoning",
|
||||
text: "",
|
||||
native: event.data.native,
|
||||
time: { created },
|
||||
}),
|
||||
)
|
||||
},
|
||||
"session.reasoning.ended": (event) => {
|
||||
return updateOwnedAssistant(event.data.assistantMessageID, (draft) => {
|
||||
const match = latestReasoning(draft)
|
||||
if (match) {
|
||||
return adapter.updateAssistantPart(
|
||||
event.data.assistantMessageID,
|
||||
{ type: "reasoning", incompleteReasoning: true },
|
||||
(match) => {
|
||||
match.text = event.data.text
|
||||
match.time = { created: match.time?.created ?? created, completed: created }
|
||||
if (event.data.native !== undefined) match.native = event.data.native
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
},
|
||||
"session.retry.scheduled": (event) => {
|
||||
return updateOwnedAssistant(event.data.assistantMessageID, (draft) => {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
export * as SessionProjector from "./projector.js"
|
||||
|
||||
import { produce } from "immer"
|
||||
import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, or, sql } from "drizzle-orm"
|
||||
import { DateTime, Effect, Layer, Schema, Stream } from "effect"
|
||||
import path from "path"
|
||||
|
|
@ -12,7 +13,7 @@ import { SessionMessage } from "./message.js"
|
|||
import { SessionMessageUpdater } from "./message-updater.js"
|
||||
import { SessionInbox } from "./inbox.js"
|
||||
import { InstructionState } from "./instruction-state.js"
|
||||
import { SessionInboxTable, SessionMessageTable, SessionTable } from "./sql.js"
|
||||
import { SessionInboxTable, SessionMessageTable, SessionPartTable, SessionTable } from "./sql.js"
|
||||
import { InstructionEntry } from "./instruction-entry.js"
|
||||
import { Slug } from "../util/slug.js"
|
||||
import { FSUtil } from "@opencode/util/fs-util"
|
||||
|
|
@ -215,7 +216,10 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* (
|
|||
seq: row.seq,
|
||||
time_created: row.time_created,
|
||||
time_updated: row.time_updated,
|
||||
data: row.data,
|
||||
data:
|
||||
row.type === "assistant" && SessionHistory.hasInlineContent(row.data)
|
||||
? { ...row.data, content: [] }
|
||||
: row.data,
|
||||
}
|
||||
// A summary references the first message it kept, which the fork copied under a new ID.
|
||||
const keepID = row.type === "compaction" ? row.data.metadata?.keepID : undefined
|
||||
|
|
@ -235,6 +239,61 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* (
|
|||
)
|
||||
yield* db.insert(SessionMessageTable).values(values).run().pipe(Effect.orDie)
|
||||
|
||||
const assistantRows = rows.filter((row) => row.type === "assistant")
|
||||
if (assistantRows.length > 0) {
|
||||
const idMap = new Map(assistantRows.map((row) => [row.id, forkedID(row.seq)]))
|
||||
const storedParts = yield* db
|
||||
.select()
|
||||
.from(SessionPartTable)
|
||||
.where(
|
||||
and(
|
||||
eq(SessionPartTable.session_id, event.data.parentID),
|
||||
inArray(
|
||||
SessionPartTable.message_id,
|
||||
assistantRows.map((row) => row.id),
|
||||
),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(SessionPartTable.message_id), asc(SessionPartTable.ordinal))
|
||||
.all()
|
||||
.pipe(Effect.orDie)
|
||||
const splitParentIDs = new Set(storedParts.map((part) => part.message_id))
|
||||
const partValues: Array<typeof SessionPartTable.$inferInsert> = storedParts.map((part) => ({
|
||||
message_id: idMap.get(part.message_id)!,
|
||||
session_id: event.data.sessionID,
|
||||
ordinal: part.ordinal,
|
||||
type: part.type,
|
||||
call_id: part.call_id,
|
||||
time_created: part.time_created,
|
||||
time_updated: part.time_updated,
|
||||
data: part.data,
|
||||
}))
|
||||
for (const row of assistantRows) {
|
||||
if (splitParentIDs.has(row.id) || !SessionHistory.hasInlineContent(row.data)) continue
|
||||
const decoded = SessionHistory.decodeMessageRowSync(row)
|
||||
if (decoded.type !== "assistant") continue
|
||||
decoded.content.forEach((part, ordinal) => {
|
||||
partValues.push({
|
||||
message_id: idMap.get(row.id)!,
|
||||
session_id: event.data.sessionID,
|
||||
ordinal,
|
||||
type: part.type,
|
||||
call_id: part.type === "tool" ? part.id : null,
|
||||
time_created: row.time_created,
|
||||
time_updated: row.time_updated,
|
||||
data: SessionHistory.encodePart(part),
|
||||
})
|
||||
})
|
||||
}
|
||||
for (let index = 0; index < partValues.length; index += ForkBatchSize) {
|
||||
yield* db
|
||||
.insert(SessionPartTable)
|
||||
.values(partValues.slice(index, index + ForkBatchSize))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
}
|
||||
}
|
||||
|
||||
cursor = rows.at(-1)!.seq
|
||||
}
|
||||
if (copiedSeq !== undefined) yield* Bus.reserveSequence(db, event.data.sessionID, copiedSeq)
|
||||
|
|
@ -244,12 +303,79 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* (
|
|||
|
||||
function run(db: DatabaseService, event: MessageEvent) {
|
||||
return Effect.gen(function* () {
|
||||
const splitLegacyAssistantRow = Effect.fnUntraced(function* (row: typeof SessionMessageTable.$inferSelect) {
|
||||
const message = SessionHistory.decodeMessageRowSync(row)
|
||||
if (message.type !== "assistant") return undefined
|
||||
if (!SessionHistory.hasInlineContent(row.data)) return message
|
||||
const partRows = message.content.map((part, ordinal) => ({
|
||||
message_id: message.id,
|
||||
session_id: row.session_id,
|
||||
ordinal,
|
||||
type: part.type,
|
||||
call_id: part.type === "tool" ? part.id : null,
|
||||
time_created: row.time_created,
|
||||
time_updated: event.created,
|
||||
data: SessionHistory.encodePart(part),
|
||||
}))
|
||||
yield* db.delete(SessionPartTable).where(eq(SessionPartTable.message_id, message.id)).run().pipe(Effect.orDie)
|
||||
for (let index = 0; index < partRows.length; index += ForkBatchSize) {
|
||||
yield* db
|
||||
.insert(SessionPartTable)
|
||||
.values(partRows.slice(index, index + ForkBatchSize))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
}
|
||||
const envelope: SessionMessage.Assistant = { ...message, content: [] }
|
||||
const { id: _, type: __, ...data } = encodeMessage(envelope)
|
||||
yield* db
|
||||
.update(SessionMessageTable)
|
||||
.set({ data })
|
||||
.where(and(eq(SessionMessageTable.id, message.id), eq(SessionMessageTable.session_id, row.session_id)))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
return envelope
|
||||
})
|
||||
const ensureAssistantPartsSplit = Effect.fnUntraced(function* (messageID: SessionMessage.ID) {
|
||||
const row = yield* db
|
||||
.select({
|
||||
id: SessionMessageTable.id,
|
||||
inlineCount: sql<number>`json_array_length(${SessionMessageTable.data}, '$.content')`,
|
||||
})
|
||||
.from(SessionMessageTable)
|
||||
.where(
|
||||
and(
|
||||
eq(SessionMessageTable.id, messageID),
|
||||
eq(SessionMessageTable.session_id, event.data.sessionID),
|
||||
eq(SessionMessageTable.type, "assistant"),
|
||||
),
|
||||
)
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
if (!row) return false
|
||||
if (row.inlineCount > 0) {
|
||||
const full = yield* db
|
||||
.select()
|
||||
.from(SessionMessageTable)
|
||||
.where(eq(SessionMessageTable.id, messageID))
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
if (full) yield* splitLegacyAssistantRow(full)
|
||||
}
|
||||
return true
|
||||
})
|
||||
const updateMessage = (message: SessionMessage.Info) => {
|
||||
const encoded = encodeMessage(message)
|
||||
const { id: _, type, ...data } = encoded
|
||||
const encoded = encodeMessage(
|
||||
message.type === "assistant" && message.content.length > 0 ? { ...message, content: [] } : message,
|
||||
)
|
||||
const { id: _, type: __, ...data } = encoded
|
||||
return db
|
||||
.update(SessionMessageTable)
|
||||
.set({ type, time_created: DateTime.toEpochMillis(message.time.created), data })
|
||||
.set({
|
||||
...(event.type === SessionEvent.Step.Started.type
|
||||
? { time_created: DateTime.toEpochMillis(message.time.created) }
|
||||
: {}),
|
||||
data,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(SessionMessageTable.id, message.id),
|
||||
|
|
@ -324,8 +450,8 @@ function run(db: DatabaseService, event: MessageEvent) {
|
|||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
if (!row) return
|
||||
const message = SessionHistory.decodeMessageRowSync(row)
|
||||
return message.type === "assistant" && !message.time.completed ? message : undefined
|
||||
const message = yield* splitLegacyAssistantRow(row)
|
||||
return message && !message.time.completed ? message : undefined
|
||||
})
|
||||
},
|
||||
getAssistant(messageID) {
|
||||
|
|
@ -343,8 +469,121 @@ function run(db: DatabaseService, event: MessageEvent) {
|
|||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
if (!row) return
|
||||
const message = SessionHistory.decodeMessageRowSync(row)
|
||||
return message.type === "assistant" ? message : undefined
|
||||
return yield* splitLegacyAssistantRow(row)
|
||||
})
|
||||
},
|
||||
appendAssistantPart(messageID, part) {
|
||||
return Effect.gen(function* () {
|
||||
if (!(yield* ensureAssistantPartsSplit(messageID))) return
|
||||
const next = yield* db
|
||||
.select({ ordinal: sql<number>`coalesce(max(${SessionPartTable.ordinal}) + 1, 0)` })
|
||||
.from(SessionPartTable)
|
||||
.where(eq(SessionPartTable.message_id, messageID))
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
yield* db
|
||||
.insert(SessionPartTable)
|
||||
.values({
|
||||
message_id: messageID,
|
||||
session_id: event.data.sessionID,
|
||||
ordinal: next?.ordinal ?? 0,
|
||||
type: part.type,
|
||||
call_id: part.type === "tool" ? part.id : null,
|
||||
time_created: event.created,
|
||||
time_updated: event.created,
|
||||
data: SessionHistory.encodePart(part),
|
||||
})
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
})
|
||||
},
|
||||
updateAssistantPart(messageID, match, recipe) {
|
||||
return Effect.gen(function* () {
|
||||
if (!(yield* ensureAssistantPartsSplit(messageID))) return
|
||||
const row = yield* db
|
||||
.select()
|
||||
.from(SessionPartTable)
|
||||
.where(
|
||||
and(
|
||||
eq(SessionPartTable.message_id, messageID),
|
||||
eq(SessionPartTable.session_id, event.data.sessionID),
|
||||
eq(SessionPartTable.type, match.type),
|
||||
match.callID !== undefined ? eq(SessionPartTable.call_id, match.callID) : undefined,
|
||||
match.incompleteReasoning
|
||||
? sql`json_extract(${SessionPartTable.data}, '$.time.completed') is null`
|
||||
: undefined,
|
||||
),
|
||||
)
|
||||
.orderBy(desc(SessionPartTable.ordinal))
|
||||
.limit(1)
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
if (!row) return
|
||||
|
||||
const current = SessionHistory.decodePartRowSync(row) as Extract<
|
||||
SessionMessage.AssistantContent,
|
||||
{ readonly type: typeof match.type }
|
||||
>
|
||||
const updated = produce(current, recipe)
|
||||
if (updated === current) return
|
||||
yield* db
|
||||
.update(SessionPartTable)
|
||||
.set({ data: SessionHistory.encodePart(updated), time_updated: event.created })
|
||||
.where(
|
||||
and(
|
||||
eq(SessionPartTable.message_id, messageID),
|
||||
eq(SessionPartTable.ordinal, row.ordinal),
|
||||
),
|
||||
)
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
})
|
||||
},
|
||||
replaceAssistantParts(messageID, parts) {
|
||||
return Effect.gen(function* () {
|
||||
const messageRow = yield* db
|
||||
.select()
|
||||
.from(SessionMessageTable)
|
||||
.where(
|
||||
and(
|
||||
eq(SessionMessageTable.id, messageID),
|
||||
eq(SessionMessageTable.session_id, event.data.sessionID),
|
||||
eq(SessionMessageTable.type, "assistant"),
|
||||
),
|
||||
)
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
if (!messageRow) return
|
||||
if (SessionHistory.hasInlineContent(messageRow.data)) {
|
||||
const message = SessionHistory.decodeMessageRowSync(messageRow)
|
||||
if (message.type === "assistant") {
|
||||
const { id: _, type: __, ...data } = encodeMessage({ ...message, content: [] })
|
||||
yield* db
|
||||
.update(SessionMessageTable)
|
||||
.set({ data })
|
||||
.where(eq(SessionMessageTable.id, messageID))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
}
|
||||
}
|
||||
yield* db.delete(SessionPartTable).where(eq(SessionPartTable.message_id, messageID)).run().pipe(Effect.orDie)
|
||||
const partRows = parts.map((part, ordinal) => ({
|
||||
message_id: messageID,
|
||||
session_id: event.data.sessionID,
|
||||
ordinal,
|
||||
type: part.type,
|
||||
call_id: part.type === "tool" ? part.id : null,
|
||||
time_created: event.created,
|
||||
time_updated: event.created,
|
||||
data: SessionHistory.encodePart(part),
|
||||
}))
|
||||
for (let index = 0; index < partRows.length; index += ForkBatchSize) {
|
||||
yield* db
|
||||
.insert(SessionPartTable)
|
||||
.values(partRows.slice(index, index + ForkBatchSize))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
}
|
||||
})
|
||||
},
|
||||
getShell(shellID) {
|
||||
|
|
@ -399,20 +638,44 @@ function run(db: DatabaseService, event: MessageEvent) {
|
|||
}
|
||||
|
||||
function insertMessage(db: DatabaseService, event: SessionEvent.DurableEvent, message: SessionMessage.Info) {
|
||||
const encoded = encodeMessage(message)
|
||||
const { id: _, type, ...data } = encoded
|
||||
return db
|
||||
.insert(SessionMessageTable)
|
||||
.values({
|
||||
id: message.id,
|
||||
session_id: event.data.sessionID,
|
||||
type,
|
||||
seq: event.durable.seq,
|
||||
time_created: DateTime.toEpochMillis(message.time.created),
|
||||
data,
|
||||
})
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
return Effect.gen(function* () {
|
||||
const encoded = encodeMessage(
|
||||
message.type === "assistant" && message.content.length > 0 ? { ...message, content: [] } : message,
|
||||
)
|
||||
const { id: _, type, ...data } = encoded
|
||||
const timeCreated = DateTime.toEpochMillis(message.time.created)
|
||||
yield* db
|
||||
.insert(SessionMessageTable)
|
||||
.values({
|
||||
id: message.id,
|
||||
session_id: event.data.sessionID,
|
||||
type,
|
||||
seq: event.durable.seq,
|
||||
time_created: timeCreated,
|
||||
data,
|
||||
})
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
if (message.type === "assistant" && message.content.length > 0) {
|
||||
const partRows = message.content.map((part, ordinal) => ({
|
||||
message_id: message.id,
|
||||
session_id: event.data.sessionID,
|
||||
ordinal,
|
||||
type: part.type,
|
||||
call_id: part.type === "tool" ? part.id : null,
|
||||
time_created: timeCreated,
|
||||
time_updated: event.created,
|
||||
data: SessionHistory.encodePart(part),
|
||||
}))
|
||||
for (let index = 0; index < partRows.length; index += ForkBatchSize) {
|
||||
yield* db
|
||||
.insert(SessionPartTable)
|
||||
.values(partRows.slice(index, index + ForkBatchSize))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function projectIdle(
|
||||
|
|
|
|||
|
|
@ -18,9 +18,10 @@ import { AbsolutePath, RelativePath } from "../schema.js"
|
|||
import { Session } from "../session.js"
|
||||
import { Slug } from "../util/slug.js"
|
||||
import { SessionEvent } from "./event.js"
|
||||
import { SessionHistory } from "./history.js"
|
||||
import { SessionMessage } from "./message.js"
|
||||
import { SessionProjector } from "./projector.js"
|
||||
import { SessionMessageTable, SessionTable } from "./sql.js"
|
||||
import { SessionMessageTable, SessionPartTable, SessionTable } from "./sql.js"
|
||||
|
||||
export const Data = SessionTransfer.Data
|
||||
export type Data = SessionTransfer.Data
|
||||
|
|
@ -74,8 +75,11 @@ const layer = Layer.effect(
|
|||
const project = yield* projects.resolve(input.location.directory)
|
||||
yield* upsertProject(db, project).pipe(Effect.orDie)
|
||||
const importedAt = yield* Clock.currentTimeMillis
|
||||
const messages = input.data.messages.filter(isSettled).map((message, index) => {
|
||||
const encoded = encodeMessage(message)
|
||||
const settled = input.data.messages.filter(isSettled)
|
||||
const messages = settled.map((message, index) => {
|
||||
const encoded = encodeMessage(
|
||||
message.type === "assistant" && message.content.length > 0 ? { ...message, content: [] } : message,
|
||||
)
|
||||
const { id: _, type, ...data } = encoded
|
||||
return {
|
||||
id: message.id,
|
||||
|
|
@ -86,6 +90,20 @@ const layer = Layer.effect(
|
|||
data,
|
||||
}
|
||||
})
|
||||
const parts = settled.flatMap((message) => {
|
||||
if (message.type !== "assistant" || message.content.length === 0) return []
|
||||
const timeCreated = DateTime.toEpochMillis(message.time.created)
|
||||
return message.content.map((part, ordinal) => ({
|
||||
message_id: message.id,
|
||||
session_id: sessionID,
|
||||
ordinal,
|
||||
type: part.type,
|
||||
call_id: part.type === "tool" ? part.id : null,
|
||||
time_created: timeCreated,
|
||||
time_updated: importedAt,
|
||||
data: SessionHistory.encodePart(part),
|
||||
}))
|
||||
})
|
||||
yield* bus
|
||||
.publish(
|
||||
SessionEvent.Created,
|
||||
|
|
@ -111,6 +129,13 @@ const layer = Layer.effect(
|
|||
Effect.gen(function* () {
|
||||
if (messages.length > 0) {
|
||||
yield* db.insert(SessionMessageTable).values(messages).run().pipe(Effect.orDie)
|
||||
for (let index = 0; index < parts.length; index += 500) {
|
||||
yield* db
|
||||
.insert(SessionPartTable)
|
||||
.values(parts.slice(index, index + 500))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
}
|
||||
yield* Bus.reserveSequence(db, sessionID, seq + messages.length)
|
||||
}
|
||||
yield* db
|
||||
|
|
|
|||
|
|
@ -24,7 +24,14 @@ import { fromRow } from "@opencode/core/session/info"
|
|||
import { SessionInbox } from "@opencode/core/session/inbox"
|
||||
import { SessionStore } from "@opencode/core/session/store"
|
||||
import { Shell } from "@opencode/schema/shell"
|
||||
import { InstructionStateTable, SessionInboxTable, SessionMessageTable, SessionTable } from "@opencode/core/session/sql"
|
||||
import {
|
||||
InstructionStateTable,
|
||||
SessionInboxTable,
|
||||
SessionMessageTable,
|
||||
SessionPartTable,
|
||||
SessionTable,
|
||||
} from "@opencode/core/session/sql"
|
||||
import { SessionHistory } from "@opencode/core/session/history"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { Snapshot } from "@opencode/core/snapshot"
|
||||
|
||||
|
|
@ -750,7 +757,7 @@ describe("SessionProjector", () => {
|
|||
expect(JSON.parse(replayed?.data ?? "{}")).toMatchObject({ native: { step: "replayed" } })
|
||||
expect(JSON.parse(replayed?.data ?? "{}")).not.toHaveProperty("providerState")
|
||||
|
||||
// Projecting onto the legacy row wrote it back in the current shape.
|
||||
// Projecting onto the legacy row split its parts into session_part in the current shape.
|
||||
const rewritten = JSON.parse(
|
||||
(yield* db.get<{ data: string }>(sql`SELECT data FROM session_message WHERE id = ${assistantID}`))?.data ??
|
||||
"{}",
|
||||
|
|
@ -758,13 +765,22 @@ describe("SessionProjector", () => {
|
|||
expect(rewritten).not.toHaveProperty("providerState")
|
||||
expect(rewritten).toMatchObject({
|
||||
native: { step: "replayed" },
|
||||
content: [
|
||||
{ type: "text", native: { signature: "text" } },
|
||||
{ type: "reasoning", native: { signature: "reasoning" } },
|
||||
{ type: "tool", native: { call: "kept", result: "kept" } },
|
||||
],
|
||||
content: [],
|
||||
})
|
||||
expect(rewritten.content.map((part: Record<string, unknown>) => Object.keys(part).toSorted())).toEqual([
|
||||
const partRows = yield* db
|
||||
.select({ data: SessionPartTable.data })
|
||||
.from(SessionPartTable)
|
||||
.where(eq(SessionPartTable.message_id, assistantID))
|
||||
.orderBy(asc(SessionPartTable.ordinal))
|
||||
.all()
|
||||
.pipe(Effect.orDie)
|
||||
const rewrittenParts = partRows.map((row) => row.data)
|
||||
expect(rewrittenParts).toMatchObject([
|
||||
{ type: "text", native: { signature: "text" } },
|
||||
{ type: "reasoning", native: { signature: "reasoning" } },
|
||||
{ type: "tool", native: { call: "kept", result: "kept" } },
|
||||
])
|
||||
expect(rewrittenParts.map((part) => Object.keys(part).toSorted())).toEqual([
|
||||
["native", "text", "type"],
|
||||
["native", "text", "type"],
|
||||
["executed", "id", "name", "native", "state", "time", "type"],
|
||||
|
|
@ -815,7 +831,8 @@ describe("SessionProjector", () => {
|
|||
.where(eq(SessionMessageTable.id, assistantMessageID))
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
expect(row?.data).toMatchObject({
|
||||
expect(row?.data).toMatchObject({ content: [] })
|
||||
expect(yield* SessionHistory.loadMessageRow(db, row!)).toMatchObject({
|
||||
content: [
|
||||
{ id: "succeeded", native: { call: "succeeded", result: "succeeded" }, state: { status: "completed" } },
|
||||
{ id: "failed", native: { call: "failed" }, state: { status: "error" } },
|
||||
|
|
@ -923,9 +940,7 @@ describe("SessionProjector", () => {
|
|||
.orderBy(asc(SessionMessageTable.id))
|
||||
.all()
|
||||
.pipe(Effect.orDie)
|
||||
const messages = rows.map((row) =>
|
||||
Schema.decodeUnknownSync(SessionMessage.Info)({ ...row.data, id: row.id, type: row.type }),
|
||||
)
|
||||
const messages = yield* SessionHistory.decodeMessageRows(db, rows).pipe(Effect.orDie)
|
||||
expect(messages).toEqual([
|
||||
SessionMessage.Assistant.make({
|
||||
id: SessionMessage.ID.make("msg_assistant_completed"),
|
||||
|
|
@ -993,4 +1008,238 @@ describe("SessionProjector", () => {
|
|||
expect(yield* updated()).toEqual({ time_updated: 15 })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect(
|
||||
"stores interleaved assistant parts in session_part by ordinal across out-of-order tool completions and forks",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const db = yield* seedSession()
|
||||
const bus = yield* Bus.Service
|
||||
const assistantMessageID = SessionMessage.ID.make("msg_interleaved")
|
||||
|
||||
yield* bus.publish(SessionEvent.Step.Started, {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
agent: build,
|
||||
model,
|
||||
started: 1,
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Reasoning.Started, { sessionID, assistantMessageID, ordinal: 0 })
|
||||
yield* bus.publish(SessionEvent.Reasoning.Ended, {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
ordinal: 0,
|
||||
text: "plan first",
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Text.Started, { sessionID, assistantMessageID, ordinal: 1 })
|
||||
yield* bus.publish(SessionEvent.Text.Ended, {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
ordinal: 1,
|
||||
text: "running two tools",
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Tool.Input.Started, {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
id: "call_first",
|
||||
name: "read",
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Tool.Called, {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
id: "call_first",
|
||||
input: { file: "a.ts" },
|
||||
executed: true,
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Tool.Input.Started, {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
id: "call_second",
|
||||
name: "read",
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Tool.Called, {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
id: "call_second",
|
||||
input: { file: "b.ts" },
|
||||
executed: true,
|
||||
})
|
||||
// Complete the second tool before the first tool
|
||||
yield* bus.publish(SessionEvent.Tool.Success, {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
id: "call_second",
|
||||
content: [{ type: "text", text: "b contents" }],
|
||||
executed: true,
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Tool.Success, {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
id: "call_first",
|
||||
content: [{ type: "text", text: "a contents" }],
|
||||
executed: true,
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Text.Started, { sessionID, assistantMessageID, ordinal: 4 })
|
||||
yield* bus.publish(SessionEvent.Text.Ended, {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
ordinal: 4,
|
||||
text: "all done",
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Step.Ended, {
|
||||
sessionID,
|
||||
assistantMessageID,
|
||||
finish: "stop",
|
||||
cost: Money.USD.make(0),
|
||||
tokens: { input: 10, output: 5, reasoning: 2, cache: { read: 0, write: 0 } },
|
||||
})
|
||||
|
||||
const envelope = yield* db
|
||||
.select()
|
||||
.from(SessionMessageTable)
|
||||
.where(eq(SessionMessageTable.id, assistantMessageID))
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
expect(envelope?.data).toMatchObject({ content: [] })
|
||||
|
||||
const parts = yield* db
|
||||
.select()
|
||||
.from(SessionPartTable)
|
||||
.where(eq(SessionPartTable.message_id, assistantMessageID))
|
||||
.orderBy(asc(SessionPartTable.ordinal))
|
||||
.all()
|
||||
.pipe(Effect.orDie)
|
||||
expect(parts.map((row) => ({ ordinal: row.ordinal, type: row.type, callID: row.call_id }))).toEqual([
|
||||
{ ordinal: 0, type: "reasoning", callID: null },
|
||||
{ ordinal: 1, type: "text", callID: null },
|
||||
{ ordinal: 2, type: "tool", callID: "call_first" },
|
||||
{ ordinal: 3, type: "tool", callID: "call_second" },
|
||||
{ ordinal: 4, type: "text", callID: null },
|
||||
])
|
||||
|
||||
const forkedSessionID = Session.ID.make("ses_projected_fork")
|
||||
yield* bus.publish(SessionEvent.Forked, {
|
||||
sessionID: forkedSessionID,
|
||||
parentID: sessionID,
|
||||
boundary: { type: "through", messageID: assistantMessageID },
|
||||
})
|
||||
const forkedMessage = yield* db
|
||||
.select()
|
||||
.from(SessionMessageTable)
|
||||
.where(eq(SessionMessageTable.session_id, forkedSessionID))
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
const loadedFork = yield* SessionHistory.loadMessageRow(db, forkedMessage!).pipe(Effect.orDie)
|
||||
expect(loadedFork).toMatchObject({
|
||||
type: "assistant",
|
||||
content: [
|
||||
{ type: "reasoning", text: "plan first" },
|
||||
{ type: "text", text: "running two tools" },
|
||||
{ type: "tool", id: "call_first", state: { status: "completed" } },
|
||||
{ type: "tool", id: "call_second", state: { status: "completed" } },
|
||||
{ type: "text", text: "all done" },
|
||||
],
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("replaces conflicting session_part rows when splitting an inline assistant row", () =>
|
||||
Effect.gen(function* () {
|
||||
const db = yield* seedSession()
|
||||
const bus = yield* Bus.Service
|
||||
const conflictID = SessionMessage.ID.make("msg_conflict_replace")
|
||||
|
||||
// Simulate a row that had stale session_part rows (ordinals 0..2) and then had inline content written
|
||||
yield* db
|
||||
.insert(SessionMessageTable)
|
||||
.values({
|
||||
id: conflictID,
|
||||
session_id: sessionID,
|
||||
seq: 1,
|
||||
type: "assistant",
|
||||
time_created: 10,
|
||||
time_updated: 20,
|
||||
data: {
|
||||
agent: build,
|
||||
model,
|
||||
content: [
|
||||
{ type: "reasoning", text: "fresh inline reasoning", time: { created: 10, completed: 12 } },
|
||||
{ type: "text", text: "fresh inline text" },
|
||||
],
|
||||
time: { created: 10 },
|
||||
},
|
||||
})
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
yield* db
|
||||
.insert(SessionPartTable)
|
||||
.values([
|
||||
{
|
||||
message_id: conflictID,
|
||||
session_id: sessionID,
|
||||
ordinal: 0,
|
||||
type: "text",
|
||||
call_id: null,
|
||||
time_created: 1,
|
||||
time_updated: 1,
|
||||
data: { type: "text", text: "stale part 0" },
|
||||
},
|
||||
{
|
||||
message_id: conflictID,
|
||||
session_id: sessionID,
|
||||
ordinal: 1,
|
||||
type: "text",
|
||||
call_id: null,
|
||||
time_created: 2,
|
||||
time_updated: 2,
|
||||
data: { type: "text", text: "stale part 1" },
|
||||
},
|
||||
{
|
||||
message_id: conflictID,
|
||||
session_id: sessionID,
|
||||
ordinal: 2,
|
||||
type: "text",
|
||||
call_id: null,
|
||||
time_created: 3,
|
||||
time_updated: 3,
|
||||
data: { type: "text", text: "stale trailing part 2" },
|
||||
},
|
||||
])
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
|
||||
yield* bus.publish(SessionEvent.Text.Started, {
|
||||
sessionID,
|
||||
assistantMessageID: conflictID,
|
||||
ordinal: 2,
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Text.Ended, {
|
||||
sessionID,
|
||||
assistantMessageID: conflictID,
|
||||
ordinal: 2,
|
||||
text: "appended after split",
|
||||
})
|
||||
|
||||
const messageRow = yield* db
|
||||
.select()
|
||||
.from(SessionMessageTable)
|
||||
.where(eq(SessionMessageTable.id, conflictID))
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
expect(messageRow?.data).toMatchObject({ content: [] })
|
||||
|
||||
const partRows = yield* db
|
||||
.select()
|
||||
.from(SessionPartTable)
|
||||
.where(eq(SessionPartTable.message_id, conflictID))
|
||||
.orderBy(asc(SessionPartTable.ordinal))
|
||||
.all()
|
||||
.pipe(Effect.orDie)
|
||||
expect(partRows.map((row) => ({ ordinal: row.ordinal, data: row.data }))).toMatchObject([
|
||||
{ ordinal: 0, data: { type: "reasoning", text: "fresh inline reasoning" } },
|
||||
{ ordinal: 1, data: { type: "text", text: "fresh inline text" } },
|
||||
{ ordinal: 2, data: { type: "text", text: "appended after split" } },
|
||||
])
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import { SessionEvent } from "@opencode/core/session/event"
|
|||
import { SessionMessage } from "@opencode/core/session/message"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { SessionProjector } from "@opencode/core/session/projector"
|
||||
import { SessionHistory } from "@opencode/core/session/history"
|
||||
import { SessionMessageTable, SessionTable } from "@opencode/core/session/sql"
|
||||
import { Project } from "@opencode/core/project"
|
||||
import { ProjectTable } from "@opencode/core/project/sql"
|
||||
|
|
@ -214,7 +215,7 @@ testEffect(
|
|||
.from(SessionMessageTable)
|
||||
.where(eq(SessionMessageTable.id, assistantMessageID))
|
||||
.get()
|
||||
expect(message?.data).toMatchObject({
|
||||
expect(yield* SessionHistory.loadMessageRow(database.db, message!)).toMatchObject({
|
||||
content: [{ type: "tool", id: call.id, executed: true, state: { status: "completed" } }],
|
||||
})
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -63,7 +63,13 @@ import { Document, Info } from "@opencode/schema/config"
|
|||
import { ConfigCompaction } from "@opencode/schema/config/compaction"
|
||||
import { Tool } from "@opencode/core/tool"
|
||||
import type { Info as ToolInfo } from "@opencode/schema/tool"
|
||||
import { InstructionStateTable, SessionInboxTable, SessionMessageTable, SessionTable } from "@opencode/core/session/sql"
|
||||
import {
|
||||
InstructionStateTable,
|
||||
SessionInboxTable,
|
||||
SessionMessageTable,
|
||||
SessionPartTable,
|
||||
SessionTable,
|
||||
} from "@opencode/core/session/sql"
|
||||
import { InstructionEntry } from "@opencode/core/session/instruction-entry"
|
||||
import { SessionStore } from "@opencode/core/session/store"
|
||||
import { Instructions } from "@opencode/core/instructions/index"
|
||||
|
|
@ -4641,15 +4647,15 @@ describe("SessionRunnerLLM", () => {
|
|||
executed: false,
|
||||
})
|
||||
yield* s.db
|
||||
.update(SessionMessageTable)
|
||||
.update(SessionPartTable)
|
||||
.set({
|
||||
data: sql`json_set(
|
||||
${SessionMessageTable.data},
|
||||
'$.content[0].state.metadata',
|
||||
${SessionPartTable.data},
|
||||
'$.state.metadata',
|
||||
json('{"sessionID":"ses_existing_child","status":"running","internal":"private"}')
|
||||
)`,
|
||||
})
|
||||
.where(eq(SessionMessageTable.id, assistantMessageID))
|
||||
.where(eq(SessionPartTable.message_id, assistantMessageID))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
s.requests.length = 0
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import { AbsolutePath, RelativePath } from "@opencode/core/schema"
|
|||
import { Session } from "@opencode/core/session"
|
||||
import { SessionMessage } from "@opencode/core/session/message"
|
||||
import { SessionProjector } from "@opencode/core/session/projector"
|
||||
import { SessionHistory } from "@opencode/core/session/history"
|
||||
import { SessionRunnerModel } from "@opencode/core/session/runner/model"
|
||||
import { SessionStep } from "@opencode/core/session/runner/step"
|
||||
import { SessionMessageTable, SessionTable } from "@opencode/core/session/sql"
|
||||
|
|
@ -138,6 +139,9 @@ for (const fixture of [
|
|||
finish: fixture.finish,
|
||||
tokens: { input: 10, output: 4, reasoning: 2, cache: { read: 3, write: 2 } },
|
||||
snapshot: { start, end, files },
|
||||
content: [],
|
||||
})
|
||||
expect(yield* SessionHistory.loadMessageRow(db, message!)).toMatchObject({
|
||||
content: [{ type: "tool", state: { status: fixture.toolChoice === "none" ? "error" : "completed" } }],
|
||||
})
|
||||
expect(message?.data).toHaveProperty("cost", expect.closeTo(0.0000233, 10))
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ import { Bus } from "@opencode/core/bus"
|
|||
import { Database } from "@opencode/core/database/database"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { ProjectTable } from "@opencode/core/project/sql"
|
||||
import { SessionHistory } from "@opencode/core/session/history"
|
||||
import { SessionProjector } from "@opencode/core/session/projector"
|
||||
import { SessionHistory } from "@opencode/core/session/history"
|
||||
import { SessionMessageTable, SessionPartTable } from "@opencode/core/session/sql"
|
||||
import { SessionStore } from "@opencode/core/session/store"
|
||||
import { Agent } from "@opencode/schema/agent"
|
||||
|
|
@ -194,107 +194,142 @@ describe("SessionStore", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
it.effect("hydrates assistant parts from session_part when present and falls back to inline content", () =>
|
||||
it.effect("hydrates and settles assistant messages across session_part rows and legacy inline content rows", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessionID = Session.ID.make("ses_part_read_fallback")
|
||||
yield* seedSessions([{ id: sessionID, updated: 0 }])
|
||||
const sessionID = Session.ID.make("ses_dual_read")
|
||||
const bus = yield* seedSessions([{ id: sessionID, updated: 0 }])
|
||||
const database = yield* Database.Service
|
||||
const store = yield* SessionStore.Service
|
||||
const agent = Agent.ID.make("build")
|
||||
const model = { providerID: Provider.ID.make("anthropic"), id: Model.ID.make("claude-sonnet-4-5") }
|
||||
|
||||
const inlineOnlyID = SessionMessage.ID.make("msg_inline_only")
|
||||
const splitID = SessionMessage.ID.make("msg_split_parts")
|
||||
const legacyUntouchedID = SessionMessage.ID.make("msg_legacy_untouched")
|
||||
const legacyMutatedID = SessionMessage.ID.make("msg_legacy_mutated")
|
||||
const splitID = SessionMessage.ID.make("msg_split")
|
||||
|
||||
// 1. Assistant message with inline content only (no session_part rows) -> falls back to inline content
|
||||
// 1. Untouched legacy row with inline content and no session_part rows
|
||||
yield* database.db
|
||||
.insert(SessionMessageTable)
|
||||
.values({
|
||||
id: inlineOnlyID,
|
||||
id: legacyUntouchedID,
|
||||
session_id: sessionID,
|
||||
seq: 10,
|
||||
seq: -2,
|
||||
type: "assistant",
|
||||
time_created: 10,
|
||||
time_updated: 10,
|
||||
data: {
|
||||
agent,
|
||||
model,
|
||||
content: [{ type: "text", text: "inline fallback content" }],
|
||||
content: [{ type: "text", text: "legacy inline only" }],
|
||||
time: { created: 10, completed: 11 },
|
||||
},
|
||||
})
|
||||
.run()
|
||||
|
||||
// 2. Assistant message with session_part rows -> hydrates parts in ordinal order
|
||||
// 2. Legacy row with inline content that gets mutated via projector and split into session_part
|
||||
yield* database.db
|
||||
.insert(SessionMessageTable)
|
||||
.values({
|
||||
id: splitID,
|
||||
id: legacyMutatedID,
|
||||
session_id: sessionID,
|
||||
seq: 20,
|
||||
seq: -1,
|
||||
type: "assistant",
|
||||
time_created: 20,
|
||||
time_updated: 20,
|
||||
data: {
|
||||
agent,
|
||||
model,
|
||||
content: [],
|
||||
time: { created: 20, completed: 25 },
|
||||
content: [{ type: "reasoning", text: "legacy reasoning" }],
|
||||
time: { created: 20 },
|
||||
},
|
||||
})
|
||||
.run()
|
||||
yield* database.db
|
||||
.insert(SessionPartTable)
|
||||
.values([
|
||||
{
|
||||
message_id: splitID,
|
||||
session_id: sessionID,
|
||||
ordinal: 0,
|
||||
type: "reasoning",
|
||||
call_id: null,
|
||||
time_created: 20,
|
||||
time_updated: 21,
|
||||
data: { type: "reasoning", text: "first reasoning", time: { created: 20, completed: 21 } },
|
||||
},
|
||||
{
|
||||
message_id: splitID,
|
||||
session_id: sessionID,
|
||||
ordinal: 1,
|
||||
type: "tool",
|
||||
call_id: "call_read",
|
||||
time_created: 21,
|
||||
time_updated: 23,
|
||||
data: {
|
||||
type: "tool",
|
||||
id: "call_read",
|
||||
name: "read",
|
||||
executed: true,
|
||||
state: {
|
||||
status: "completed",
|
||||
input: { path: "src/index.ts" },
|
||||
content: [{ type: "text", text: "export {}" }],
|
||||
},
|
||||
time: { created: 21, ran: 22, completed: 23 },
|
||||
},
|
||||
},
|
||||
{
|
||||
message_id: splitID,
|
||||
session_id: sessionID,
|
||||
ordinal: 2,
|
||||
type: "text",
|
||||
call_id: null,
|
||||
time_created: 23,
|
||||
time_updated: 25,
|
||||
data: { type: "text", text: "hydrated from session_part" },
|
||||
},
|
||||
])
|
||||
.run()
|
||||
yield* bus.publish(SessionEvent.Text.Started, {
|
||||
sessionID,
|
||||
assistantMessageID: legacyMutatedID,
|
||||
ordinal: 1,
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Text.Ended, {
|
||||
sessionID,
|
||||
assistantMessageID: legacyMutatedID,
|
||||
ordinal: 1,
|
||||
text: "appended into session_part",
|
||||
})
|
||||
|
||||
expect(yield* store.message(inlineOnlyID)).toMatchObject({
|
||||
// 3. Fresh step projected directly into session_part
|
||||
yield* bus.publish(SessionEvent.Step.Started, {
|
||||
sessionID,
|
||||
assistantMessageID: splitID,
|
||||
agent,
|
||||
model,
|
||||
started: 30,
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Reasoning.Started, { sessionID, assistantMessageID: splitID, ordinal: 0 })
|
||||
yield* bus.publish(SessionEvent.Reasoning.Ended, {
|
||||
sessionID,
|
||||
assistantMessageID: splitID,
|
||||
ordinal: 0,
|
||||
text: "step reasoning",
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Tool.Input.Started, {
|
||||
sessionID,
|
||||
assistantMessageID: splitID,
|
||||
id: "call_1",
|
||||
name: "bash",
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Tool.Called, {
|
||||
sessionID,
|
||||
assistantMessageID: splitID,
|
||||
id: "call_1",
|
||||
input: { command: "ls" },
|
||||
executed: true,
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Tool.Success, {
|
||||
sessionID,
|
||||
assistantMessageID: splitID,
|
||||
id: "call_1",
|
||||
content: [{ type: "text", text: "ok" }],
|
||||
executed: true,
|
||||
})
|
||||
yield* bus.publish(SessionEvent.Text.Started, { sessionID, assistantMessageID: splitID, ordinal: 2 })
|
||||
yield* bus.publish(SessionEvent.Text.Ended, {
|
||||
sessionID,
|
||||
assistantMessageID: splitID,
|
||||
ordinal: 2,
|
||||
text: "step answer",
|
||||
})
|
||||
|
||||
// Verify raw storage split on the mutated legacy row
|
||||
const mutatedRaw = yield* database.db
|
||||
.select()
|
||||
.from(SessionMessageTable)
|
||||
.where(eq(SessionMessageTable.id, legacyMutatedID))
|
||||
.get()
|
||||
expect(mutatedRaw?.data).toMatchObject({ content: [] })
|
||||
const mutatedParts = yield* database.db
|
||||
.select()
|
||||
.from(SessionPartTable)
|
||||
.where(eq(SessionPartTable.message_id, legacyMutatedID))
|
||||
.orderBy(asc(SessionPartTable.ordinal))
|
||||
.all()
|
||||
expect(mutatedParts).toHaveLength(2)
|
||||
|
||||
// Settle reads (single-message lookup)
|
||||
expect(yield* store.message(legacyUntouchedID)).toMatchObject({
|
||||
sessionID,
|
||||
message: {
|
||||
id: inlineOnlyID,
|
||||
content: [{ type: "text", text: "inline fallback content" }],
|
||||
id: legacyUntouchedID,
|
||||
content: [{ type: "text", text: "legacy inline only" }],
|
||||
},
|
||||
})
|
||||
expect(yield* store.message(legacyMutatedID)).toMatchObject({
|
||||
sessionID,
|
||||
message: {
|
||||
id: legacyMutatedID,
|
||||
content: [
|
||||
{ type: "reasoning", text: "legacy reasoning" },
|
||||
{ type: "text", text: "appended into session_part" },
|
||||
],
|
||||
},
|
||||
})
|
||||
expect(yield* store.message(splitID)).toMatchObject({
|
||||
|
|
@ -302,26 +337,33 @@ describe("SessionStore", () => {
|
|||
message: {
|
||||
id: splitID,
|
||||
content: [
|
||||
{ type: "reasoning", text: "first reasoning" },
|
||||
{ type: "tool", id: "call_read", state: { status: "completed" } },
|
||||
{ type: "text", text: "hydrated from session_part" },
|
||||
{ type: "reasoning", text: "step reasoning" },
|
||||
{ type: "tool", id: "call_1", state: { status: "completed" } },
|
||||
{ type: "text", text: "step answer" },
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
// Hydrate reads (paged store.messages and full SessionHistory.get)
|
||||
const hydrated = yield* store.messages({ sessionID, order: "asc" })
|
||||
expect(hydrated).toMatchObject([
|
||||
{ id: inlineOnlyID, content: [{ type: "text", text: "inline fallback content" }] },
|
||||
{ id: legacyUntouchedID, content: [{ type: "text", text: "legacy inline only" }] },
|
||||
{
|
||||
id: legacyMutatedID,
|
||||
content: [
|
||||
{ type: "reasoning", text: "legacy reasoning" },
|
||||
{ type: "text", text: "appended into session_part" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: splitID,
|
||||
content: [
|
||||
{ type: "reasoning", text: "first reasoning" },
|
||||
{ type: "tool", id: "call_read", state: { status: "completed" } },
|
||||
{ type: "text", text: "hydrated from session_part" },
|
||||
{ type: "reasoning", text: "step reasoning" },
|
||||
{ type: "tool", id: "call_1", state: { status: "completed" } },
|
||||
{ type: "text", text: "step answer" },
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const rows = yield* database.db
|
||||
.select()
|
||||
.from(SessionMessageTable)
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import { Session } from "@opencode/core/session"
|
|||
import { SessionEvent } from "@opencode/core/session/event"
|
||||
import { SessionMessage } from "@opencode/core/session/message"
|
||||
import { SessionProjector } from "@opencode/core/session/projector"
|
||||
import { SessionHistory } from "@opencode/core/session/history"
|
||||
import { SessionTable, SessionMessageTable } from "@opencode/core/session/sql"
|
||||
import { testEffect } from "./lib/effect"
|
||||
|
||||
|
|
@ -68,7 +69,8 @@ describe("Session tool progress", () => {
|
|||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
if (!row) return yield* Effect.die("Missing projected assistant")
|
||||
return Schema.decodeUnknownSync(SessionMessage.Assistant)({ ...row.data, id: row.id, type: row.type })
|
||||
const message = yield* SessionHistory.loadMessageRow(db, row).pipe(Effect.orDie)
|
||||
return Schema.decodeUnknownSync(SessionMessage.Assistant)(Schema.encodeSync(SessionMessage.Info)(message))
|
||||
})
|
||||
const start = (id: string) =>
|
||||
Effect.gen(function* () {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue