mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 05:01:03 +03:00
feat(session-ui): summarize each turn's changed files (#55064)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
Unverified
parent
34d8ded0c5
commit
81d57087a4
@@ -790,6 +790,8 @@ export const dict = {
|
||||
"settings.timeline.description.text-only": "Hide all activity.",
|
||||
"settings.timeline.description.custom": "Uses advanced settings.",
|
||||
"settings.timeline.custom": "Custom",
|
||||
"settings.timeline.row.turnDiffs.title": "Changed files",
|
||||
"settings.timeline.row.turnDiffs.description": "List the files each turn changed when it finishes",
|
||||
"settings.timeline.advanced": "Advanced",
|
||||
"settings.timeline.advanced.description": "Set placement and details for each activity category.",
|
||||
"settings.timeline.group": "Group",
|
||||
|
||||
@@ -180,6 +180,7 @@ export function createTimelineController(input: { session: TimelineSessionSource
|
||||
timelineDetail,
|
||||
pendingInputIDs,
|
||||
queuedCompactionIDs,
|
||||
turnDiffs: settings.general.showTurnDiffs,
|
||||
})
|
||||
|
||||
const [pending, setPending] = createStore({ rename: false })
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { FileDiffInfo } from "@opencode/client/promise"
|
||||
import { createRoot } from "solid-js"
|
||||
import { createTurnDiffCache } from "./turn-diffs"
|
||||
|
||||
const turn = { sessionID: "ses_a", from: "msg_open" }
|
||||
|
||||
// Every pending promise callback runs before the next macrotask.
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve))
|
||||
|
||||
const diff = { file: "src/a.ts", patch: "", additions: 1, deletions: 0, status: "modified" } satisfies FileDiffInfo
|
||||
|
||||
describe("turn diff cache", () => {
|
||||
test("loads each turn once and retries after a failure", async () => {
|
||||
const cache = createRoot(() => createTurnDiffCache())
|
||||
const failed = Promise.withResolvers<readonly FileDiffInfo[]>()
|
||||
const calls: string[] = []
|
||||
|
||||
cache.load(turn, () => (calls.push("failed"), failed.promise))
|
||||
cache.load(turn, () => (calls.push("duplicate"), Promise.resolve([diff])))
|
||||
failed.reject(new Error("offline"))
|
||||
await settle()
|
||||
expect(cache.get(turn)).toBeUndefined()
|
||||
|
||||
cache.load(turn, () => (calls.push("retry"), Promise.resolve([diff])))
|
||||
await settle()
|
||||
cache.load(turn, () => (calls.push("cached"), Promise.resolve([])))
|
||||
|
||||
expect(calls).toEqual(["failed", "retry"])
|
||||
expect(cache.get(turn)).toEqual([diff])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { FileDiffInfo } from "@opencode/client/promise"
|
||||
import type { TurnDiffInput } from "@opencode/session-ui/context"
|
||||
import { createStore } from "solid-js/store"
|
||||
|
||||
/**
|
||||
* One tab's in-memory cache of the files each finished turn changed. A finished turn's snapshots never
|
||||
* change, so each turn loads once per tab and survives the timeline remounting; closing the tab drops it.
|
||||
*/
|
||||
export function createTurnDiffCache() {
|
||||
const [diffs, setDiffs] = createStore<Record<string, readonly FileDiffInfo[] | undefined>>({})
|
||||
const loading = new Set<string>()
|
||||
const key = (input: TurnDiffInput) => `${input.sessionID}/${input.from}`
|
||||
|
||||
return {
|
||||
get: (input: TurnDiffInput) => diffs[key(input)],
|
||||
load(input: TurnDiffInput, fetch: () => Promise<readonly FileDiffInfo[]>) {
|
||||
const id = key(input)
|
||||
|
||||
if (diffs[id] || loading.has(id)) return
|
||||
loading.add(id)
|
||||
// A failed load leaves the turn unloaded, so the next request retries.
|
||||
void fetch()
|
||||
.then(
|
||||
(value) => setDiffs(id, value),
|
||||
() => undefined,
|
||||
)
|
||||
.finally(() => loading.delete(id))
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -317,6 +317,17 @@ export const SettingsGeneral: Component = () => {
|
||||
onChange={settings.general.setTimelineDetail}
|
||||
/>
|
||||
</div>
|
||||
<SettingsRow
|
||||
title={language.t("settings.timeline.row.turnDiffs.title")}
|
||||
description={language.t("settings.timeline.row.turnDiffs.description")}
|
||||
>
|
||||
<div data-action="settings-show-turn-diffs">
|
||||
<Switch
|
||||
checked={settings.general.showTurnDiffs()}
|
||||
onChange={(checked) => settings.general.setShowTurnDiffs(checked)}
|
||||
/>
|
||||
</div>
|
||||
</SettingsRow>
|
||||
</SettingsList>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -93,6 +93,7 @@ describe("settings schema", () => {
|
||||
showFileTree: false,
|
||||
timelineDetail: timelinePresets[2].value,
|
||||
showCustomAgents: false,
|
||||
showTurnDiffs: false,
|
||||
mobileTitlebarPosition: "top",
|
||||
terminalPlacement: "side",
|
||||
followUpBehavior: "steer",
|
||||
|
||||
@@ -116,6 +116,7 @@ const generalSchema = Persistence.struct({
|
||||
tools: placementOnlySchema,
|
||||
}),
|
||||
showCustomAgents: Schema.Boolean,
|
||||
showTurnDiffs: Schema.Boolean,
|
||||
mobileTitlebarPosition: Schema.Literals(["top", "bottom"]),
|
||||
// Owned by the review extension, which copies it out once; kept so settings rewrites cannot drop it first.
|
||||
mobileDiffWrap: Persistence.optional(Schema.Boolean),
|
||||
@@ -278,6 +279,7 @@ export const defaultSettings: Settings = {
|
||||
showFileTree: false,
|
||||
timelineDetail: { ...timelinePresets[2].value },
|
||||
showCustomAgents: false,
|
||||
showTurnDiffs: false,
|
||||
mobileTitlebarPosition: "top",
|
||||
terminalPlacement: "side",
|
||||
followUpBehavior: "steer",
|
||||
@@ -351,6 +353,10 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont
|
||||
setShowCustomAgents(value: boolean) {
|
||||
setStore("general", "showCustomAgents", value)
|
||||
},
|
||||
showTurnDiffs: withFallback(() => store.general?.showTurnDiffs, defaultSettings.general.showTurnDiffs),
|
||||
setShowTurnDiffs(value: boolean) {
|
||||
setStore("general", "showTurnDiffs", value)
|
||||
},
|
||||
mobileTitlebarPosition: withFallback(
|
||||
() => store.general?.mobileTitlebarPosition,
|
||||
defaultSettings.general.mobileTitlebarPosition,
|
||||
|
||||
@@ -8,10 +8,11 @@ import type { ServerConnection } from "@/runtime/server/registry"
|
||||
import { sessionHref } from "@/shell/routes/session"
|
||||
import { useData } from "@/runtime/server/current"
|
||||
import { useServerSDK } from "@/runtime/server/client"
|
||||
import { useTabs } from "@/shell/tabs/tabs"
|
||||
import { useTabs, type Tab } from "@/shell/tabs/tabs"
|
||||
import { readLocalImage } from "@/runtime/server/image"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { showToast } from "@/shell/notifications/toast"
|
||||
import { createTurnDiffCache } from "@/session/timeline/turn-diffs"
|
||||
|
||||
export function SessionUIProvider(
|
||||
props: ParentProps<{
|
||||
@@ -65,6 +66,23 @@ export function SessionUIProvider(
|
||||
|
||||
const providers = useProviders(directory)
|
||||
|
||||
// Turn diffs live in the tab's in-memory state, so they outlast timeline remounts and go when the tab closes.
|
||||
const turnDiffs = () => {
|
||||
const id = params.id
|
||||
|
||||
if (!id) return
|
||||
|
||||
const tab =
|
||||
tabs.store.find(
|
||||
(item) =>
|
||||
item.type === "session" &&
|
||||
item.server === props.server &&
|
||||
(item.sessionId === id || item.routeSessionId === id),
|
||||
) ?? ({ type: "session", server: props.server, sessionId: id } satisfies Tab)
|
||||
|
||||
return tabs.state(tab, "turnDiffs", createTurnDiffCache)
|
||||
}
|
||||
|
||||
const sessionUIData = createMemo(() => ({
|
||||
provider: providers.ready()
|
||||
? { all: providers.all(), default: providers.default(), connected: providers.connected().map((item) => item.id) }
|
||||
@@ -88,6 +106,10 @@ export function SessionUIProvider(
|
||||
sessionID={params.id}
|
||||
shellRunning={(id) => !!data.shell.get(id)}
|
||||
shellOutput={(input) => serverSDK.api.shell.output(input)}
|
||||
turnDiff={{
|
||||
get: (input) => turnDiffs()?.get(input),
|
||||
load: (input) => turnDiffs()?.load(input, () => serverSDK.api.session.diff(input)),
|
||||
}}
|
||||
onNavigateToSession={navigateToSession}
|
||||
onSessionHref={href}
|
||||
>
|
||||
|
||||
@@ -36,6 +36,17 @@ type Data = {
|
||||
}
|
||||
}
|
||||
|
||||
/** Names a finished turn by its Session and the user message that opened it. */
|
||||
export type TurnDiffInput = { sessionID: string; from: string }
|
||||
|
||||
/** The host's cache of the files each finished turn changed. */
|
||||
export type TurnDiffSource = {
|
||||
/** The turn's diffs, or undefined until they load. */
|
||||
get: (input: TurnDiffInput) => readonly FileDiffInfo[] | undefined
|
||||
/** Starts loading the turn's diffs unless they are cached or already loading. */
|
||||
load: (input: TurnDiffInput) => void
|
||||
}
|
||||
|
||||
export type NavigateToSessionFn = (sessionID: string) => void
|
||||
|
||||
export type SessionHrefFn = (sessionID: string) => string
|
||||
@@ -48,6 +59,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({
|
||||
sessionID?: string
|
||||
shellRunning?: (id: string) => boolean
|
||||
shellOutput?: (input: ShellOutputInput) => Promise<ShellOutputOutput>
|
||||
turnDiff?: TurnDiffSource
|
||||
onNavigateToSession?: NavigateToSessionFn
|
||||
onSessionHref?: SessionHrefFn
|
||||
}) => {
|
||||
@@ -65,6 +77,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({
|
||||
sessionHref: props.onSessionHref,
|
||||
shellRunning: props.shellRunning,
|
||||
shellOutput: props.shellOutput,
|
||||
turnDiff: props.turnDiff,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
@@ -62,6 +62,7 @@ export function CurrentSessionProviders(props: { document: SessionDocument; chil
|
||||
},
|
||||
session_diff: { [CURRENT_SESSION_ID]: props.document.diffs },
|
||||
}}
|
||||
turnDiff={{ get: () => props.document.diffs, load: () => {} }}
|
||||
>
|
||||
<FileComponentProvider component={File}>{props.children}</FileComponentProvider>
|
||||
</DataProvider>
|
||||
@@ -76,6 +77,7 @@ export function CurrentSessionTimelineStory(props: {
|
||||
width?: string
|
||||
shellToolDefaultOpen?: boolean
|
||||
editToolDefaultOpen?: boolean
|
||||
turnDiffs?: boolean
|
||||
}) {
|
||||
// Inline story documents rebuild their messages on every prop read, and the timeline projection keys text by identity.
|
||||
const document = createMemo(() => props.document)
|
||||
@@ -118,6 +120,7 @@ export function CurrentSessionTimelineStory(props: {
|
||||
actions={actions}
|
||||
shellToolDefaultOpen={props.shellToolDefaultOpen}
|
||||
editToolDefaultOpen={props.editToolDefaultOpen}
|
||||
turnDiffs={props.turnDiffs}
|
||||
/>
|
||||
</CurrentSessionProviders>
|
||||
</div>
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
writeFileDocument,
|
||||
} from "../storybook/current-session-fixtures"
|
||||
import { storyDocument, storyPatchFile, storyTool } from "../storybook/current-session-scenarios"
|
||||
import type { SessionDocument } from "../document"
|
||||
import { SessionTimeline } from "./session-timeline"
|
||||
import { ToolDisplay } from "../tools/tool-renderer"
|
||||
|
||||
@@ -198,6 +199,76 @@ const WrittenSource = {
|
||||
),
|
||||
}
|
||||
|
||||
// A finished turn: the step records which files changed, and the idle marker ends the turn.
|
||||
function finishedTurnDocument(files: { file: string; before: string; after: string }[]): SessionDocument {
|
||||
const document = storyDocument([
|
||||
storyTool("tool_turn_shell", "shell", "completed", { command: "bun run format" }, { output: "Formatted" }),
|
||||
])
|
||||
|
||||
const step = document.messages.at(-1)
|
||||
|
||||
if (step?.type !== "assistant") throw new Error("Expected the story document to end with a step")
|
||||
|
||||
return {
|
||||
...document,
|
||||
messages: [
|
||||
...document.messages.slice(0, -1),
|
||||
{ ...step, snapshot: { files: files.map((item) => item.file) } },
|
||||
{ id: "msg_turn_idle", type: "idle", outcome: "succeeded", time: { created: step.time.created + 400 } },
|
||||
],
|
||||
diffs: files.map((item) => {
|
||||
const lines = (text: string) => (text ? text.split("\n").length - 1 : 0)
|
||||
const changes = createTwoFilesPatch(item.file, item.file, item.before, item.after)
|
||||
|
||||
return {
|
||||
file: item.file,
|
||||
patch: changes,
|
||||
additions: item.before ? (item.after ? 1 : 0) : lines(item.after),
|
||||
deletions: item.after ? (item.before ? 1 : 0) : lines(item.before),
|
||||
status: !item.before ? "added" : !item.after ? "deleted" : "modified",
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
export const TurnChangeSummary = {
|
||||
render: () => (
|
||||
<CurrentSessionTimelineStory
|
||||
title="Turn change summary"
|
||||
description="Once the turn ends, every file it changed is summarized below it, including changes made by shell commands."
|
||||
document={finishedTurnDocument([
|
||||
{
|
||||
file: "packages/app/src/session/timeline/message-timeline.tsx",
|
||||
before: "export const before = true\n",
|
||||
after: "export const after = true\n",
|
||||
},
|
||||
{ file: "packages/app/src/session/turn-summary.ts", before: "", after: "export const summary = []\n" },
|
||||
{ file: "packages/app/src/session/legacy-summary.ts", before: "export const legacy = []\n", after: "" },
|
||||
])}
|
||||
width="860px"
|
||||
turnDiffs
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const TurnChangeSummaryOverflow = {
|
||||
render: () => (
|
||||
<CurrentSessionTimelineStory
|
||||
title="Turn change summary with many files"
|
||||
description="Past five files, the rest of the turn's changes wait behind Show all."
|
||||
document={finishedTurnDocument(
|
||||
Array.from({ length: 14 }, (_, index) => ({
|
||||
file: `src/modules/module-${index + 1}.ts`,
|
||||
before: `export const value = ${index}\n`,
|
||||
after: `export const value = ${index + 1}\n`,
|
||||
})),
|
||||
)}
|
||||
width="860px"
|
||||
turnDiffs
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
const fileScenarios = {
|
||||
repeated: RepeatedEdits,
|
||||
streaming: EditWithStreamedSibling,
|
||||
@@ -256,6 +327,7 @@ export const AppendingToolCalls = {
|
||||
export const ChangingFiles = {
|
||||
args: { scenario: "streaming" },
|
||||
argTypes: { scenario: { control: "select", options: Object.keys(fileScenarios) } },
|
||||
// SAFETY: the scenario control only offers fileScenarios keys.
|
||||
render: (args: { scenario: string }) => fileScenarios[args.scenario as keyof typeof fileScenarios].render(),
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ type Entry =
|
||||
| { type: "assistant"; message: SessionMessageAssistant }
|
||||
| { type: "notice"; message: Notice }
|
||||
| { type: "idle"; message: FailedIdle }
|
||||
| { type: "diff"; message: SessionMessageIdle; from: string; files: string[] }
|
||||
|
||||
type Content = SessionMessageAssistant["content"][number]
|
||||
|
||||
@@ -79,6 +80,7 @@ export type TimelineProjectionInput = {
|
||||
timelineDetail?: TimelineDetail
|
||||
pendingInputIDs?: ReadonlySet<string>
|
||||
queuedCompactionIDs?: readonly string[]
|
||||
turnDiffs?: boolean
|
||||
previousRows?: TimelineRow.TimelineRow[]
|
||||
}
|
||||
|
||||
@@ -95,6 +97,7 @@ export function createTimelineProjection(input: TimelineProjectionInput) {
|
||||
undefined,
|
||||
input.timelineDetail,
|
||||
input.queuedCompactionIDs,
|
||||
input.turnDiffs,
|
||||
)
|
||||
|
||||
const rows = reuseTimelineRows(input.previousRows, projection.rows)
|
||||
@@ -133,6 +136,8 @@ export function createReactiveTimelineProjection(input: {
|
||||
timelineDetail?: Accessor<TimelineDetail>
|
||||
pendingInputIDs?: Accessor<ReadonlySet<string>>
|
||||
queuedCompactionIDs?: Accessor<readonly string[]>
|
||||
/** Summarize each finished turn's changed files after it. */
|
||||
turnDiffs?: Accessor<boolean>
|
||||
}) {
|
||||
const sessionMessageByID = createMemo(
|
||||
() => new Map(input.sessionMessages().map((message) => [message.id, message] as const)),
|
||||
@@ -170,6 +175,7 @@ export function createReactiveTimelineProjection(input: {
|
||||
textVisible().get(content)!(),
|
||||
input.timelineDetail?.(),
|
||||
input.queuedCompactionIDs?.(),
|
||||
input.turnDiffs?.(),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -232,6 +238,7 @@ export namespace Timeline {
|
||||
isRenderable = renderable,
|
||||
detail?: TimelineDetail,
|
||||
queuedCompactionIDs: readonly string[] = [],
|
||||
turnDiffs = false,
|
||||
) {
|
||||
type Turn = {
|
||||
id: string
|
||||
@@ -245,6 +252,8 @@ export namespace Timeline {
|
||||
const turnByUserID = new Map<string, Turn>()
|
||||
const leading: Notice[] = []
|
||||
let current: Turn | undefined
|
||||
// Everything since the last idle marker is one turn, including prompts steered in meanwhile.
|
||||
let execution: { opener: string; turn: Turn; files: Set<string> } | undefined
|
||||
|
||||
messages.forEach((message) => {
|
||||
if (isNotice(message)) {
|
||||
@@ -270,38 +279,32 @@ export namespace Timeline {
|
||||
turnByUserID.set(message.id, turn)
|
||||
current = turn
|
||||
|
||||
// Undelivered input has not joined the turn yet.
|
||||
if (!pendingInputIDs?.has(message.id))
|
||||
execution = { opener: execution?.opener ?? message.id, turn, files: execution?.files ?? new Set() }
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (isFailedIdle(message)) {
|
||||
const last = current?.entries.at(-1)
|
||||
if (message.type === "idle") {
|
||||
appendIdle(message)
|
||||
|
||||
if (
|
||||
last?.type === "notice" &&
|
||||
last.message.type === "compaction" &&
|
||||
last.message.status === "failed" &&
|
||||
!isInterrupted(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 (current && !current.shell) {
|
||||
current.entries.push({ type: "idle", message })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const turn: Turn = { id: message.id, time: message.time, entries: [{ type: "idle", message }] }
|
||||
turns.push(turn)
|
||||
current = turn
|
||||
// The summary follows the turn's last prompt, after any failure the marker reports.
|
||||
// Sorted like the diff route's git order, so the list keeps its order when the diffs arrive.
|
||||
if (turnDiffs && execution?.files.size)
|
||||
execution.turn.entries.push({
|
||||
type: "diff",
|
||||
message,
|
||||
from: execution.opener,
|
||||
files: [...execution.files].sort(),
|
||||
})
|
||||
execution = undefined
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (message.type !== "assistant") return
|
||||
message.snapshot?.files?.forEach((file) => execution?.files.add(file))
|
||||
const existing = current?.user ? current : undefined
|
||||
|
||||
if (existing?.user) {
|
||||
@@ -322,6 +325,33 @@ export namespace Timeline {
|
||||
current = turn
|
||||
})
|
||||
|
||||
function appendIdle(message: SessionMessageIdle) {
|
||||
if (!isFailedIdle(message)) return
|
||||
const last = current?.entries.at(-1)
|
||||
|
||||
if (
|
||||
last?.type === "notice" &&
|
||||
last.message.type === "compaction" &&
|
||||
last.message.status === "failed" &&
|
||||
!isInterrupted(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 (current && !current.shell) {
|
||||
current.entries.push({ type: "idle", message })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const turn: Turn = { id: message.id, time: message.time, entries: [{ type: "idle", message }] }
|
||||
turns.push(turn)
|
||||
current = turn
|
||||
}
|
||||
|
||||
const activeMessageID =
|
||||
turns.findLast((turn) => !pendingInputIDs?.has(turn.id) || turn.entries.some((entry) => entry.type === "idle"))
|
||||
?.id ?? turns.at(-1)?.id
|
||||
@@ -339,6 +369,7 @@ export namespace Timeline {
|
||||
entry.type === "notice"
|
||||
? visibleNotice(entry.message)
|
||||
: entry.type === "idle" ||
|
||||
entry.type === "diff" ||
|
||||
!!entry.message.error ||
|
||||
!!entry.message.retry ||
|
||||
entry.message.content.some((content) => isRenderable(content, showReasoning, detail)),
|
||||
@@ -556,6 +587,19 @@ export namespace Timeline {
|
||||
}),
|
||||
)
|
||||
|
||||
return
|
||||
case "diff":
|
||||
appendAssistantSegment(assistantSegment)
|
||||
assistantSegment = []
|
||||
rows.push(
|
||||
new TimelineRow.TurnDiff({
|
||||
userMessageID: turnID,
|
||||
messageID: entry.message.id,
|
||||
from: entry.from,
|
||||
files: entry.files,
|
||||
}),
|
||||
)
|
||||
|
||||
return
|
||||
case "notice":
|
||||
if (detail?.notices.placement === "hidden" && !timelineNoticeRequired(entry.message)) return
|
||||
|
||||
@@ -1452,4 +1452,67 @@ describe("current session timeline rows", () => {
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
test("summarizes a turn's changed files after the idle marker that ends it", () => {
|
||||
const step = (id: string, files?: string[]) =>
|
||||
({
|
||||
id,
|
||||
type: "assistant",
|
||||
agent: "build",
|
||||
model: { id: "model", providerID: "provider" },
|
||||
content: [{ type: "text", text: id }],
|
||||
snapshot: files && { start: "tree_a", end: "tree_b", files },
|
||||
time: { created: 1, completed: 2 },
|
||||
}) satisfies SessionMessageAssistant
|
||||
|
||||
const idle = (id: string) => ({ id, type: "idle", outcome: "succeeded", time: { created: 1 } }) as const
|
||||
const user = (id: string) => ({ id, type: "user", text: id, time: { created: 1 } }) as const
|
||||
|
||||
const source = [
|
||||
// A steered prompt joins the running turn; the summary diffs from its opening prompt and lists
|
||||
// every path its steps recorded once, sorted.
|
||||
user("msg_open"),
|
||||
step("msg_edit", ["src/a.ts"]),
|
||||
user("msg_steer"),
|
||||
step("msg_answer", ["src/c.ts", "src/a.ts"]),
|
||||
idle("msg_idle_1"),
|
||||
// A turn that changed nothing gets no summary.
|
||||
user("msg_ask"),
|
||||
step("msg_reply", []),
|
||||
idle("msg_idle_2"),
|
||||
// Neither does a turn still running.
|
||||
user("msg_next"),
|
||||
step("msg_running", ["src/b.ts"]),
|
||||
] satisfies SessionMessageInfo[]
|
||||
|
||||
const rows = createTimelineProjection({
|
||||
sessionMessages: source,
|
||||
status: { type: "busy" },
|
||||
reasoningMode: "compact",
|
||||
turnDiffs: true,
|
||||
}).rows
|
||||
|
||||
expect(rows.filter((row) => Predicate.isTagged(row, "TurnDiff"))).toEqual([
|
||||
new TimelineRow.TurnDiff({
|
||||
userMessageID: "msg_steer",
|
||||
messageID: "msg_idle_1",
|
||||
from: "msg_open",
|
||||
files: ["src/a.ts", "src/c.ts"],
|
||||
}),
|
||||
])
|
||||
expect(rows.map(TimelineRow.key).slice(0, 6)).toEqual([
|
||||
"user-message:msg_open",
|
||||
"assistant-part:part:part:msg_edit:msg_edit:text:0",
|
||||
"turn-gap:msg_steer",
|
||||
"user-message:msg_steer",
|
||||
"assistant-part:part:part:msg_answer:msg_answer:text:0",
|
||||
"turn-diff:msg_idle_1",
|
||||
])
|
||||
// Hosts opt in, so a timeline without the setting lists no summaries.
|
||||
expect(
|
||||
Timeline.constructSessionMessageRows(source, true, { type: "busy" }).rows.some((row) =>
|
||||
Predicate.isTagged(row, "TurnDiff"),
|
||||
),
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -6,7 +6,8 @@ import type {
|
||||
} from "@opencode/client/promise"
|
||||
import { useI18n } from "@opencode/ui/context/i18n"
|
||||
import { Option, Predicate, Schema } from "effect"
|
||||
import { For, Show, createMemo, type Accessor, type JSX } from "solid-js"
|
||||
import { For, Show, createEffect, createMemo, type Accessor, type JSX } from "solid-js"
|
||||
import { DiffChanges } from "@opencode/ui/diff-changes"
|
||||
import { Dynamic } from "solid-js/web"
|
||||
import type { SessionUserActions, SessionUserAttachmentReference, SessionUserComment } from "../actions"
|
||||
import { useData } from "../context"
|
||||
@@ -25,7 +26,8 @@ import {
|
||||
SessionCompactionMessage,
|
||||
SessionCompactionQueued,
|
||||
} from "../message/message-content"
|
||||
import type { ContextGroupPart } from "../tools/tool-renderer"
|
||||
import { ToolRegistry, type ContextGroupPart } from "../tools/tool-renderer"
|
||||
import { GenericTool } from "../components/basic-tool"
|
||||
import { SessionRetry } from "../components/session-retry"
|
||||
import { SessionError } from "../components/session-error"
|
||||
import { timelineCategory, type TimelineDetail } from "./detail"
|
||||
@@ -41,6 +43,9 @@ import {
|
||||
|
||||
const emptyAssistantMessages: SessionMessageAssistant[] = []
|
||||
|
||||
// Past this many files, the rest of a turn's changes wait behind "Show all".
|
||||
const turnDiffFileLimit = 5
|
||||
|
||||
const decodeMetadataFile = Schema.decodeUnknownOption(Schema.Struct({ file: Schema.String }))
|
||||
|
||||
type Projection = ReturnType<typeof createReactiveTimelineProjection>
|
||||
@@ -704,6 +709,56 @@ export function createSessionTimelineRowRenderer(input: {
|
||||
)
|
||||
}
|
||||
|
||||
function TurnDiff(props: { row: TimelineRow.TurnDiff; onSizeChange?: () => void }) {
|
||||
const render = ToolRegistry.render("patch") ?? GenericTool
|
||||
// Until the diff loads, list the paths the turn's steps recorded, without change counts.
|
||||
const turn = () => ({ sessionID: input.sessionID(), from: props.row.from })
|
||||
const diffs = () => data.turnDiff?.get(turn())
|
||||
const paths = () => diffs()?.map((diff) => diff.file) ?? props.row.files
|
||||
const showAllKey = () => `turn-diff:${props.row.messageID}`
|
||||
const showAll = () => input.disclosure.value(showAllKey()) === true
|
||||
const limit = <T,>(items: readonly T[]) => (showAll() ? items : items.slice(0, turnDiffFileLimit))
|
||||
const overflow = () => paths().length > turnDiffFileLimit
|
||||
const fileKey = (path: string) => `turn-diff:${props.row.messageID}:file:${path}`
|
||||
|
||||
createEffect(() => data.turnDiff?.load(turn()))
|
||||
|
||||
return (
|
||||
<Show when={data.turnDiff && paths().length > 0}>
|
||||
<div data-slot="session-turn-diffs" class="flex flex-col gap-2 pt-4">
|
||||
<div class="flex h-6 min-w-0 items-center gap-2">
|
||||
<span class="text-14-medium text-text-strong tabular-nums">
|
||||
{i18n.plural("ui.sessionTurn.diffs.changed", paths().length)}
|
||||
</span>
|
||||
<DiffChanges changes={[...(diffs() ?? [])]} />
|
||||
<Show when={overflow()}>
|
||||
<button
|
||||
type="button"
|
||||
class="ml-auto text-14-regular text-text-interactive-base"
|
||||
onClick={() => input.disclosure.set(showAllKey(), !showAll())}
|
||||
>
|
||||
{showAll() ? i18n.t("ui.sessionTurn.diffs.showLess") : i18n.t("ui.sessionTurn.diffs.showAll")}
|
||||
</button>
|
||||
</Show>
|
||||
</div>
|
||||
<Dynamic
|
||||
component={render}
|
||||
tool="patch"
|
||||
input={{}}
|
||||
metadata={{ files: limit(diffs() ?? []) }}
|
||||
pendingFiles={diffs() ? undefined : limit(props.row.files)}
|
||||
status="completed"
|
||||
fileOpen={(path: string) => input.disclosure.value(fileKey(path))}
|
||||
onFileOpenChange={(path: string, open: boolean) => input.disclosure.set(fileKey(path), open)}
|
||||
deferContent
|
||||
virtualizeDiff={false}
|
||||
onContentRendered={props.onSizeChange}
|
||||
/>
|
||||
</div>
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
const render = (row: Accessor<TimelineRow.TimelineRow>, onSizeChange?: () => void) => {
|
||||
if (Predicate.isTagged(row(), "TurnGap")) return <div data-timeline-row="TurnGap" aria-hidden="true" class="h-6" />
|
||||
|
||||
@@ -898,6 +953,24 @@ export function createSessionTimelineRowRenderer(input: {
|
||||
)
|
||||
}
|
||||
|
||||
if (Predicate.isTagged(row(), "TurnDiff")) {
|
||||
const current = () => {
|
||||
const value = row()
|
||||
|
||||
if (!Predicate.isTagged(value, "TurnDiff")) throw new Error("Expected a turn-diff timeline row")
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
return (
|
||||
<Frame row={current()}>
|
||||
<div data-slot="session-turn-message-container" class={`w-full ${padding()}`}>
|
||||
<TurnDiff row={current()} onSizeChange={onSizeChange} />
|
||||
</div>
|
||||
</Frame>
|
||||
)
|
||||
}
|
||||
|
||||
if (Predicate.isTagged(row(), "Retry")) {
|
||||
const current = () => {
|
||||
const value = row()
|
||||
|
||||
@@ -16,6 +16,7 @@ export type SessionTimelineProps = {
|
||||
shellToolDefaultOpen?: boolean
|
||||
editToolDefaultOpen?: boolean
|
||||
timelineDetail?: TimelineDetail
|
||||
turnDiffs?: boolean
|
||||
class?: string
|
||||
}
|
||||
|
||||
@@ -27,6 +28,7 @@ export function SessionTimeline(props: SessionTimelineProps) {
|
||||
shellToolDefaultOpen: () => props.shellToolDefaultOpen ?? false,
|
||||
editToolDefaultOpen: () => props.editToolDefaultOpen ?? false,
|
||||
timelineDetail: props.timelineDetail && (() => props.timelineDetail!),
|
||||
turnDiffs: () => props.turnDiffs ?? false,
|
||||
})
|
||||
|
||||
const [toolOpen, setToolOpen] = createStore<Record<string, boolean | undefined>>({})
|
||||
|
||||
@@ -72,6 +72,19 @@ export namespace TimelineRow {
|
||||
inboxID: string
|
||||
}> {}
|
||||
|
||||
/**
|
||||
* The files a finished turn changed, shown once the Session goes idle. `messageID` is the
|
||||
* idle marker that ended the turn; `from` is the prompt that opened it, which names the turn
|
||||
* to the session diff route even when later prompts were steered in. `files` are the paths its
|
||||
* steps recorded, listed before the diff loads; the diff can omit a file a later step reverted.
|
||||
*/
|
||||
export class TurnDiff extends Data.TaggedClass("TurnDiff")<{
|
||||
userMessageID: string
|
||||
messageID: string
|
||||
from: string
|
||||
files: readonly string[]
|
||||
}> {}
|
||||
|
||||
/** Where the host shows the active turn's live status when undelivered input waits below it. */
|
||||
export class Activity extends Data.TaggedClass("Activity")<{
|
||||
userMessageID: string
|
||||
@@ -88,6 +101,7 @@ export namespace TimelineRow {
|
||||
| Error
|
||||
| Retry
|
||||
| CompactionQueued
|
||||
| TurnDiff
|
||||
| Activity
|
||||
|
||||
export const key: (row: TimelineRow) => string = Match.typeTags<TimelineRow>()({
|
||||
@@ -104,6 +118,7 @@ export namespace TimelineRow {
|
||||
Error: (row) => `error:${row.userMessageID}`,
|
||||
Retry: (row) => `retry:${row.userMessageID}`,
|
||||
CompactionQueued: (row) => `compaction-queued:${row.inboxID}`,
|
||||
TurnDiff: (row) => `turn-diff:${row.messageID}`,
|
||||
// One live status exists at a time; it keeps its identity when the active turn changes.
|
||||
Activity: () => "activity",
|
||||
})
|
||||
@@ -129,5 +144,6 @@ export type TimelineRowMap = {
|
||||
Retry: { userMessageID: string }
|
||||
Error: { userMessageID: string; text: string }
|
||||
CompactionQueued: { userMessageID: string; inboxID: string }
|
||||
TurnDiff: { userMessageID: string; messageID: string; from: string; files: readonly string[] }
|
||||
Activity: { userMessageID: string }
|
||||
}
|
||||
|
||||
@@ -1132,6 +1132,8 @@ export interface ToolProps {
|
||||
deferContent?: boolean
|
||||
virtualizeDiff?: boolean
|
||||
onContentRendered?: () => void
|
||||
/** Paths the patch view lists, without change counts or diffs, instead of `metadata.files`. */
|
||||
pendingFiles?: readonly string[]
|
||||
forceOpen?: boolean
|
||||
locked?: boolean
|
||||
}
|
||||
@@ -2212,7 +2214,18 @@ ToolRegistry.register({
|
||||
render(props) {
|
||||
const i18n = useI18n()
|
||||
const fileComponent = useFileComponent()
|
||||
const files = createMemo(() => patchFileGroups(props.metadata.files))
|
||||
|
||||
const files = createMemo(
|
||||
() =>
|
||||
props.pendingFiles?.map((path) => ({
|
||||
path,
|
||||
type: "update" as const,
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
views: [],
|
||||
})) ?? patchFileGroups(props.metadata.files),
|
||||
)
|
||||
|
||||
const [expanded, setExpanded] = createSignal<string[]>([])
|
||||
|
||||
const title = createMemo(() => {
|
||||
|
||||
Reference in New Issue
Block a user