mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 18:57:17 +03:00
fix(session-ui): end the live turn phase on retry, failure and interrupt (#61823)
This commit is contained in:
committed by
GitHub
Unverified
parent
8bae6b5c1c
commit
6f725c68d1
@@ -52,6 +52,7 @@ import type {
|
||||
} from "@opencode/client/promise"
|
||||
import type { SessionUserActions, SessionUserAttachmentReference, SessionUserComment } from "../actions"
|
||||
import { agentLabel } from "./agent-label"
|
||||
import { isInterruptedError } from "../timeline/turn-phase-machine"
|
||||
import { attached, imageAttachmentPlaceholderStyle, typeLabel } from "../components/message-file"
|
||||
import {
|
||||
createMessageActionState,
|
||||
@@ -101,9 +102,7 @@ function modelItems(data: ReturnType<typeof useData>, model: SessionMessageAssis
|
||||
}
|
||||
|
||||
function sameModel(a: SessionMessageAssistant["model"], b: SessionMessageAssistant["model"]) {
|
||||
return (
|
||||
a.providerID === b.providerID && a.id === b.id && (a.variant ?? "default") === (b.variant ?? "default")
|
||||
)
|
||||
return a.providerID === b.providerID && a.id === b.id && (a.variant ?? "default") === (b.variant ?? "default")
|
||||
}
|
||||
|
||||
function MetaItems(props: { items: MetaItem[]; slot: "user-message" | "text-part" }) {
|
||||
@@ -1164,11 +1163,7 @@ export function AssistantTextContent(props: {
|
||||
onMount(() => (rendered = true))
|
||||
const sources = () => (props.showCopy && sourcesHost?.enabled ? props.sources : undefined)
|
||||
|
||||
const interrupted = () => {
|
||||
const type = props.message.error?.type.toLowerCase()
|
||||
|
||||
return !!type && (type.includes("abort") || type.includes("interrupt"))
|
||||
}
|
||||
const interrupted = () => isInterruptedError(props.message.error)
|
||||
|
||||
const labels = createMemo<MetaItem[]>(() => {
|
||||
const agent = agentLabel(props.message.agent, data.agents)
|
||||
|
||||
@@ -17,8 +17,19 @@ import {
|
||||
} from "../message/current-tool-state"
|
||||
import { TimelineRow, type PartGroup, type PartRef, type TimelineRowMap } from "./timeline-row"
|
||||
import { timelineCategory, timelineNoticePlacement, timelineNoticeRequired, type TimelineDetail } from "./detail"
|
||||
import {
|
||||
IDLE_TURN_PHASE,
|
||||
isInterruptedError,
|
||||
sameTurnPhase,
|
||||
transitionTurnPhase,
|
||||
viewTurnPhase,
|
||||
type TurnErrorInfo,
|
||||
type TurnPhase,
|
||||
type TurnPhaseEvent,
|
||||
type TurnThinkingPlacement,
|
||||
} from "./turn-phase-machine"
|
||||
|
||||
export { TimelineRow, type PartGroup, type PartRef, type TimelineRowMap }
|
||||
export { TimelineRow, type PartGroup, type PartRef, type TimelineRowMap, type TurnPhase }
|
||||
|
||||
export type ReasoningMode = "hidden" | "compact" | "full"
|
||||
|
||||
@@ -121,6 +132,7 @@ export function createTimelineProjection(input: TimelineProjectionInput) {
|
||||
|
||||
return {
|
||||
activeMessageID: projection.activeMessageID,
|
||||
turnPhaseByID: projection.turnPhaseByID,
|
||||
assistantMessagesByParent: indexAssistantMessages(input.sessionMessages),
|
||||
lastAssistantGroupKey,
|
||||
messageByID: sessionMessageByID,
|
||||
@@ -199,6 +211,17 @@ export function createReactiveTimelineProjection(input: {
|
||||
|
||||
const activeMessageID = createMemo(() => projection().activeMessageID)
|
||||
|
||||
// Rows read their turn's phase, so a recomputed projection that leaves every phase as it was notifies none of them.
|
||||
const turnPhaseByID = createMemo(() => projection().turnPhaseByID, undefined, {
|
||||
equals: (previous, next) =>
|
||||
previous.size === next.size &&
|
||||
[...next].every(([id, phase]) => {
|
||||
const prior = previous.get(id)
|
||||
|
||||
return !!prior && sameTurnPhase(prior, phase)
|
||||
}),
|
||||
})
|
||||
|
||||
const rows = createMemo((previous: TimelineRow.TimelineRow[] | undefined) =>
|
||||
reuseTimelineRows(previous, withNewMessages(projection().rows, input.newMessages?.(), input.newMessagesRead?.())),
|
||||
)
|
||||
@@ -233,6 +256,7 @@ export function createReactiveTimelineProjection(input: {
|
||||
|
||||
return {
|
||||
activeMessageID,
|
||||
turnPhaseByID,
|
||||
assistantMessagesByParent,
|
||||
lastAssistantGroupKey,
|
||||
messageByID: sessionMessageByID,
|
||||
@@ -376,13 +400,14 @@ export namespace Timeline {
|
||||
last?.type === "notice" &&
|
||||
last.message.type === "compaction" &&
|
||||
last.message.status === "failed" &&
|
||||
!isInterrupted(last.message.error)
|
||||
!isInterruptedError(last.message.error)
|
||||
)
|
||||
return
|
||||
|
||||
const lastStep = current?.entries.findLast((entry) => entry.type === "assistant" || entry.type === "idle")
|
||||
|
||||
if (lastStep?.type === "assistant" && lastStep.message.error && !isInterrupted(lastStep.message.error)) return
|
||||
if (lastStep?.type === "assistant" && lastStep.message.error && !isInterruptedError(lastStep.message.error))
|
||||
return
|
||||
|
||||
if (current && !current.shell) {
|
||||
current.entries.push({ type: "idle", message })
|
||||
@@ -399,10 +424,18 @@ export namespace Timeline {
|
||||
turns.findLast((turn) => !pendingInputIDs?.has(turn.id) || turn.entries.some((entry) => entry.type === "idle"))
|
||||
?.id ?? turns.at(-1)?.id
|
||||
|
||||
const placement = detail ? detail.thinking.placement : showReasoning ? "separate" : "hidden"
|
||||
|
||||
const turnPhaseByID = new Map(
|
||||
turns.map((turn) => [turn.id, turnPhase(turn.entries, turn.id === activeMessageID, status, placement)] as const),
|
||||
)
|
||||
|
||||
const phaseOf = (turn: Turn) => turnPhaseByID.get(turn.id) ?? IDLE_TURN_PHASE
|
||||
|
||||
const commentary = new Set(
|
||||
detail && detail.commentary.placement !== "separate"
|
||||
? turns.flatMap((turn) =>
|
||||
turnCommentary(turn.entries, turn.id !== activeMessageID || status.type === "idle", (content) =>
|
||||
turnCommentary(turn.entries, viewTurnPhase(phaseOf(turn)).settled, (content) =>
|
||||
isRenderable(content, showReasoning, detail),
|
||||
),
|
||||
)
|
||||
@@ -459,8 +492,7 @@ export namespace Timeline {
|
||||
turn.entries,
|
||||
index,
|
||||
showReasoning,
|
||||
status,
|
||||
turn.id === activeMessageID,
|
||||
phaseOf(turn),
|
||||
shellToolDefaultOpen,
|
||||
editToolDefaultOpen,
|
||||
visible,
|
||||
@@ -492,6 +524,7 @@ export namespace Timeline {
|
||||
|
||||
return {
|
||||
activeMessageID,
|
||||
turnPhaseByID,
|
||||
rows: detail
|
||||
? groupMessages(
|
||||
rows,
|
||||
@@ -517,8 +550,7 @@ export namespace Timeline {
|
||||
entries: Entry[],
|
||||
index: number,
|
||||
showReasoning: boolean,
|
||||
status: SessionStatus,
|
||||
isActive: boolean,
|
||||
phase: TurnPhase,
|
||||
shellToolDefaultOpen = false,
|
||||
editToolDefaultOpen = false,
|
||||
isRenderable = renderable,
|
||||
@@ -531,21 +563,8 @@ export namespace Timeline {
|
||||
const lastStep = entries.findLast((entry) => entry.type === "assistant" || entry.type === "idle")
|
||||
const previousUserMessage = index > 0
|
||||
const compaction = entries.some((entry) => entry.type === "notice" && entry.message.type === "compaction")
|
||||
const lastContent = lastAssistant?.content.at(-1)
|
||||
|
||||
const working =
|
||||
isActive &&
|
||||
status.type === "busy" &&
|
||||
lastStep?.type === "assistant" &&
|
||||
lastAssistant?.time.completed === undefined &&
|
||||
!lastAssistant?.error &&
|
||||
!lastAssistant?.retry
|
||||
|
||||
const thinking =
|
||||
working &&
|
||||
(detail ? detail.thinking.placement === "separate" : showReasoning) &&
|
||||
lastContent?.type === "reasoning" &&
|
||||
lastContent.time?.completed === undefined
|
||||
const view = viewTurnPhase(phase)
|
||||
const thinking = view.separateThinkingRef
|
||||
|
||||
if (previousUserMessage) rows.push(new TimelineRow.TurnGap({ userMessageID: turnID }))
|
||||
|
||||
@@ -561,12 +580,13 @@ export namespace Timeline {
|
||||
contentEntries(message)
|
||||
.filter(
|
||||
(entry) =>
|
||||
isRenderable(entry.content, showReasoning, detail) && !(thinking && entry.content === lastContent),
|
||||
isRenderable(entry.content, showReasoning, detail) &&
|
||||
!(thinking?.messageID === message.id && thinking.partID === entry.id),
|
||||
)
|
||||
.map((entry) => ({ messageID: message.id, messageIndex, partID: entry.id, content: entry.content })),
|
||||
)
|
||||
|
||||
const interruptedAt = messages.findIndex((message) => isInterrupted(message.error))
|
||||
const interruptedAt = messages.findIndex((message) => isInterruptedError(message.error))
|
||||
const before = interruptedAt < 0 ? refs : refs.filter((ref) => ref.messageIndex <= interruptedAt)
|
||||
const after = interruptedAt < 0 ? [] : refs.filter((ref) => ref.messageIndex > interruptedAt)
|
||||
|
||||
@@ -599,26 +619,21 @@ export namespace Timeline {
|
||||
if (messages.at(-1) !== lastAssistant) return
|
||||
|
||||
// The live reasoning row closes its own step, so notices that arrive meanwhile follow it.
|
||||
if (thinking && lastAssistant)
|
||||
rows.push(
|
||||
new TimelineRow.Thinking({
|
||||
userMessageID: turnID,
|
||||
ref: { messageID: lastAssistant.id, partID: contentEntries(lastAssistant).at(-1)!.id },
|
||||
}),
|
||||
)
|
||||
if (thinking) rows.push(new TimelineRow.Thinking({ userMessageID: turnID, ref: thinking }))
|
||||
|
||||
if (lastStep?.type !== "assistant") return
|
||||
|
||||
if (isActive && lastAssistant?.retry) rows.push(new TimelineRow.Retry({ userMessageID: turnID }))
|
||||
else if (lastAssistant?.error && !isInterrupted(lastAssistant.error))
|
||||
if (view.retry)
|
||||
rows.push(
|
||||
new TimelineRow.Error({
|
||||
new TimelineRow.Retry({
|
||||
userMessageID: turnID,
|
||||
text: unwrapErrorMessage(lastAssistant.error.message),
|
||||
...usageLimit(lastAssistant),
|
||||
...budgetLimit(lastAssistant),
|
||||
attempt: view.retry.attempt,
|
||||
message: view.retry.message,
|
||||
next: view.retry.next,
|
||||
}),
|
||||
)
|
||||
|
||||
if (view.error) rows.push(new TimelineRow.Error({ userMessageID: turnID, ...view.error }))
|
||||
}
|
||||
|
||||
let assistantSegment: SessionMessageAssistant[] = []
|
||||
@@ -632,15 +647,8 @@ export namespace Timeline {
|
||||
appendAssistantSegment(assistantSegment)
|
||||
assistantSegment = []
|
||||
|
||||
if (entry === lastStep)
|
||||
rows.push(
|
||||
new TimelineRow.Error({
|
||||
userMessageID: turnID,
|
||||
text: unwrapErrorMessage(entry.message.error.message),
|
||||
...usageLimit(entry.message),
|
||||
...budgetLimit(entry.message),
|
||||
}),
|
||||
)
|
||||
if (entry === lastStep && view.error)
|
||||
rows.push(new TimelineRow.Error({ userMessageID: turnID, ...view.error }))
|
||||
|
||||
return
|
||||
case "diff":
|
||||
@@ -728,8 +736,56 @@ function budgetLimit(message: Pick<SessionMessageAssistant, "error">) {
|
||||
return { kind, resetAt: at }
|
||||
}
|
||||
|
||||
function isInterrupted(error: SessionMessageAssistant["error"]) {
|
||||
return error?.type.toLowerCase().includes("abort") || error?.type.toLowerCase().includes("interrupt")
|
||||
// Each step replaces the phase the steps before it left, so the turn ends in the phase of its last step.
|
||||
function turnPhase(entries: Entry[], active: boolean, status: SessionStatus, placement: TurnThinkingPlacement) {
|
||||
return entries.reduce(
|
||||
(phase, entry) => {
|
||||
if (entry.type === "idle")
|
||||
return transitionTurnPhase(phase, { type: "idle.failed", error: errorInfo(entry.message) })
|
||||
|
||||
if (entry.type !== "assistant") return phase
|
||||
|
||||
return transitionTurnPhase(phase, stepEvent(entry.message, active, status, placement))
|
||||
},
|
||||
transitionTurnPhase(IDLE_TURN_PHASE, { type: "started", live: active && status.type !== "idle" }),
|
||||
)
|
||||
}
|
||||
|
||||
function stepEvent(
|
||||
message: SessionMessageAssistant,
|
||||
active: boolean,
|
||||
status: SessionStatus,
|
||||
placement: TurnThinkingPlacement,
|
||||
): TurnPhaseEvent {
|
||||
const completed = message.time.completed !== undefined
|
||||
const last = !completed && active ? Timeline.contentEntries(message).at(-1) : undefined
|
||||
|
||||
return {
|
||||
type: "step",
|
||||
active,
|
||||
session: status.type,
|
||||
completed,
|
||||
reasoning:
|
||||
last?.content.type === "reasoning" && last.content.time?.completed === undefined
|
||||
? { ref: { messageID: message.id, partID: last.id }, placement }
|
||||
: undefined,
|
||||
retry: message.retry
|
||||
? { attempt: message.retry.attempt, message: message.retry.error.message, next: message.retry.at }
|
||||
: undefined,
|
||||
error: !message.error
|
||||
? undefined
|
||||
: isInterruptedError(message.error)
|
||||
? { interrupted: true }
|
||||
: { interrupted: false, info: errorInfo(message) },
|
||||
}
|
||||
}
|
||||
|
||||
function errorInfo(message: Parameters<typeof usageLimit>[0]): TurnErrorInfo {
|
||||
return {
|
||||
text: unwrapErrorMessage(message.error?.message ?? ""),
|
||||
...usageLimit(message),
|
||||
...budgetLimit(message),
|
||||
}
|
||||
}
|
||||
|
||||
function isFailedIdle(message: SessionMessageInfo): message is FailedIdle {
|
||||
|
||||
@@ -59,6 +59,7 @@ import {
|
||||
type PartRef,
|
||||
type ReasoningMode,
|
||||
} from "./projection"
|
||||
import { IDLE_TURN_PHASE, sameRef, viewTurnPhase } from "./turn-phase-machine"
|
||||
|
||||
const emptyAssistantMessages: SessionMessageAssistant[] = []
|
||||
|
||||
@@ -197,8 +198,7 @@ export function createSessionTimelineRowRenderer(input: {
|
||||
equals: (a, b) => a?.above === b?.above && a?.below === b?.below,
|
||||
})
|
||||
|
||||
const workingTurn = (messageID: string) =>
|
||||
input.status().type !== "idle" && input.projection.activeMessageID() === messageID
|
||||
const phase = (messageID: string) => viewTurnPhase(input.projection.turnPhaseByID().get(messageID) ?? IDLE_TURN_PHASE)
|
||||
|
||||
const duration = (messageID: string) => {
|
||||
const user = input.projection.messageByID().get(messageID)
|
||||
@@ -219,7 +219,7 @@ export function createSessionTimelineRowRenderer(input: {
|
||||
}
|
||||
|
||||
const copyContentID = (messageID: string) => {
|
||||
if (workingTurn(messageID)) return null
|
||||
if (phase(messageID).hideCopy) return null
|
||||
|
||||
const message = input.projection
|
||||
.assistantMessagesByParent()
|
||||
@@ -262,7 +262,7 @@ export function createSessionTimelineRowRenderer(input: {
|
||||
|
||||
if (group.type !== "context") return []
|
||||
const contents = indexGroupContents(group.refs)
|
||||
const lastAssistant = input.projection.assistantMessagesByParent().get(row().userMessageID)?.at(-1)
|
||||
const streaming = phase(row().userMessageID).streamingReasoningRef
|
||||
|
||||
return group.refs.flatMap<ContextGroupPart>((ref) => {
|
||||
const content = contents.get(ref.messageID)?.get(ref.partID)
|
||||
@@ -278,15 +278,7 @@ export function createSessionTimelineRowRenderer(input: {
|
||||
{
|
||||
...content,
|
||||
id: ref.partID,
|
||||
streaming:
|
||||
workingTurn(row().userMessageID) &&
|
||||
input.status().type === "busy" &&
|
||||
lastAssistant?.id === ref.messageID &&
|
||||
lastAssistant.time.completed === undefined &&
|
||||
!lastAssistant.error &&
|
||||
!lastAssistant.retry &&
|
||||
lastAssistant.content.at(-1) === content &&
|
||||
content.time?.completed === undefined,
|
||||
streaming: sameRef(streaming, ref),
|
||||
},
|
||||
]
|
||||
const message = input.projection.messageByID().get(ref.messageID)
|
||||
@@ -349,7 +341,7 @@ export function createSessionTimelineRowRenderer(input: {
|
||||
onFileOpenChange={(path, open) => input.disclosure.set(`patch:${path}`, open)}
|
||||
open={input.disclosure.value(key()) === true}
|
||||
busy={
|
||||
workingTurn(row().userMessageID) &&
|
||||
phase(row().userMessageID).live &&
|
||||
input.projection.lastAssistantGroupKey().get(row().userMessageID) === row().group.key
|
||||
}
|
||||
onOpenChange={(open) => input.disclosure.set(key(), open)}
|
||||
@@ -1117,7 +1109,7 @@ export function createSessionTimelineRowRenderer(input: {
|
||||
return (
|
||||
<Frame row={current()}>
|
||||
<div data-slot="session-turn-message-container" class={`w-full ${padding()}`}>
|
||||
<div data-slot="session-turn-assistant-content" aria-hidden={workingTurn(current().userMessageID)}>
|
||||
<div data-slot="session-turn-assistant-content" aria-hidden={phase(current().userMessageID).live}>
|
||||
{content}
|
||||
</div>
|
||||
</div>
|
||||
@@ -1198,20 +1190,13 @@ export function createSessionTimelineRowRenderer(input: {
|
||||
return value
|
||||
}
|
||||
|
||||
const status = createMemo(() => {
|
||||
const retry = (
|
||||
input.projection.assistantMessagesByParent().get(current().userMessageID) ?? emptyAssistantMessages
|
||||
).at(-1)?.retry
|
||||
|
||||
if (!retry) return input.status()
|
||||
|
||||
return { type: "retry" as const, attempt: retry.attempt, message: retry.error.message, next: retry.at }
|
||||
})
|
||||
|
||||
return (
|
||||
<Frame row={current()}>
|
||||
<div data-slot="session-turn-message-container" class={`w-full ${padding()}`}>
|
||||
<SessionRetry status={status()} show={input.projection.activeMessageID() === current().userMessageID} />
|
||||
<SessionRetry
|
||||
status={{ type: "retry", attempt: current().attempt, message: current().message, next: current().next }}
|
||||
show={input.projection.activeMessageID() === current().userMessageID}
|
||||
/>
|
||||
</div>
|
||||
</Frame>
|
||||
)
|
||||
|
||||
@@ -76,8 +76,12 @@ export namespace TimelineRow {
|
||||
resetAt?: number
|
||||
}> {}
|
||||
|
||||
/** The active turn waits to retry its step: `attempt` counts tries, `next` is when the next one starts. */
|
||||
export class Retry extends Data.TaggedClass("Retry")<{
|
||||
userMessageID: string
|
||||
attempt: number
|
||||
message: string
|
||||
next: number
|
||||
}> {}
|
||||
|
||||
/** A compaction the server has admitted but not started. */
|
||||
@@ -161,7 +165,11 @@ export namespace TimelineRow {
|
||||
other.text === row.text &&
|
||||
other.kind === row.kind &&
|
||||
other.resetAt === row.resetAt,
|
||||
Retry: () => (other: TimelineRow) => Predicate.isTagged(other, "Retry"),
|
||||
Retry: (row) => (other: TimelineRow) =>
|
||||
Predicate.isTagged(other, "Retry") &&
|
||||
other.attempt === row.attempt &&
|
||||
other.message === row.message &&
|
||||
other.next === row.next,
|
||||
CompactionQueued: (row) => (other: TimelineRow) =>
|
||||
Predicate.isTagged(other, "CompactionQueued") && other.inboxID === row.inboxID,
|
||||
TurnDiff: (row) => (other: TimelineRow) =>
|
||||
@@ -212,7 +220,7 @@ export type TimelineRowMap = {
|
||||
spacing?: "tool" | "content"
|
||||
}
|
||||
Thinking: { userMessageID: string; ref: PartRef }
|
||||
Retry: { userMessageID: string }
|
||||
Retry: { userMessageID: string; attempt: number; message: string; next: number }
|
||||
Error: {
|
||||
userMessageID: string
|
||||
text: string
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { SessionMessageAssistant, SessionMessageInfo, SessionStatus } from "@opencode/client/promise"
|
||||
import { timelinePresets, type TimelineDetail } from "./detail"
|
||||
import { Timeline } from "./projection"
|
||||
import {
|
||||
IDLE_TURN_PHASE,
|
||||
INTERRUPTED_TURN_PHASE,
|
||||
transitionTurnPhase,
|
||||
viewTurnPhase,
|
||||
WORKING_TURN_PHASE,
|
||||
type TurnPhaseEvent,
|
||||
} from "./turn-phase-machine"
|
||||
|
||||
const user = { id: "msg_user", type: "user", text: "go", time: { created: 1 } } satisfies SessionMessageInfo
|
||||
|
||||
const thought = { type: "reasoning", text: "Thinking", time: { created: 2 } } as const
|
||||
|
||||
const grouped: TimelineDetail = timelinePresets[2].value
|
||||
|
||||
function assistant(id: string, fields: Partial<SessionMessageAssistant> = {}): SessionMessageAssistant {
|
||||
return {
|
||||
id,
|
||||
type: "assistant",
|
||||
agent: "build",
|
||||
model: { id: "model", providerID: "provider" },
|
||||
content: [thought],
|
||||
time: { created: 2 },
|
||||
...fields,
|
||||
}
|
||||
}
|
||||
|
||||
function phase(
|
||||
messages: SessionMessageInfo[],
|
||||
status: SessionStatus = { type: "busy" },
|
||||
detail: TimelineDetail | undefined = grouped,
|
||||
) {
|
||||
return Timeline.constructSessionMessageRows(
|
||||
messages,
|
||||
true,
|
||||
status,
|
||||
undefined,
|
||||
false,
|
||||
false,
|
||||
undefined,
|
||||
detail,
|
||||
).turnPhaseByID.get(user.id)!
|
||||
}
|
||||
|
||||
describe("turn phase", () => {
|
||||
test("ends the live phase when a step retries or fails while the Session is still busy", () => {
|
||||
const retrying = phase([
|
||||
user,
|
||||
assistant("msg_a", { retry: { attempt: 2, at: 10, error: { type: "ProviderError", message: "rate limited" } } }),
|
||||
])
|
||||
|
||||
const failed = phase([user, assistant("msg_a", { error: { type: "provider.error", message: "Failed" } })])
|
||||
|
||||
expect(retrying).toEqual({ status: "retrying", attempt: 2, message: "rate limited", next: 10 })
|
||||
expect(viewTurnPhase(retrying)).toMatchObject({ live: false, hideCopy: true, streamingReasoningRef: undefined })
|
||||
expect(failed).toEqual({ status: "failed", error: { text: "Failed" } })
|
||||
expect(viewTurnPhase(failed)).toMatchObject({ live: false, hideCopy: false, streamingReasoningRef: undefined })
|
||||
})
|
||||
|
||||
test("stays working between steps and settles on an interrupt or a failed idle marker before the status does", () => {
|
||||
const between = phase([user, assistant("msg_a", { content: [], time: { created: 2, completed: 3 } })])
|
||||
|
||||
const interrupted = phase([
|
||||
user,
|
||||
assistant("msg_a", { error: { type: "MessageAbortedError", message: "Stopped" } }),
|
||||
])
|
||||
|
||||
const idle = phase([
|
||||
user,
|
||||
assistant("msg_a"),
|
||||
{
|
||||
id: "msg_idle",
|
||||
type: "idle",
|
||||
outcome: "failed",
|
||||
error: { type: "unknown", message: "Session failed" },
|
||||
time: { created: 4 },
|
||||
},
|
||||
])
|
||||
|
||||
expect(between).toBe(WORKING_TURN_PHASE)
|
||||
expect(viewTurnPhase(between).live).toBe(true)
|
||||
expect(interrupted).toBe(INTERRUPTED_TURN_PHASE)
|
||||
expect(viewTurnPhase(interrupted)).toMatchObject({ live: false, hideCopy: false, settled: true })
|
||||
expect(idle).toEqual({ status: "failed", error: { text: "Session failed" } })
|
||||
expect(viewTurnPhase(idle).streamingReasoningRef).toBeUndefined()
|
||||
})
|
||||
|
||||
test("streams reasoning only where the reader sees it", () => {
|
||||
const ref = { messageID: "msg_a", partID: "msg_a:reasoning:0" }
|
||||
const messages = [user, assistant("msg_a")]
|
||||
|
||||
const hidden = phase(
|
||||
messages,
|
||||
{ type: "busy" },
|
||||
{ ...grouped, thinking: { ...grouped.thinking, placement: "hidden" } },
|
||||
)
|
||||
|
||||
const separate = phase(
|
||||
messages,
|
||||
{ type: "busy" },
|
||||
{ ...grouped, thinking: { ...grouped.thinking, placement: "separate" } },
|
||||
)
|
||||
|
||||
const inline = phase(
|
||||
messages,
|
||||
{ type: "busy" },
|
||||
{ ...grouped, thinking: { ...grouped.thinking, placement: "grouped" } },
|
||||
)
|
||||
|
||||
expect(hidden).toBe(WORKING_TURN_PHASE)
|
||||
expect(viewTurnPhase(separate)).toMatchObject({ separateThinkingRef: ref, streamingReasoningRef: ref })
|
||||
expect(viewTurnPhase(inline)).toMatchObject({ separateThinkingRef: undefined, streamingReasoningRef: ref })
|
||||
})
|
||||
|
||||
test("settles every turn but the active one, and the active one once the Session is idle", () => {
|
||||
const messages = [user, assistant("msg_a")]
|
||||
|
||||
const projection = Timeline.constructSessionMessageRows(
|
||||
[...messages, { id: "msg_next", type: "user", text: "next", time: { created: 5 } }],
|
||||
true,
|
||||
{ type: "busy" },
|
||||
)
|
||||
|
||||
expect(projection.turnPhaseByID.get(user.id)).toBe(IDLE_TURN_PHASE)
|
||||
expect(projection.turnPhaseByID.get("msg_next")).toBe(WORKING_TURN_PHASE)
|
||||
expect(phase(messages, { type: "idle" })).toBe(IDLE_TURN_PHASE)
|
||||
})
|
||||
|
||||
test("recovers from a failed step when a later step runs", () => {
|
||||
const failed = {
|
||||
type: "step",
|
||||
active: true,
|
||||
session: "busy",
|
||||
completed: true,
|
||||
error: { interrupted: false, info: { text: "x" } },
|
||||
} satisfies TurnPhaseEvent
|
||||
|
||||
const next = { type: "step", active: true, session: "busy", completed: false } satisfies TurnPhaseEvent
|
||||
|
||||
const state = [failed, next].reduce(
|
||||
transitionTurnPhase,
|
||||
transitionTurnPhase(IDLE_TURN_PHASE, { type: "started", live: true }),
|
||||
)
|
||||
|
||||
expect(state).toBe(WORKING_TURN_PHASE)
|
||||
})
|
||||
|
||||
test("keeps the same thinking phase while the same part streams", () => {
|
||||
const event = {
|
||||
type: "step",
|
||||
active: true,
|
||||
session: "busy",
|
||||
completed: false,
|
||||
reasoning: { ref: { messageID: "msg_a", partID: "p" }, placement: "grouped" },
|
||||
} satisfies TurnPhaseEvent
|
||||
|
||||
const first = transitionTurnPhase(WORKING_TURN_PHASE, event)
|
||||
|
||||
expect(
|
||||
transitionTurnPhase(first, {
|
||||
...event,
|
||||
reasoning: { ...event.reasoning, ref: { messageID: "msg_a", partID: "p" } },
|
||||
}),
|
||||
).toBe(first)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { PartRef } from "./timeline-row"
|
||||
|
||||
export type TurnLimitKind = "free-limit" | "go-limit" | "budget-limit" | "model-budget-limit"
|
||||
|
||||
export type TurnErrorInfo = {
|
||||
readonly text: string
|
||||
readonly kind?: TurnLimitKind
|
||||
readonly resetAt?: number
|
||||
}
|
||||
|
||||
export type TurnThinkingPlacement = "separate" | "grouped" | "hidden"
|
||||
|
||||
/**
|
||||
* Where one turn stands. `working` means the model runs, between steps too; `thinking` is working with a reasoning part
|
||||
* still streaming where the reader can see it. `retrying`, `failed` and `interrupted` end the live phase even while the
|
||||
* Session status has not settled yet.
|
||||
*/
|
||||
export type TurnPhase =
|
||||
| { readonly status: "idle" }
|
||||
| { readonly status: "working" }
|
||||
| { readonly status: "thinking"; readonly ref: PartRef; readonly placement: "separate" | "grouped" }
|
||||
| { readonly status: "retrying"; readonly attempt: number; readonly message: string; readonly next: number }
|
||||
| { readonly status: "failed"; readonly error: TurnErrorInfo }
|
||||
| { readonly status: "interrupted" }
|
||||
|
||||
/** The facts of one turn in order: whether it can run, then each step it took. Notices are not steps. */
|
||||
export type TurnPhaseEvent =
|
||||
| { readonly type: "started"; readonly live: boolean }
|
||||
| {
|
||||
readonly type: "step"
|
||||
readonly active: boolean
|
||||
readonly session: "idle" | "busy" | "retry"
|
||||
readonly completed: boolean
|
||||
readonly reasoning?: { readonly ref: PartRef; readonly placement: TurnThinkingPlacement }
|
||||
readonly retry?: { readonly attempt: number; readonly message: string; readonly next: number }
|
||||
readonly error?: { readonly interrupted: true } | { readonly interrupted: false; readonly info: TurnErrorInfo }
|
||||
}
|
||||
| { readonly type: "idle.failed"; readonly error: TurnErrorInfo }
|
||||
|
||||
export const IDLE_TURN_PHASE: TurnPhase = Object.freeze({ status: "idle" })
|
||||
|
||||
export const WORKING_TURN_PHASE: TurnPhase = Object.freeze({ status: "working" })
|
||||
|
||||
export const INTERRUPTED_TURN_PHASE: TurnPhase = Object.freeze({ status: "interrupted" })
|
||||
|
||||
export function transitionTurnPhase(state: TurnPhase, event: TurnPhaseEvent): TurnPhase {
|
||||
if (event.type === "started") return event.live ? WORKING_TURN_PHASE : IDLE_TURN_PHASE
|
||||
|
||||
if (event.type === "idle.failed") return { status: "failed", error: event.error }
|
||||
|
||||
if (event.active && event.retry) return { status: "retrying", ...event.retry }
|
||||
|
||||
if (event.error)
|
||||
return event.error.interrupted ? INTERRUPTED_TURN_PHASE : { status: "failed", error: event.error.info }
|
||||
|
||||
if (!event.active || event.session === "idle") return IDLE_TURN_PHASE
|
||||
|
||||
if (event.session === "busy" && !event.completed && event.reasoning && event.reasoning.placement !== "hidden")
|
||||
return state.status === "thinking" &&
|
||||
state.placement === event.reasoning.placement &&
|
||||
sameRef(state.ref, event.reasoning.ref)
|
||||
? state
|
||||
: { status: "thinking", ref: event.reasoning.ref, placement: event.reasoning.placement }
|
||||
|
||||
return WORKING_TURN_PHASE
|
||||
}
|
||||
|
||||
export function viewTurnPhase(state: TurnPhase) {
|
||||
const live = state.status === "working" || state.status === "thinking"
|
||||
|
||||
return {
|
||||
/** The model is producing this turn, so its content is still changing. */
|
||||
live,
|
||||
/** Settled turns keep their last text as the answer. */
|
||||
settled: state.status === "idle" || state.status === "failed" || state.status === "interrupted",
|
||||
/** The reply is not final yet, so it offers no Copy. */
|
||||
hideCopy: live || state.status === "retrying",
|
||||
separateThinkingRef: state.status === "thinking" && state.placement === "separate" ? state.ref : undefined,
|
||||
streamingReasoningRef: state.status === "thinking" ? state.ref : undefined,
|
||||
retry: state.status === "retrying" ? state : undefined,
|
||||
error: state.status === "failed" ? state.error : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export function sameTurnPhase(a: TurnPhase, b: TurnPhase) {
|
||||
if (a === b) return true
|
||||
|
||||
if (a.status === "thinking") return b.status === "thinking" && a.placement === b.placement && sameRef(a.ref, b.ref)
|
||||
|
||||
if (a.status === "retrying")
|
||||
return b.status === "retrying" && a.attempt === b.attempt && a.message === b.message && a.next === b.next
|
||||
|
||||
if (a.status === "failed")
|
||||
return (
|
||||
b.status === "failed" &&
|
||||
a.error.text === b.error.text &&
|
||||
a.error.kind === b.error.kind &&
|
||||
a.error.resetAt === b.error.resetAt
|
||||
)
|
||||
|
||||
return a.status === b.status
|
||||
}
|
||||
|
||||
export function isInterruptedError(error: { readonly type: string } | undefined) {
|
||||
const type = error?.type.toLowerCase()
|
||||
|
||||
return !!type && (type.includes("abort") || type.includes("interrupt"))
|
||||
}
|
||||
|
||||
export function sameRef(a: PartRef | undefined, b: PartRef | undefined) {
|
||||
return a === b || (!!a && !!b && a.messageID === b.messageID && a.partID === b.partID)
|
||||
}
|
||||
Reference in New Issue
Block a user