mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
feat(session-ui): flat execute layout and script diffs behind full_codemode (#66509)
This commit is contained in:
parent
4769a48e5d
commit
104bda5ba3
35 changed files with 1356 additions and 58 deletions
|
|
@ -75,6 +75,8 @@ export function createTimelineController(input: {
|
|||
active: Accessor<boolean>
|
||||
/** Whether this timeline is the New timeline experiment. */
|
||||
next: boolean
|
||||
/** The server's `full_codemode` flag: without it, a script's changes neither show nor count. */
|
||||
scriptDiffs: Accessor<boolean>
|
||||
}) {
|
||||
const navigate = useNavigate()
|
||||
const sdk = useWorkspaceLocation()
|
||||
|
|
@ -213,6 +215,7 @@ export function createTimelineController(input: {
|
|||
pendingInputIDs,
|
||||
queuedCompactionIDs,
|
||||
turnDiffs: settings.general.showTurnDiffs,
|
||||
scriptDiffs: input.scriptDiffs,
|
||||
}
|
||||
|
||||
const projection = input.next
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { abort } from "@opencode/util/abort"
|
|||
import { createAnimatedPresence } from "@/runtime/animated-presence"
|
||||
import type { SessionMessageUser } from "@opencode/client/promise"
|
||||
import type { SessionUserActions } from "@opencode/session-ui/actions"
|
||||
import { useData } from "@opencode/session-ui/context"
|
||||
import { Button } from "@opencode/ui/button"
|
||||
import { Icon } from "@opencode/ui/icon"
|
||||
import { IconButton } from "@opencode/ui/icon-button"
|
||||
|
|
@ -116,10 +117,13 @@ export function MessageTimeline(props: MessageTimelineProps) {
|
|||
}
|
||||
|
||||
function MountedTimeline(props: MessageTimelineProps & { next: boolean }) {
|
||||
const data = useData()
|
||||
|
||||
const controller = createTimelineController({
|
||||
session: props.session,
|
||||
active: () => props.active !== false,
|
||||
next: props.next,
|
||||
scriptDiffs: () => data.flag("full_codemode"),
|
||||
})
|
||||
|
||||
const tail = props.follow.following() ? controller.data.projection.rows().at(-1) : undefined
|
||||
|
|
|
|||
|
|
@ -8,8 +8,11 @@ story("spaces an error between a shell result and expanded updates", async ({ mo
|
|||
const shellBox = (await shell.boundingBox())!
|
||||
const errorBox = (await error.boundingBox())!
|
||||
const updatesBox = (await updates.boundingBox())!
|
||||
// The row's line of text: its 28px click area reaches 6px above and below it.
|
||||
const updatesLine = (await updates.locator('[data-component="tool-trigger"]').first().boundingBox())!
|
||||
expect(errorBox.y - (shellBox.y + shellBox.height)).toBe(24)
|
||||
expect(updatesBox.y - (errorBox.y + errorBox.height)).toBe(8)
|
||||
// Blocks stand 16px apart, measured from one block's text to the next; a script's own changes keep 8px under it.
|
||||
expect(updatesLine.y - (errorBox.y + errorBox.height)).toBe(16)
|
||||
expect(updatesBox.x).toBe(errorBox.x)
|
||||
await updates.click()
|
||||
const notice = timeline.locator('[data-slot="session-timeline-notice"]')
|
||||
|
|
@ -17,7 +20,8 @@ story("spaces an error between a shell result and expanded updates", async ({ mo
|
|||
const expandedBox = (await updates.boundingBox())!
|
||||
expect((await notice.boundingBox())!.y - (expandedBox.y + expandedBox.height)).toBe(0)
|
||||
expect((await notice.boundingBox())!.x - expandedBox.x).toBe(24)
|
||||
expect(expandedBox.height).toBe(28)
|
||||
// The open header's click area: 6px above its line, the line, then the 16px gap to its first item.
|
||||
expect(expandedBox.height).toBe(38)
|
||||
})
|
||||
|
||||
for (const streaming of [false, true]) {
|
||||
|
|
|
|||
|
|
@ -1065,6 +1065,11 @@
|
|||
margin-top: 12px;
|
||||
}
|
||||
|
||||
/* A script's Output row, after its last change when its changes are drawn right after it, keeps the block's tight gap. */
|
||||
[data-script-changes] > [data-script-output] {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
[data-component="execute-tool-calls"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
|
@ -1205,6 +1210,32 @@
|
|||
}
|
||||
}
|
||||
|
||||
/* The flat layout (`full_codemode`): steps line up with the title, with no markers before them, and read as steps in
|
||||
the face of the timeline's titles while what they ran on stays code. Output is muted, as the title is. */
|
||||
[data-component="execute-tool-calls"][data-execute-layout="flat"] {
|
||||
[data-slot="execute-tool-call-name"] {
|
||||
font-family: var(--v2-font-family-sans);
|
||||
font-weight: 440;
|
||||
letter-spacing: -0.04px;
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call"][data-kind="output"] [data-slot="execute-tool-call-name"] {
|
||||
color: var(--v2-text-text-muted);
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call-more"],
|
||||
[data-slot="execute-tool-output"],
|
||||
[data-slot="execute-tool-error"] {
|
||||
margin-inline-start: 0;
|
||||
padding-inline-start: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* A script's title labels the steps under it, so it is muted as the timeline's other labels are. */
|
||||
[data-component="collapsible"] [data-slot="basic-tool-tool-title"][data-execute-title] {
|
||||
color: var(--v2-text-text-muted);
|
||||
}
|
||||
|
||||
[data-slot="execute-tool-call-marker"] [data-slot="icon-svg"] {
|
||||
color: inherit;
|
||||
}
|
||||
|
|
@ -1455,6 +1486,11 @@
|
|||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
/* An opened group spaces its items as the timeline spaces blocks; a script's changes stay by the script. */
|
||||
> [data-slot="context-tool-group-item"] + [data-slot="context-tool-group-item"]:not([data-script-change]) {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
[data-slot="context-tool-group-item"] {
|
||||
min-width: 0;
|
||||
min-height: 28px;
|
||||
|
|
@ -2169,3 +2205,59 @@
|
|||
border-color: var(--v2-border-border-base);
|
||||
color: var(--v2-text-text-faint);
|
||||
}
|
||||
|
||||
/* In the current timeline, as in the New timeline, a block is as tall as its text, so the gaps between blocks are the
|
||||
gaps that show and every pair of blocks stands the same 16px apart. A row's 28px click area stays: 6px of padding
|
||||
above and below, taken back by margins of the same size. An open row keeps its header's room above its content. */
|
||||
[data-timeline-row="AssistantPart"]:not([data-timeline="next"]) {
|
||||
[data-component="collapsible"] > [data-slot="collapsible-trigger"] {
|
||||
box-sizing: border-box;
|
||||
height: calc(var(--line-height-compact) + 12px);
|
||||
padding-block: 6px;
|
||||
margin-block: -6px;
|
||||
}
|
||||
|
||||
[data-component="collapsible"] > [data-slot="collapsible-trigger"]:is([aria-expanded="true"], [data-locked]) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
/* An open group's header stands as far above its first item as blocks stand apart. */
|
||||
[data-component="collapsed-tool-group"]
|
||||
> [data-component="collapsible"]
|
||||
> [data-slot="collapsible-trigger"][aria-expanded="true"] {
|
||||
height: calc(var(--line-height-compact) + 22px);
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
|
||||
[data-component="context-tool-group-list"] [data-slot="context-tool-group-item"] {
|
||||
min-height: var(--line-height-compact);
|
||||
}
|
||||
|
||||
/* A row's action stays centred on its click area, which reaches 6px above the row, without making the row taller. */
|
||||
[data-component="collapsible"] > [data-slot="basic-tool-action"] {
|
||||
margin-top: -4px;
|
||||
}
|
||||
|
||||
/* The flat layout (`full_codemode`): a script's title's text sits above its first call's text as far as one call's
|
||||
text sits above the next, as in the New timeline. */
|
||||
[data-component="collapsible"].tool-collapsible:has(
|
||||
> [data-slot="collapsible-content"] > [data-component="execute-tool-calls"][data-execute-layout="flat"]
|
||||
) {
|
||||
row-gap: 0;
|
||||
|
||||
> [data-slot="collapsible-trigger"][data-locked] {
|
||||
--execute-title-gap: calc(6px + (var(--line-height-base) - var(--line-height-compact)) / 2);
|
||||
padding-bottom: var(--execute-title-gap);
|
||||
height: calc(var(--line-height-compact) + 6px + var(--execute-title-gap));
|
||||
|
||||
[data-slot="basic-tool-tool-info"] {
|
||||
line-height: var(--line-height-compact);
|
||||
}
|
||||
}
|
||||
|
||||
/* The title's row holds the gap below its text, so the View code button sits at its top, centred on the text. */
|
||||
> [data-slot="basic-tool-action"] {
|
||||
align-self: flex-start;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
168
packages/session-ui/src/storybook/codemode-snapshots/index.ts
Normal file
168
packages/session-ui/src/storybook/codemode-snapshots/index.ts
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
import type { SessionMessageInfo } from "@opencode/client/promise"
|
||||
import type { SessionDocument } from "../../document"
|
||||
|
||||
/**
|
||||
* Code Mode `execute` parts captured from real core and server runs (origin/dev 7b8a065e29, and b6973f1b7b for
|
||||
* `interleaved`; opencode-drive with its simulated model). Each scenario holds `GET /api/session/:id/message` as
|
||||
* returned (newest first) and the tool part as the client store held it after each event that changed it. The drive run
|
||||
* directory is shortened to `/repo`, and the 300 KB string literal in `large-patch`'s script is replaced by the
|
||||
* expression that builds it.
|
||||
*/
|
||||
export type CodeModeToolPart = Extract<
|
||||
Extract<SessionMessageInfo, { type: "assistant" }>["content"][number],
|
||||
{ type: "tool" }
|
||||
>
|
||||
|
||||
export type CodeModeState = {
|
||||
file: string
|
||||
/** `called`, `first-progress`, `progress`, `files-N` or `final`. */
|
||||
reason: string
|
||||
at: number
|
||||
eventIndex: number
|
||||
part: CodeModeToolPart
|
||||
}
|
||||
|
||||
type Capture = {
|
||||
session: { id: string; title: string; directory: string; time: { created: number; updated: number } }
|
||||
messages: { data: SessionMessageInfo[]; cursor?: unknown }
|
||||
states: CodeModeState[]
|
||||
}
|
||||
|
||||
const captures = new Map(
|
||||
Object.entries(import.meta.glob<Capture>("./*.json", { eager: true, import: "default" })).map(([path, capture]) => [
|
||||
path.slice(2, -".json".length),
|
||||
capture,
|
||||
]),
|
||||
)
|
||||
|
||||
export const codeModeScenarios = [
|
||||
{ name: "running", description: "Sleeps between writes, so files grow 1, 2, 3 while it runs and 4 at the end." },
|
||||
{
|
||||
name: "interleaved",
|
||||
description: "Ten rounds of a thought and a script in one turn: reads, shells, edits, a failed read, a delete.",
|
||||
},
|
||||
{ name: "edits-patch", description: "Two patches to one file, a Bun write and a delete. app.ts is listed twice." },
|
||||
{ name: "edits-editwrite", description: "Inner edit and write calls. Too fast for files to show before the final." },
|
||||
{ name: "appends", description: "Writer flushes, one entry each with no patch, and a binary logo.png." },
|
||||
{ name: "many-calls", description: "85 inner reads, past the toolCalls display cap." },
|
||||
{ name: "errors", description: "A caught failing read, then a write and an edit before the script throws." },
|
||||
{ name: "interrupted", description: "Interrupted during a sleep. The error part keeps the last progress metadata." },
|
||||
{ name: "backgrounded", description: "background: true. The final part has only jobID; the result comes later." },
|
||||
{ name: "timeout-bg", description: "timeout: 1500 moves the script to the background partway through." },
|
||||
{ name: "large-patch", description: "A 6000-line write over the 200 KB budget: counts but no patch." },
|
||||
{ name: "shell-truncated", description: "An inner shell with truncated output, visible only in the returned value." },
|
||||
{ name: "direct", description: "Direct edit and write tools with Code Mode off. A direct write has no files." },
|
||||
{ name: "direct-patch", description: "Two direct patch calls, each with metadata.files." },
|
||||
] as const
|
||||
|
||||
export type CodeModeScenario = (typeof codeModeScenarios)[number]["name"]
|
||||
|
||||
function capture(name: CodeModeScenario) {
|
||||
const found = captures.get(name)
|
||||
|
||||
if (!found) throw new Error(`No captured Code Mode scenario ${name}`)
|
||||
|
||||
return found
|
||||
}
|
||||
|
||||
export const codeModeSession = (name: CodeModeScenario) => capture(name).session
|
||||
|
||||
/** The session's messages in time order. */
|
||||
export const codeModeMessages = (name: CodeModeScenario) => [...capture(name).messages.data].reverse()
|
||||
|
||||
export const codeModeStates = (name: CodeModeScenario) => capture(name).states
|
||||
|
||||
/**
|
||||
* The session as the timeline reads it. With a state file the session is cut at that moment: messages after the
|
||||
* part's assistant message are dropped, the part is the client-store snapshot, and later content in that message is
|
||||
* removed. While the part is running, the message is still open. `now` moves every timestamp so that moment is now, which keeps running durations realistic.
|
||||
*/
|
||||
export function codeModeDocument(
|
||||
name: CodeModeScenario,
|
||||
stateFile?: string,
|
||||
options: { now?: number } = {},
|
||||
): SessionDocument {
|
||||
const session = capture(name).session
|
||||
let list = codeModeMessages(name)
|
||||
let busy = false
|
||||
let moment = Math.max(...list.map((message) => message.time.created))
|
||||
|
||||
if (stateFile) {
|
||||
const state = codeModeStates(name).find((item) => item.file === stateFile || item.file.startsWith(stateFile))
|
||||
|
||||
if (!state) throw new Error(`No state ${stateFile} in ${name}`)
|
||||
|
||||
const at = list.findIndex(
|
||||
(message) =>
|
||||
message.type === "assistant" &&
|
||||
message.content.some((part) => part.type === "tool" && part.id === state.part.id),
|
||||
)
|
||||
|
||||
// SAFETY: `at` is the assistant message that holds the part, found just above.
|
||||
const message = structuredClone(list[at]) as Extract<SessionMessageInfo, { type: "assistant" }>
|
||||
const index = message.content.findIndex((part) => part.type === "tool" && part.id === state.part.id)
|
||||
|
||||
message.content = [...message.content.slice(0, index), structuredClone(state.part)]
|
||||
busy = state.part.state.status === "running" || state.part.state.status === "streaming"
|
||||
|
||||
// What the end of the step sets had not happened yet. load.ts keeps `error`, which drew an interrupted turn
|
||||
// while the script was still running.
|
||||
if (busy) {
|
||||
delete message.time.completed
|
||||
delete message.finish
|
||||
delete message.rawFinish
|
||||
delete message.error
|
||||
}
|
||||
|
||||
list = [...list.slice(0, at), message]
|
||||
moment = state.at
|
||||
}
|
||||
|
||||
const messages = options.now === undefined ? list : shiftTimes(list, options.now - moment)
|
||||
|
||||
return {
|
||||
sessionID: session.id,
|
||||
messages,
|
||||
status: busy ? { type: "busy" } : { type: "idle" },
|
||||
diffs: [],
|
||||
}
|
||||
}
|
||||
|
||||
function shiftTimes(messages: SessionMessageInfo[], delta: number): SessionMessageInfo[] {
|
||||
return messages.map((message) => {
|
||||
if (message.type !== "assistant") return { ...message, time: shift(message.time, delta) }
|
||||
|
||||
return {
|
||||
...message,
|
||||
time: shift(message.time, delta),
|
||||
content: message.content.map((part) =>
|
||||
part.type === "tool" ? { ...part, time: shift(part.time, delta) } : part,
|
||||
),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function shift<T extends object>(time: T, delta: number): T {
|
||||
// SAFETY: every field of a message's or a tool part's `time` is epoch milliseconds.
|
||||
return Object.fromEntries(Object.entries(time).map(([key, value]) => [key, (value as number) + delta])) as T
|
||||
}
|
||||
|
||||
/** The `execute` metadata fields this capture holds, as `core/src/codemode/tool.ts` writes them. */
|
||||
export type CodeModeMetadata = {
|
||||
toolCalls?: { tool: string; status: string }[]
|
||||
files?: { file: string; status?: string; additions?: number; deletions?: number; patch?: string }[]
|
||||
background?: boolean
|
||||
jobID?: string
|
||||
error?: boolean
|
||||
truncated?: boolean
|
||||
}
|
||||
|
||||
export function codeModeMetadata(part: CodeModeToolPart): CodeModeMetadata {
|
||||
const state = part.state
|
||||
|
||||
if (state.status !== "running" && state.status !== "completed" && state.status !== "error") return {}
|
||||
|
||||
// SAFETY: the fixtures are the captured parts, whose metadata is Code Mode's output schema (tool.ts:47-52) or a
|
||||
// direct edit or patch part's `files`.
|
||||
return (state.metadata ?? {}) as CodeModeMetadata
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1 @@
|
|||
{"session":{"id":"ses_decc99c70ffe1L2Bf3ntn9k06N","title":"shell-truncated","directory":"/repo","time":{"created":1795618661264,"updated":1795618661264}},"messages":{"data":[{"id":"msg_2133663e3001oAgJBx2K3crHbF","time":{"created":1795618661347},"type":"idle","outcome":"succeeded"},{"id":"msg_2133663d2001Ztdwi7YshvOm8s","time":{"created":1795618661332,"firstToken":1795618661338,"streamed":1795618661343,"completed":1795618661344},"type":"assistant","agent":"build","model":{"id":"claude-opus-5-5","providerID":"simulation","variant":"default"},"content":[{"type":"text","text":"Done shell-truncated (1)."}],"finish":"stop","rawFinish":"stop","cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}}},{"id":"msg_2133663a2001mJlt8efcsxDvq2","time":{"created":1795618661285,"firstToken":1795618661292,"streamed":1795618661302,"completed":1795618661322},"type":"assistant","agent":"build","model":{"id":"claude-opus-5-5","providerID":"simulation","variant":"default"},"content":[{"type":"text","text":"Running shell-truncated."},{"type":"tool","id":"call_shell_truncated","name":"execute","executed":false,"state":{"status":"completed","input":{"code":"const r = await tools.shell({ command: 'seq 1 3000' })\nreturn { truncated: r.truncated, outputPath: r.outputPath, exit: r.exitCode }"},"content":[{"type":"text","text":"{\"outputPath\":\"/repo/logs/opencode/shell/4bceb1d1c52a253f8e4d7cb1b9f5ee8dcc169637/sh_2133663be001EYWRQ8LYgYWO3g.out\",\"exit\":0}"}],"metadata":{"toolCalls":[{"tool":"shell","status":"completed","input":{"command":"seq 1 3000"}}],"truncated":false}},"time":{"created":1795618661296,"ran":1795618661300,"completed":1795618661320}}],"finish":"tool-calls","rawFinish":"tool_calls","cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}}},{"id":"msg_213366394001Z9MLIvHrzYNFtK","time":{"created":1795618661278},"text":"SCN:shell-truncated please","type":"user"}],"cursor":{"previous":"eyJpZCI6Im1zZ18yMTMzNjYzZTMwMDFvQWdKQngySzNjckhiRiIsIm9yZGVyIjoiZGVzYyIsImRpcmVjdGlvbiI6InByZXZpb3VzIn0","next":"eyJpZCI6Im1zZ18yMTMzNjYzOTQwMDFaOU1MSXZIcnpZTkZ0SyIsIm9yZGVyIjoiZGVzYyIsImRpcmVjdGlvbiI6Im5leHQifQ"}},"states":[{"file":"00-execute-ll_truncated-called.json","reason":"called","at":1795618661300,"eventIndex":11,"part":{"type":"tool","id":"call_shell_truncated","name":"execute","time":{"created":1795618661296,"ran":1795618661300},"state":{"status":"running","input":{"code":"const r = await tools.shell({ command: 'seq 1 3000' })\nreturn { truncated: r.truncated, outputPath: r.outputPath, exit: r.exitCode }"},"metadata":{}},"executed":false}},{"file":"01-execute-ll_truncated-first-progress.json","reason":"first-progress","at":1795618661304,"eventIndex":14,"part":{"type":"tool","id":"call_shell_truncated","name":"execute","time":{"created":1795618661296,"ran":1795618661300},"state":{"status":"running","input":{"code":"const r = await tools.shell({ command: 'seq 1 3000' })\nreturn { truncated: r.truncated, outputPath: r.outputPath, exit: r.exitCode }"},"metadata":{"background":true}},"executed":false}},{"file":"02-execute-ll_truncated-progress.json","reason":"progress","at":1795618661308,"eventIndex":15,"part":{"type":"tool","id":"call_shell_truncated","name":"execute","time":{"created":1795618661296,"ran":1795618661300},"state":{"status":"running","input":{"code":"const r = await tools.shell({ command: 'seq 1 3000' })\nreturn { truncated: r.truncated, outputPath: r.outputPath, exit: r.exitCode }"},"metadata":{"toolCalls":[{"tool":"shell","status":"running","input":{"command":"seq 1 3000"}}],"background":true}},"executed":false}},{"file":"03-execute-ll_truncated-final.json","reason":"final","at":1795618661320,"eventIndex":18,"part":{"type":"tool","id":"call_shell_truncated","name":"execute","time":{"created":1795618661296,"ran":1795618661300,"completed":1795618661320},"state":{"status":"completed","input":{"code":"const r = await tools.shell({ command: 'seq 1 3000' })\nreturn { truncated: r.truncated, outputPath: r.outputPath, exit: r.exitCode }"},"metadata":{"toolCalls":[{"tool":"shell","status":"completed","input":{"command":"seq 1 3000"}}],"truncated":false},"content":[{"type":"text","text":"{\"outputPath\":\"/repo/logs/opencode/shell/4bceb1d1c52a253f8e4d7cb1b9f5ee8dcc169637/sh_2133663be001EYWRQ8LYgYWO3g.out\",\"exit\":0}"}]},"executed":false}}]}
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -11,14 +11,19 @@ import { CURRENT_SESSION_ID, STORY_TIME } from "./current-session-fixtures"
|
|||
|
||||
export function CurrentSessionProviders(props: {
|
||||
document: SessionDocument
|
||||
/** The session's directory, which paths in the timeline are shown relative to. */
|
||||
directory?: string
|
||||
/** The location's resolved feature flags, as the app passes them. */
|
||||
flags?: Readonly<Record<string, boolean>>
|
||||
readMedia?: ReadMediaUrlFn
|
||||
turnDiff?: TurnDiffSource
|
||||
children: JSX.Element
|
||||
}) {
|
||||
return (
|
||||
<DataProvider
|
||||
directory="C:/workspaces/opencode"
|
||||
directory={props.directory ?? "C:/workspaces/opencode"}
|
||||
sessionID={props.document.sessionID}
|
||||
flags={props.flags}
|
||||
readMedia={props.readMedia}
|
||||
data={{
|
||||
agent: [
|
||||
|
|
|
|||
|
|
@ -110,6 +110,8 @@ export function createNextTimelineProjection(input: {
|
|||
queuedCompactionIDs?: Accessor<readonly string[]>
|
||||
/** Summarize each finished turn's changed files after it. */
|
||||
turnDiffs?: Accessor<boolean>
|
||||
/** The server's `full_codemode` flag: without it, a script's changes neither show nor count. */
|
||||
scriptDiffs?: Accessor<boolean>
|
||||
}) {
|
||||
const sessionMessageByID = createMemo(
|
||||
() => new Map(input.sessionMessages().map((message) => [message.id, message] as const)),
|
||||
|
|
@ -141,7 +143,7 @@ export function createNextTimelineProjection(input: {
|
|||
)
|
||||
|
||||
const textVisible = createMemo(() => new Map<Content, Accessor<boolean>>(textParts()))
|
||||
const factOf = placeFacts(input.sessionMessages)
|
||||
const factOf = placeFacts(input.sessionMessages, input.scriptDiffs)
|
||||
|
||||
const projection = createMemo(() => {
|
||||
const detail = input.timelineDetail()
|
||||
|
|
|
|||
|
|
@ -31,10 +31,19 @@ import { useData } from "../context"
|
|||
import { useSources } from "../context/sources"
|
||||
import { turnSources } from "../sources/sources"
|
||||
import { SessionReadToolGroup, SessionUserMessage } from "../message/current-message"
|
||||
import { FileChangeRuns, fileRuns, runDisclosureKey, ScriptChanges, taskAgentName } from "../tools/tool-renderer"
|
||||
import {
|
||||
FileChangeRuns,
|
||||
fileRuns,
|
||||
runDisclosureKey,
|
||||
ScriptChanges,
|
||||
ScriptOutputProvider,
|
||||
taskAgentName,
|
||||
type ScriptOutputPlacement,
|
||||
} from "../tools/tool-renderer"
|
||||
import { SessionRetry } from "../components/session-retry"
|
||||
import { SessionError } from "../components/session-error"
|
||||
import type { TimelineDetail } from "../timeline/detail"
|
||||
import { scriptOutputLayout } from "../timeline/script-output"
|
||||
import { TimelineRow, type PartRef } from "../timeline/timeline-row"
|
||||
import { userMessageRuns, userRunSpring } from "../timeline/user-runs"
|
||||
import { IDLE_TURN_PHASE, sameRef, viewTurnPhase } from "../timeline/turn-phase-machine"
|
||||
|
|
@ -787,10 +796,22 @@ export function createNextTimelineRowRenderer(input: {
|
|||
|
||||
// Each row's only space is the gap below it, which sets the row below apart. A message joining the user's message
|
||||
// above sits its run's 4 px below it instead, which its turn gap springs to.
|
||||
const following = createMemo(() => {
|
||||
const rows = input.projection.rows()
|
||||
|
||||
return new Map(rows.map((row, index) => [TimelineRow.key(row), rows[index + 1]] as const))
|
||||
})
|
||||
|
||||
// Blocks stand a step further apart than a script stands from its own changes, which keep the small gap.
|
||||
const gap = (row: TimelineRow.TimelineRow) => {
|
||||
if (Predicate.isTagged(row, "TurnGap") && runs().get(row.userMessageID)?.above) return undefined
|
||||
const value = gaps().get(TimelineRow.key(row))
|
||||
const next = following().get(TimelineRow.key(row))
|
||||
|
||||
return gaps().get(TimelineRow.key(row))
|
||||
if (value !== "s" || !Predicate.isTagged(row, "AssistantPart") || (next && TimelineRow.scriptChanges(next)))
|
||||
return value
|
||||
|
||||
return "m"
|
||||
}
|
||||
|
||||
const Frame = (props: { row: FramedTimelineRow; grow?: boolean; children: JSX.Element }) => (
|
||||
|
|
@ -1601,11 +1622,23 @@ export function createNextTimelineRowRenderer(input: {
|
|||
)
|
||||
}
|
||||
|
||||
// Where each script's Output row goes, from the rows: after its changes when they are drawn right after it.
|
||||
const scriptOutput = createMemo(() =>
|
||||
scriptOutputLayout(input.projection.rows(), input.projection.messageByID(), data.flag("full_codemode")),
|
||||
)
|
||||
|
||||
const scriptPlacement: ScriptOutputPlacement = {
|
||||
afterChanges: (partID) => scriptOutput().afterChanges.has(partID),
|
||||
outputAfter: (fileID) => scriptOutput().outputAfter.get(fileID),
|
||||
}
|
||||
|
||||
function Row(props: { row: Accessor<TimelineRow.TimelineRow>; onSizeChange?: () => void }) {
|
||||
return (
|
||||
<Show when={TimelineRow.key(props.row())} keyed>
|
||||
{(_key) => render(props.row, props.onSizeChange)}
|
||||
</Show>
|
||||
<ScriptOutputProvider value={scriptPlacement}>
|
||||
<Show when={TimelineRow.key(props.row())} keyed>
|
||||
{(_key) => render(props.row, props.onSizeChange)}
|
||||
</Show>
|
||||
</ScriptOutputProvider>
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,654 @@
|
|||
import { Button } from "@opencode/ui/button"
|
||||
import { Collapsible } from "@opencode/ui/collapsible"
|
||||
import { SegmentedControl, SegmentedControlItem } from "@opencode/ui/segmented-control"
|
||||
import { TextShimmer } from "@opencode/ui/text-shimmer"
|
||||
import { Predicate } from "effect"
|
||||
import { For, Show, createEffect, createMemo, createSignal, onCleanup, onMount, type JSX } from "solid-js"
|
||||
import { BackgroundMoveHint } from "../../../../app/src/session/timeline/message-timeline"
|
||||
import { createStore, reconcile } from "solid-js/store"
|
||||
import type { SessionDocument } from "../../document"
|
||||
import {
|
||||
codeModeDocument,
|
||||
codeModeMetadata,
|
||||
codeModeScenarios,
|
||||
codeModeSession,
|
||||
codeModeStates,
|
||||
type CodeModeScenario,
|
||||
type CodeModeState,
|
||||
} from "../../storybook/codemode-snapshots"
|
||||
import { CurrentSessionProviders } from "../../storybook/current-session-story"
|
||||
import { timelinePresets, type TimelineDetail } from "../../timeline/detail"
|
||||
import { Timeline, createReactiveTimelineProjection, type ReasoningMode } from "../../timeline/projection"
|
||||
import { SessionTimeline } from "../../timeline/session-timeline"
|
||||
import { createNextTimelineProjection } from "../projection"
|
||||
import { laneGap } from "../spacing"
|
||||
import { timelineStatus } from "../status"
|
||||
import { StatusLane } from "../status-line"
|
||||
import { NextSessionTimeline } from "./session-timeline"
|
||||
|
||||
/**
|
||||
* Code Mode `execute` parts captured from real runs, drawn by the real timelines at each state the client store held:
|
||||
* called, first progress, progress, each time the files list grew, and final. The last step is the whole session,
|
||||
* with what came after the call. Play steps through them once a second, as the live updates arrived.
|
||||
*
|
||||
* The controls live in the address: `?id=codemode-captured-states--captured&scenario=running&step=3&metadata=open`.
|
||||
* Left and right arrows step too.
|
||||
*/
|
||||
export default {
|
||||
title: "Code Mode/Captured states",
|
||||
id: "codemode-captured-states",
|
||||
parameters: { layout: "fullscreen" },
|
||||
}
|
||||
|
||||
const timelines = [
|
||||
{ id: "old", label: "Old" },
|
||||
{ id: "new", label: "New" },
|
||||
{ id: "both", label: "Side by side" },
|
||||
] as const
|
||||
|
||||
const presetLabels = {
|
||||
everything: "Everything",
|
||||
detailed: "Detailed",
|
||||
compact: "Compact",
|
||||
quiet: "Quiet",
|
||||
"text-only": "Messages only",
|
||||
} as const
|
||||
|
||||
// The control's default is a fixed 232px of equal segments, too narrow for these labels.
|
||||
const segments = { width: "auto" }
|
||||
|
||||
const segment = { flex: "none" }
|
||||
|
||||
type Step = { label: string; file?: string; state: CodeModeState }
|
||||
|
||||
const names = codeModeScenarios.map((scenario) => scenario.name)
|
||||
|
||||
// Each state of the scenario's tool parts, then the whole session.
|
||||
const steps = (name: CodeModeScenario): Step[] => {
|
||||
const states = codeModeStates(name)
|
||||
const calls = [...new Map(states.map((state) => [state.part.id, state.part.name])).entries()]
|
||||
|
||||
// A session of several calls labels each state with its call, numbered where a tool runs more than once.
|
||||
const call = (state: CodeModeState) => {
|
||||
const named = calls.filter(([, tool]) => tool === state.part.name)
|
||||
|
||||
if (named.length < 2) return state.part.name
|
||||
|
||||
return `${state.part.name} ${named.findIndex(([id]) => id === state.part.id) + 1}`
|
||||
}
|
||||
|
||||
return [
|
||||
...states.map((state) => ({
|
||||
label: calls.length > 1 ? `${call(state)} · ${state.reason}` : state.reason,
|
||||
file: state.file,
|
||||
state,
|
||||
})),
|
||||
{ label: "session end", state: states.at(-1)! },
|
||||
]
|
||||
}
|
||||
|
||||
export const Captured = {
|
||||
render: () => {
|
||||
const query = new URLSearchParams(location.search)
|
||||
|
||||
const [state, setState] = createStore({
|
||||
scenario: names.find((name) => name === query.get("scenario")) ?? names[0],
|
||||
step: query.has("step") ? Number(query.get("step")) : Number.MAX_SAFE_INTEGER,
|
||||
timeline: timelines.find((item) => item.id === query.get("timeline"))?.id ?? timelines[2].id,
|
||||
preset: timelinePresets.find((item) => item.id === query.get("preset"))?.id ?? timelinePresets[1].id,
|
||||
// The server's `full_codemode` flag, which draws the flat execute layout.
|
||||
flat: query.get("flag") !== "off",
|
||||
playing: false,
|
||||
metadata: query.get("metadata") === "open",
|
||||
})
|
||||
|
||||
const list = createMemo(() => steps(state.scenario))
|
||||
const index = createMemo(() => Math.max(0, Math.min(state.step, list().length - 1)))
|
||||
const step = createMemo(() => list()[index()]!)
|
||||
const last = () => index() === list().length - 1
|
||||
const detail = createMemo(() => timelinePresets.find((preset) => preset.id === state.preset)!.value)
|
||||
const session = createMemo(() => codeModeSession(state.scenario))
|
||||
|
||||
// One document that the store reconciles, so each step updates the rows the way a live progress event does.
|
||||
const [view, setView] = createStore<{ document: SessionDocument }>({
|
||||
document: codeModeDocument(state.scenario, step().file, { now: Date.now() }),
|
||||
})
|
||||
|
||||
createEffect(() =>
|
||||
setView("document", reconcile(codeModeDocument(state.scenario, step().file, { now: Date.now() }))),
|
||||
)
|
||||
|
||||
createEffect(() => {
|
||||
const address = new URLSearchParams(location.search)
|
||||
|
||||
address.set("scenario", state.scenario)
|
||||
address.set("step", String(index()))
|
||||
address.set("timeline", state.timeline)
|
||||
address.set("preset", state.preset)
|
||||
|
||||
if (state.flat) address.delete("flag")
|
||||
else address.set("flag", "off")
|
||||
|
||||
if (state.metadata) address.set("metadata", "open")
|
||||
else address.delete("metadata")
|
||||
|
||||
history.replaceState(history.state, "", `?${address}`)
|
||||
})
|
||||
|
||||
createEffect(() => {
|
||||
if (!state.playing) return
|
||||
|
||||
const timer = setInterval(() => {
|
||||
if (last()) return setState("playing", false)
|
||||
setState("step", index() + 1)
|
||||
}, 1_000)
|
||||
|
||||
onCleanup(() => clearInterval(timer))
|
||||
})
|
||||
|
||||
const go = (next: number) => setState({ step: Math.max(0, Math.min(next, list().length - 1)), playing: false })
|
||||
|
||||
const play = () => {
|
||||
if (state.playing) return setState("playing", false)
|
||||
setState({ step: last() ? 0 : index(), playing: true })
|
||||
}
|
||||
|
||||
const pick = (scenario: CodeModeScenario) => setState({ scenario, step: Number.MAX_SAFE_INTEGER, playing: false })
|
||||
|
||||
const keys = (event: KeyboardEvent) => {
|
||||
if (event.target instanceof HTMLElement && event.target.closest("input, textarea, select")) return
|
||||
|
||||
if (event.key === "ArrowRight") go(index() + 1)
|
||||
else if (event.key === "ArrowLeft") go(index() - 1)
|
||||
else return
|
||||
|
||||
event.preventDefault()
|
||||
}
|
||||
|
||||
onMount(() => window.addEventListener("keydown", keys))
|
||||
onCleanup(() => window.removeEventListener("keydown", keys))
|
||||
|
||||
// As MessageTimeline lays out a session: rows the width of the session column, then the status lane below them.
|
||||
const pane = (next: boolean) => (
|
||||
<div class="w-full py-6 md:mx-auto md:max-w-session">
|
||||
<CurrentSessionProviders
|
||||
document={view.document}
|
||||
directory={session().directory}
|
||||
flags={{ full_codemode: state.flat }}
|
||||
>
|
||||
<Show
|
||||
when={next}
|
||||
fallback={
|
||||
<SessionTimeline
|
||||
document={view.document}
|
||||
timelineDetail={detail()}
|
||||
turnDiffs={false}
|
||||
{...sessionTimelineSettings(detail())}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<NextSessionTimeline document={view.document} timelineDetail={detail()} />
|
||||
</Show>
|
||||
</CurrentSessionProviders>
|
||||
<SessionStatusLane document={view.document} timelineDetail={detail()} next={next} flat={state.flat} />
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div class="flex h-screen min-h-0 bg-v2-background-bg-base text-v2-text-text-base">
|
||||
<nav
|
||||
aria-label="Scenario"
|
||||
class="flex w-64 shrink-0 flex-col gap-0.5 overflow-y-auto border-r border-v2-border-border-base p-2"
|
||||
>
|
||||
<div class="px-2 pt-1 pb-2">
|
||||
<div class="text-14-medium">Code Mode</div>
|
||||
<div class="text-12-regular text-v2-text-text-muted">Captured on dev 7b8a065e29 and b6973f1b7b</div>
|
||||
</div>
|
||||
<For each={codeModeScenarios}>
|
||||
{(scenario) => (
|
||||
<button
|
||||
type="button"
|
||||
aria-current={state.scenario === scenario.name ? "true" : undefined}
|
||||
class="flex flex-col gap-0.5 rounded-md px-2 py-1.5 text-left hover:bg-v2-overlay-simple-overlay-hover"
|
||||
classList={{ "bg-v2-background-bg-layer-02": state.scenario === scenario.name }}
|
||||
onClick={() => pick(scenario.name)}
|
||||
>
|
||||
<span class="font-mono text-13-regular">{scenario.name}</span>
|
||||
<span class="text-12-regular text-v2-text-text-muted">{scenario.description}</span>
|
||||
</button>
|
||||
)}
|
||||
</For>
|
||||
</nav>
|
||||
<div class="flex min-w-0 flex-1 flex-col">
|
||||
<div class="flex flex-wrap items-center gap-x-5 gap-y-2 border-b border-v2-border-border-base px-4 py-2 text-13-regular">
|
||||
<Labeled label="Timeline">
|
||||
<SegmentedControl
|
||||
aria-label="Timeline"
|
||||
style={segments}
|
||||
value={state.timeline}
|
||||
onChange={(value) => {
|
||||
const item = timelines.find((timeline) => timeline.id === value)
|
||||
|
||||
if (item) setState("timeline", item.id)
|
||||
}}
|
||||
>
|
||||
<For each={timelines}>
|
||||
{(item) => (
|
||||
<SegmentedControlItem value={item.id} style={segment}>
|
||||
{item.label}
|
||||
</SegmentedControlItem>
|
||||
)}
|
||||
</For>
|
||||
</SegmentedControl>
|
||||
</Labeled>
|
||||
<Labeled label="Detail">
|
||||
<SegmentedControl
|
||||
aria-label="Detail"
|
||||
style={segments}
|
||||
value={state.preset}
|
||||
onChange={(value) => {
|
||||
const preset = timelinePresets.find((item) => item.id === value)
|
||||
|
||||
if (preset) setState("preset", preset.id)
|
||||
}}
|
||||
>
|
||||
<For each={timelinePresets}>
|
||||
{(preset) => (
|
||||
<SegmentedControlItem value={preset.id} style={segment}>
|
||||
{presetLabels[preset.id]}
|
||||
</SegmentedControlItem>
|
||||
)}
|
||||
</For>
|
||||
</SegmentedControl>
|
||||
</Labeled>
|
||||
<Labeled label="full_codemode">
|
||||
<SegmentedControl
|
||||
aria-label="full_codemode"
|
||||
style={segments}
|
||||
value={state.flat ? "on" : "off"}
|
||||
onChange={(value) => value && setState("flat", value === "on")}
|
||||
>
|
||||
<SegmentedControlItem value="on" style={segment}>
|
||||
On
|
||||
</SegmentedControlItem>
|
||||
<SegmentedControlItem value="off" style={segment}>
|
||||
Off
|
||||
</SegmentedControlItem>
|
||||
</SegmentedControl>
|
||||
</Labeled>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 border-b border-v2-border-border-base px-4 py-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<Button
|
||||
size="small"
|
||||
variant="neutral"
|
||||
icon="chevron-left"
|
||||
aria-label="Previous state"
|
||||
disabled={index() === 0}
|
||||
onClick={() => go(index() - 1)}
|
||||
/>
|
||||
<Button size="small" variant={state.playing ? "neutral" : "contrast"} class="w-16" onClick={play}>
|
||||
{state.playing ? "Pause" : "Play"}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
variant="neutral"
|
||||
icon="chevron-right"
|
||||
aria-label="Next state"
|
||||
disabled={last()}
|
||||
onClick={() => go(index() + 1)}
|
||||
/>
|
||||
<input
|
||||
type="range"
|
||||
aria-label="State"
|
||||
class="mx-2 min-w-0 flex-1"
|
||||
min="0"
|
||||
max={list().length - 1}
|
||||
value={index()}
|
||||
onInput={(event) => go(event.currentTarget.valueAsNumber)}
|
||||
/>
|
||||
<span class="shrink-0 text-13-regular text-v2-text-text-muted tabular-nums">
|
||||
{index() + 1}/{list().length}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<For each={list()}>
|
||||
{(item, at) => (
|
||||
<button
|
||||
type="button"
|
||||
aria-current={at() === index() ? "step" : undefined}
|
||||
class="rounded-md border border-v2-border-border-base px-1.5 py-0.5 font-mono text-12-regular hover:bg-v2-overlay-simple-overlay-hover"
|
||||
classList={{
|
||||
"bg-v2-background-bg-layer-03 text-v2-text-text-base": at() === index(),
|
||||
"text-v2-text-text-muted": at() !== index(),
|
||||
}}
|
||||
onClick={() => go(at())}
|
||||
>
|
||||
{item.label}
|
||||
</button>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
<Metadata
|
||||
state={step().state}
|
||||
file={step().file}
|
||||
open={state.metadata}
|
||||
onOpenChange={(open) => setState("metadata", open)}
|
||||
/>
|
||||
</div>
|
||||
<Show
|
||||
when={state.timeline === "both"}
|
||||
fallback={
|
||||
<div class="min-h-0 flex-1 overflow-y-auto" data-scrollable>
|
||||
{pane(state.timeline === "new")}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div class="grid min-h-0 flex-1 grid-cols-2 divide-x divide-v2-border-border-base">
|
||||
<For each={[false, true]}>
|
||||
{(next) => (
|
||||
<div class="flex min-h-0 flex-col">
|
||||
<div class="border-b border-v2-border-border-base px-4 py-1.5 text-12-medium text-v2-text-text-muted">
|
||||
{next ? "New timeline" : "Old timeline"}
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 overflow-y-auto" data-scrollable>
|
||||
{pane(next)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
function Labeled(props: { label: string; children: JSX.Element }) {
|
||||
return (
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-v2-text-text-muted">{props.label}</span>
|
||||
{props.children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// The state's raw `metadata`, as the store held it, for checking what the timeline was given.
|
||||
function Metadata(props: {
|
||||
state: CodeModeState
|
||||
file?: string
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}) {
|
||||
const part = () => props.state.part
|
||||
const metadata = createMemo(() => codeModeMetadata(part()))
|
||||
const calls = createMemo(() => metadata().toolCalls ?? [])
|
||||
const files = createMemo(() => metadata().files)
|
||||
|
||||
const counts = createMemo(() =>
|
||||
[...new Set(calls().map((call) => call.status))]
|
||||
.map((status) => `${calls().filter((call) => call.status === status).length} ${status}`)
|
||||
.join(", "),
|
||||
)
|
||||
|
||||
const flags = createMemo(() =>
|
||||
(["background", "jobID", "error", "truncated"] as const).flatMap((key) =>
|
||||
metadata()[key] === undefined ? [] : [`${key}: ${String(metadata()[key])}`],
|
||||
),
|
||||
)
|
||||
|
||||
const error = () => {
|
||||
const state = part().state
|
||||
|
||||
return state.status === "error" ? JSON.stringify(state.error) : undefined
|
||||
}
|
||||
|
||||
return (
|
||||
<Collapsible variant="ghost" open={props.open} onOpenChange={props.onOpenChange}>
|
||||
<Collapsible.Trigger class="flex w-full items-center gap-2 py-0.5 text-left text-12-regular text-v2-text-text-muted">
|
||||
<Collapsible.Arrow />
|
||||
<span class="text-12-medium text-v2-text-text-base">metadata</span>
|
||||
<span class="truncate font-mono">
|
||||
{part().name} · {part().state.status} · {calls().length} toolCalls · {files()?.length ?? "no"} files
|
||||
<For each={flags()}>{(flag) => <> · {flag}</>}</For>
|
||||
</span>
|
||||
</Collapsible.Trigger>
|
||||
<Collapsible.Content>
|
||||
<div class="grid max-h-56 grid-cols-[auto_1fr] gap-x-4 gap-y-1 overflow-y-auto py-1.5 font-mono text-12-regular">
|
||||
<span class="text-v2-text-text-muted">state</span>
|
||||
<span>{props.file ?? "session end (last state)"}</span>
|
||||
<span class="text-v2-text-text-muted">status</span>
|
||||
<span>
|
||||
{part().state.status}
|
||||
<Show when={error()}>{(text) => <> · {text()}</>}</Show>
|
||||
</span>
|
||||
<span class="text-v2-text-text-muted">toolCalls</span>
|
||||
<span>
|
||||
{calls().length}
|
||||
<Show when={counts()}>{(text) => <span class="text-v2-text-text-muted"> ({text()})</span>}</Show>
|
||||
</span>
|
||||
<span class="text-v2-text-text-muted">files</span>
|
||||
<div class="flex flex-col">
|
||||
<Show when={files()} fallback={<span class="text-v2-text-text-muted">absent</span>}>
|
||||
{(entries) => (
|
||||
<Show when={entries().length > 0} fallback={<span class="text-v2-text-text-muted">[]</span>}>
|
||||
<For each={entries()}>
|
||||
{(entry) => (
|
||||
<span>
|
||||
{entry.file} <span class="text-v2-text-text-muted">{entry.status}</span>
|
||||
<Show when={entry.additions !== undefined || entry.deletions !== undefined}>
|
||||
{" "}
|
||||
+{entry.additions ?? 0} −{entry.deletions ?? 0}
|
||||
</Show>
|
||||
<Show when={!entry.patch}>
|
||||
<span class="text-v2-text-text-faint"> no patch</span>
|
||||
</Show>
|
||||
</span>
|
||||
)}
|
||||
</For>
|
||||
</Show>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
<Show when={flags().length > 0}>
|
||||
<span class="text-v2-text-text-muted">flags</span>
|
||||
<span>{flags().join(" · ")}</span>
|
||||
</Show>
|
||||
</div>
|
||||
</Collapsible.Content>
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
|
||||
const padding = "px-4 md:px-6"
|
||||
|
||||
const statusLabels = {
|
||||
waitingApproval: "Waiting for approval",
|
||||
waitingAnswer: "Waiting for your answer",
|
||||
waitingShell: "Waiting for shell",
|
||||
working: "Working",
|
||||
} as const
|
||||
|
||||
/** The old timeline's settings as the app's timeline controller derives them from the detail setting. */
|
||||
function sessionTimelineSettings(detail: TimelineDetail) {
|
||||
const reasoningMode: ReasoningMode =
|
||||
detail.thinking.placement === "hidden" ? "hidden" : detail.thinking.details === "expanded" ? "full" : "compact"
|
||||
|
||||
return {
|
||||
reasoningMode,
|
||||
shellToolDefaultOpen: detail.shell.details === "expanded",
|
||||
editToolDefaultOpen: detail.edit.details === "expanded",
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The line below a working turn, as `MessageTimeline` in the app draws it at the bottom of the timeline: the New
|
||||
* timeline's status lane spaced like the turn's next row, or the old 36px lane, each with Working when the app shows
|
||||
* it and the offer to move a blocking call to the background. A story session has no permissions, questions, queued
|
||||
* input or background tasks, so those cases are left out.
|
||||
*/
|
||||
function SessionStatusLane(props: {
|
||||
document: SessionDocument
|
||||
timelineDetail: TimelineDetail
|
||||
next: boolean
|
||||
flat: boolean
|
||||
}) {
|
||||
const input = {
|
||||
sessionMessages: () => props.document.messages,
|
||||
status: () => props.document.status,
|
||||
scriptDiffs: () => props.flat,
|
||||
timelineDetail: () => props.timelineDetail,
|
||||
turnDiffs: () => false,
|
||||
}
|
||||
|
||||
const settings = () => sessionTimelineSettings(props.timelineDetail)
|
||||
|
||||
const projection = props.next
|
||||
? createNextTimelineProjection(input)
|
||||
: createReactiveTimelineProjection({
|
||||
...input,
|
||||
reasoningMode: () => settings().reasoningMode,
|
||||
shellToolDefaultOpen: () => settings().shellToolDefaultOpen,
|
||||
editToolDefaultOpen: () => settings().editToolDefaultOpen,
|
||||
})
|
||||
|
||||
const busy = () => props.document.status.type === "busy"
|
||||
|
||||
const assistant = () => {
|
||||
const active = projection.activeMessageID()
|
||||
|
||||
return active ? projection.assistantMessagesByParent().get(active)?.at(-1) : undefined
|
||||
}
|
||||
|
||||
const laneSpacing = createMemo(() => {
|
||||
const active = projection.activeMessageID()
|
||||
|
||||
return props.next && active ? laneGap(projection.rows(), active, projection.messageByID()) : undefined
|
||||
})
|
||||
|
||||
// MessageTimeline's showWorking, the old timeline's Working.
|
||||
const showWorking = createMemo(() => {
|
||||
if (!busy()) return false
|
||||
const active = projection.activeMessageID()
|
||||
|
||||
if (!active) return false
|
||||
const last = assistant()
|
||||
|
||||
if (last?.retry || last?.error) return false
|
||||
const content = last?.content.at(-1)
|
||||
|
||||
if (
|
||||
last?.time.completed === undefined &&
|
||||
last?.time.streamed === undefined &&
|
||||
content?.type === "text" &&
|
||||
content.text.trim()
|
||||
)
|
||||
return false
|
||||
|
||||
return !projection.rows().some((row) => {
|
||||
if (row.userMessageID !== active) return false
|
||||
|
||||
if (Predicate.isTagged(row, "Thinking")) return true
|
||||
|
||||
if (Predicate.isTagged(row, "Notice")) {
|
||||
const message = projection.messageByID().get(row.messageID)
|
||||
|
||||
return message?.type === "compaction" && message.status === "running"
|
||||
}
|
||||
|
||||
if (!Predicate.isTagged(row, "AssistantPart")) return false
|
||||
|
||||
if (row.group.type === "context" && projection.lastAssistantGroupKey().get(active) === row.group.key)
|
||||
return row.group.refs.every(
|
||||
(ref) =>
|
||||
Timeline.resolveContent(projection.messageByID().get(ref.messageID), ref.partID)?.type === "reasoning",
|
||||
)
|
||||
|
||||
if (row.group.type === "context" || row.group.type === "read") return false
|
||||
|
||||
return (row.group.type === "part" ? [row.group.ref] : row.group.refs).some((ref) => {
|
||||
const content = Timeline.resolveContent(projection.messageByID().get(ref.messageID), ref.partID)
|
||||
|
||||
return content?.type === "tool" && (content.state.status === "streaming" || content.state.status === "running")
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
const nextStatus = createMemo(() =>
|
||||
busy() && projection.activeMessageID() ? timelineStatus({ content: assistant()?.content ?? [] }) : undefined,
|
||||
)
|
||||
|
||||
const liveThought = createMemo(() =>
|
||||
projection
|
||||
.rows()
|
||||
.some((row) => Predicate.isTagged(row, "Thinking") && row.userMessageID === projection.activeMessageID()),
|
||||
)
|
||||
|
||||
const working = () => {
|
||||
if (!props.next) return showWorking()
|
||||
const status = nextStatus()
|
||||
|
||||
return !!status && (status !== "working" || !liveThought())
|
||||
}
|
||||
|
||||
// The app offers the move for a foreground shell, subagent or Code Mode script, which its background service
|
||||
// reports as blocking; the New timeline waits until the call has run for 300ms.
|
||||
const blocking = createMemo(() => {
|
||||
if (!busy()) return
|
||||
const last = assistant()
|
||||
|
||||
return last?.content.findLast(
|
||||
(part): part is Extract<typeof part, { type: "tool" }> =>
|
||||
part.type === "tool" && part.state.status === "running" && ["shell", "subagent", "execute"].includes(part.name),
|
||||
)
|
||||
})
|
||||
|
||||
const [hint, setHint] = createSignal(false)
|
||||
|
||||
createEffect(() => {
|
||||
const part = blocking()
|
||||
|
||||
if (!part) return setHint(false)
|
||||
|
||||
const wait = props.next ? Math.max(0, (part.time.ran ?? part.time.created) + 300 - Date.now()) : 0
|
||||
const timer = setTimeout(() => setHint(true), wait)
|
||||
|
||||
onCleanup(() => clearTimeout(timer))
|
||||
})
|
||||
|
||||
const move = () => (
|
||||
<Show when={hint()}>
|
||||
<div data-component="session-background-hint-row">
|
||||
<BackgroundMoveHint keybind={["Ctrl", "B"]} />
|
||||
</div>
|
||||
</Show>
|
||||
)
|
||||
|
||||
return (
|
||||
<div class="w-full min-w-0 max-w-full md:mx-auto md:max-w-session">
|
||||
<Show
|
||||
when={props.next}
|
||||
fallback={
|
||||
<div class={`flex h-9 items-center gap-2 pt-3 text-[13px] font-[530] leading-text-compact ${padding}`}>
|
||||
<Show when={showWorking()}>
|
||||
<div data-component="session-working" role="status">
|
||||
<TextShimmer text="Working" active />
|
||||
</div>
|
||||
</Show>
|
||||
{move()}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<StatusLane
|
||||
class={padding}
|
||||
spacing={laneSpacing()}
|
||||
label={working() ? statusLabels[nextStatus() ?? "working"] : undefined}
|
||||
collapsed={liveThought() && !working() && !hint()}
|
||||
>
|
||||
{move()}
|
||||
</StatusLane>
|
||||
</Show>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import { For, createMemo } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { useData } from "../../context"
|
||||
import type { SessionDocument } from "../../document"
|
||||
import type { TimelineDetail } from "../../timeline/detail"
|
||||
import { TimelineRow } from "../../timeline/timeline-row"
|
||||
|
|
@ -12,11 +13,14 @@ export function NextSessionTimeline(props: {
|
|||
timelineDetail: TimelineDetail
|
||||
turnDiffs?: boolean
|
||||
}) {
|
||||
const data = useData()
|
||||
|
||||
const projection = createNextTimelineProjection({
|
||||
sessionMessages: () => props.document.messages,
|
||||
status: () => props.document.status,
|
||||
timelineDetail: () => props.timelineDetail,
|
||||
turnDiffs: () => props.turnDiffs ?? false,
|
||||
scriptDiffs: () => data.flag("full_codemode"),
|
||||
})
|
||||
|
||||
const [disclosure, setDisclosure] = createStore<Record<string, boolean | undefined>>({})
|
||||
|
|
|
|||
|
|
@ -49,6 +49,11 @@
|
|||
margin-top: var(--timeline-gap-s);
|
||||
}
|
||||
|
||||
/* A script's Output row after its last change sits as far below it as its changes sit from each other. */
|
||||
[data-timeline="next"] [data-script-changes] > [data-script-output] {
|
||||
margin-top: var(--timeline-gap-s);
|
||||
}
|
||||
|
||||
/* Each changed file is its own accordion, rather than one stacked group, as far from the next
|
||||
as any two rows. */
|
||||
[data-timeline="next"] [data-component="accordion"][data-scope="apply-patch"] {
|
||||
|
|
@ -445,6 +450,13 @@
|
|||
padding-top: 0;
|
||||
}
|
||||
|
||||
/* An opened group spaces its items as the timeline spaces blocks; a script's changes stay by the script. */
|
||||
[data-component="context-tool-group-list"]
|
||||
> [data-slot="context-tool-group-item"]
|
||||
+ [data-slot="context-tool-group-item"]:not([data-script-change]) {
|
||||
margin-top: calc(var(--timeline-gap-m) - var(--timeline-gap-s));
|
||||
}
|
||||
|
||||
[data-component="context-tool-group-list"] [data-slot="context-tool-group-item"],
|
||||
[data-component="context-tool-group-list"] [data-slot="timeline-event-item"],
|
||||
[data-component="timeline-event-list"] [data-slot="timeline-event-item"] {
|
||||
|
|
@ -472,6 +484,32 @@
|
|||
}
|
||||
}
|
||||
|
||||
/* An open group's header stands as far above its first item as blocks stand apart (after the rule above, which
|
||||
would give it the small gap). */
|
||||
[data-component="collapsed-tool-group"]
|
||||
> [data-component="collapsible"].tool-collapsible
|
||||
> [data-slot="collapsible-trigger"][aria-expanded="true"] {
|
||||
height: calc(var(--line-height-compact) + 6px + var(--timeline-gap-m));
|
||||
padding-bottom: var(--timeline-gap-m);
|
||||
}
|
||||
|
||||
/* A script's static title's text sits above its first call's text as far as one call's text sits above the next:
|
||||
the calls' 6px gap, plus half of how much taller a call's line is than the title's. The title sits on its own line,
|
||||
not the taller line of the row around it. */
|
||||
[data-component="collapsible"].tool-collapsible:has(
|
||||
> [data-slot="collapsible-content"] > [data-component="execute-tool-calls"][data-execute-layout="flat"]
|
||||
)
|
||||
> [data-slot="collapsible-trigger"][data-locked] {
|
||||
--execute-title-gap: calc(6px + (var(--line-height-base) - var(--line-height-compact)) / 2);
|
||||
margin-bottom: 0;
|
||||
padding-bottom: var(--execute-title-gap);
|
||||
height: calc(var(--line-height-compact) + 6px + var(--execute-title-gap));
|
||||
|
||||
[data-slot="basic-tool-tool-info"] {
|
||||
line-height: var(--line-height-compact);
|
||||
}
|
||||
}
|
||||
|
||||
/* Answers are spaced by the row gaps and trimmed to their text, as the agent's text is. */
|
||||
[data-component="question-answers"] {
|
||||
gap: var(--timeline-gap-s);
|
||||
|
|
|
|||
|
|
@ -288,7 +288,14 @@ export function ContextGroup(props: {
|
|||
</Show>
|
||||
}
|
||||
>
|
||||
{(part) => <div data-slot="context-tool-group-item">{part.render()}</div>}
|
||||
{(part) => (
|
||||
<div
|
||||
data-slot="context-tool-group-item"
|
||||
data-script-change={part.file.via === "script" ? "" : undefined}
|
||||
>
|
||||
{part.render()}
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import type { JsonValue } from "@opencode/client/promise"
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { storyTool } from "../storybook/current-session-scenarios"
|
||||
import { factsOf, sameFileFact, summarize, type FileFact } from "./facts"
|
||||
import { factsOf, placeFactOf, sameFileFact, summarize, type FileFact } from "./facts"
|
||||
import { categoryOf } from "./place"
|
||||
|
||||
describe("timeline facts", () => {
|
||||
|
|
@ -113,4 +113,18 @@ describe("timeline facts", () => {
|
|||
expect(sameFileFact(before!, after!)).toBe(true)
|
||||
expect(sameFileFact(before!, scriptFiles("completed", { files: liveFiles })[0]!)).toBe(false)
|
||||
})
|
||||
|
||||
test("a script's changes show and count only with full_codemode, and a direct edit's always do", () => {
|
||||
const script = storyTool("s1", "execute", "completed", { code: "…" }, { metadata: { files: liveFiles } })
|
||||
const edit = storyTool("e1", "edit", "completed", { path: "/repo/b.ts" })
|
||||
const kinds = (facts: ReturnType<typeof factsOf>) => facts.map((fact) => fact.kind)
|
||||
|
||||
expect(kinds(factsOf([script, edit], true))).toEqual(["call", "file", "call", "file"])
|
||||
expect(summarize(factsOf([script, edit], true)).files).toEqual(["/repo/a.ts", "/repo/b.ts"])
|
||||
expect(placeFactOf(script, script.id, true).changes).toBe(1)
|
||||
|
||||
expect(kinds(factsOf([script, edit], false))).toEqual(["call", "call", "file"])
|
||||
expect(summarize(factsOf([script, edit], false)).files).toEqual(["/repo/b.ts"])
|
||||
expect(placeFactOf(script, script.id, false).changes).toBe(0)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -120,13 +120,14 @@ const modes = new Map<string, FactMode>(
|
|||
|
||||
/**
|
||||
* The facts in a list of parts, in order. Not cached: stores update a part in place as it streams, so its identity
|
||||
* says nothing about whether its facts changed. Callers read it inside a memo.
|
||||
* says nothing about whether its facts changed. Callers read it inside a memo. Without `scriptDiffs` (the server's
|
||||
* `full_codemode` flag off), a script's changes are not facts: they neither show nor count.
|
||||
*/
|
||||
export function factsOf(parts: readonly FactPart[]): Fact[] {
|
||||
return parts.flatMap(partFacts)
|
||||
export function factsOf(parts: readonly FactPart[], scriptDiffs = true): Fact[] {
|
||||
return parts.flatMap((part) => partFacts(part, scriptDiffs))
|
||||
}
|
||||
|
||||
function partFacts(part: FactPart): Fact[] {
|
||||
function partFacts(part: FactPart, scriptDiffs: boolean): Fact[] {
|
||||
const id = part.messageID ? `${part.messageID}:${part.id ?? ""}` : (part.id ?? "")
|
||||
|
||||
if (part.type === "text") return [{ kind: "text", id }]
|
||||
|
|
@ -155,7 +156,7 @@ function partFacts(part: FactPart): Fact[] {
|
|||
},
|
||||
]
|
||||
|
||||
return toolFacts(part, id)
|
||||
return toolFacts(part, id, scriptDiffs)
|
||||
}
|
||||
|
||||
const decodeFile = Schema.decodeUnknownOption(
|
||||
|
|
@ -190,12 +191,15 @@ function reads(tool: Tool): Reads {
|
|||
}
|
||||
}
|
||||
|
||||
/** What placing a call reads of it. Reads input and metadata only where they can move the call or open it. */
|
||||
export function placeFactOf(tool: Tool, id = tool.id): PlaceFact {
|
||||
return placeFact(tool, id, reads(tool))
|
||||
/**
|
||||
* What placing a call reads of it. Reads input and metadata only where they can move the call or open it. Without
|
||||
* `scriptDiffs`, a script places no changes.
|
||||
*/
|
||||
export function placeFactOf(tool: Tool, id = tool.id, scriptDiffs = true): PlaceFact {
|
||||
return placeFact(tool, id, reads(tool), scriptDiffs)
|
||||
}
|
||||
|
||||
function placeFact(tool: Tool, id: string, read: Reads): PlaceFact {
|
||||
function placeFact(tool: Tool, id: string, read: Reads, scriptDiffs = true): PlaceFact {
|
||||
const name = toolName(tool.name)
|
||||
const state = tool.state
|
||||
const stopped = toolStopped(tool)
|
||||
|
|
@ -216,7 +220,7 @@ function placeFact(tool: Tool, id: string, read: Reads): PlaceFact {
|
|||
!readImagePath(read.input()) &&
|
||||
!currentToolHasLoadedFiles(tool),
|
||||
background: name === "subagent" || (name === "shell" && read.input().background === true),
|
||||
changes: name === "execute" ? scriptChanges(tool, read).length : 0,
|
||||
changes: name === "execute" && scriptDiffs ? scriptChanges(tool, read).length : 0,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -253,9 +257,9 @@ export function launchOf(tool: Tool) {
|
|||
return placeFact(tool, tool.id, read).background ? launch(tool, toolName(tool.name), read) : undefined
|
||||
}
|
||||
|
||||
function toolFacts(tool: Tool, id: string): Fact[] {
|
||||
function toolFacts(tool: Tool, id: string, scriptDiffs: boolean): Fact[] {
|
||||
const read = reads(tool)
|
||||
const fact = placeFact(tool, id, read)
|
||||
const fact = placeFact(tool, id, read, scriptDiffs)
|
||||
const raw = read.input().path
|
||||
const path = Predicate.isString(raw) && raw ? raw : undefined
|
||||
const metadata = read.metadata()
|
||||
|
|
@ -276,6 +280,8 @@ function toolFacts(tool: Tool, id: string): Fact[] {
|
|||
|
||||
if (Predicate.isNumber(metadata.matches)) call.matches = metadata.matches
|
||||
|
||||
if (fact.name === "execute" && !scriptDiffs) return [call]
|
||||
|
||||
if (fact.name === "execute")
|
||||
return [
|
||||
call,
|
||||
|
|
@ -478,6 +484,11 @@ export function sameFileFact(previous: FileFact, next: FileFact) {
|
|||
|
||||
const scriptFilePart = /^(.*?):file:(\d+):/
|
||||
|
||||
/** Whether a part id names a change a script made, which draws as part of the script's block. */
|
||||
export function isScriptFilePartID(partID: string) {
|
||||
return scriptFilePart.test(partID)
|
||||
}
|
||||
|
||||
/** The change a script made that a part id names, read from that one entry of the script's part in the message. */
|
||||
export function scriptFileFact(content: readonly Content[], messageID: string, partID: string) {
|
||||
const match = scriptFilePart.exec(partID)
|
||||
|
|
|
|||
|
|
@ -158,6 +158,8 @@ export function createReactiveTimelineProjection(input: {
|
|||
queuedCompactionIDs?: Accessor<readonly string[]>
|
||||
/** Summarize each finished turn's changed files after it. */
|
||||
turnDiffs?: Accessor<boolean>
|
||||
/** The server's `full_codemode` flag: without it, a script's changes neither show nor count. */
|
||||
scriptDiffs?: Accessor<boolean>
|
||||
}) {
|
||||
const sessionMessageByID = createMemo(
|
||||
() => new Map(input.sessionMessages().map((message) => [message.id, message] as const)),
|
||||
|
|
@ -184,7 +186,7 @@ export function createReactiveTimelineProjection(input: {
|
|||
)
|
||||
|
||||
const textVisible = createMemo(() => new Map<Content, Accessor<boolean>>(textParts()))
|
||||
const factOf = placeFacts(input.sessionMessages)
|
||||
const factOf = placeFacts(input.sessionMessages, input.scriptDiffs)
|
||||
|
||||
const projection = createMemo(() =>
|
||||
Timeline.constructSessionMessageRows(
|
||||
|
|
@ -1219,28 +1221,32 @@ function messageParts<Part>(
|
|||
* Reads what placing each call needs through a signal per call. Streamed input and progress reports change a call many
|
||||
* times a second without moving it, and a signal notifies the rows only when what they read of it changes.
|
||||
*/
|
||||
export function placeFacts(messages: Accessor<SessionMessageInfo[]>): PlaceFactOf {
|
||||
export function placeFacts(
|
||||
messages: Accessor<SessionMessageInfo[]>,
|
||||
/** The server's `full_codemode` flag: without it, a script places no changes. */
|
||||
scriptDiffs: Accessor<boolean> = () => true,
|
||||
): PlaceFactOf {
|
||||
const parts = mapArray(
|
||||
messageParts(messages, (message) =>
|
||||
message.type === "assistant" ? message.content.filter((content): content is Tool => content.type === "tool") : [],
|
||||
),
|
||||
(tool) => {
|
||||
const [fact, setFact] = createSignal(
|
||||
untrack(() => placeFactOf(tool)),
|
||||
untrack(() => placeFactOf(tool, tool.id, scriptDiffs())),
|
||||
{ equals: samePlaceFact },
|
||||
)
|
||||
|
||||
createComputed(() => setFact(placeFactOf(tool)))
|
||||
createComputed(() => setFact(placeFactOf(tool, tool.id, scriptDiffs())))
|
||||
|
||||
// The signal only says when the fact changes, one computation after the write that changed it, so the value
|
||||
// comes from the part itself.
|
||||
return [tool, () => (fact(), untrack(() => placeFactOf(tool)))] as const
|
||||
return [tool, () => (fact(), untrack(() => placeFactOf(tool, tool.id, scriptDiffs())))] as const
|
||||
},
|
||||
)
|
||||
|
||||
const byTool = createMemo(() => new Map<Tool, Accessor<PlaceFact>>(parts()))
|
||||
|
||||
return (tool) => byTool().get(tool)?.() ?? placeFactOf(tool)
|
||||
return (tool) => byTool().get(tool)?.() ?? placeFactOf(tool, tool.id, scriptDiffs())
|
||||
}
|
||||
|
||||
const placeFactKeys = [
|
||||
|
|
|
|||
57
packages/session-ui/src/timeline/script-output.test.ts
Normal file
57
packages/session-ui/src/timeline/script-output.test.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import { describe, expect, test } from "bun:test"
|
||||
import type { SessionMessageInfo } from "@opencode/client/promise"
|
||||
import { storyTool } from "../storybook/current-session-scenarios"
|
||||
import { scriptOutputLayout } from "./script-output"
|
||||
import { TimelineRow } from "./timeline-row"
|
||||
|
||||
const messages = new Map<string, SessionMessageInfo>([
|
||||
[
|
||||
"msg_a",
|
||||
{
|
||||
id: "msg_a",
|
||||
type: "assistant",
|
||||
agent: "build",
|
||||
model: { id: "model", providerID: "provider" },
|
||||
time: { created: 1 },
|
||||
content: [storyTool("script", "execute", "completed", { code: "…" }, { output: "ok" })],
|
||||
},
|
||||
],
|
||||
])
|
||||
|
||||
// The script's row, then its changes drawn as cards in the row after it, as Detailed places them.
|
||||
const rows = [
|
||||
new TimelineRow.AssistantPart({
|
||||
userMessageID: "msg_u",
|
||||
group: { key: "part:msg_a:script", type: "part", ref: { messageID: "msg_a", partID: "script" } },
|
||||
previousAssistantPart: false,
|
||||
}),
|
||||
new TimelineRow.AssistantPart({
|
||||
userMessageID: "msg_u",
|
||||
group: {
|
||||
key: "part:msg_a:script:file:0:a.ts",
|
||||
type: "file",
|
||||
refs: [
|
||||
{ messageID: "msg_a", partID: "script:file:0:a.ts" },
|
||||
{ messageID: "msg_a", partID: "script:file:1:b.ts" },
|
||||
],
|
||||
},
|
||||
previousAssistantPart: true,
|
||||
spacing: "tool",
|
||||
}),
|
||||
]
|
||||
|
||||
describe("scriptOutputLayout", () => {
|
||||
test("moves a script's Output after its last change in the flat layout", () => {
|
||||
const layout = scriptOutputLayout(rows, messages, true)
|
||||
|
||||
expect([...layout.afterChanges]).toEqual(["script"])
|
||||
expect([...layout.outputAfter.keys()]).toEqual(["msg_a:script:file:1:b.ts"])
|
||||
})
|
||||
|
||||
test("moves nothing without the flat layout", () => {
|
||||
const layout = scriptOutputLayout(rows, messages, false)
|
||||
|
||||
expect(layout.afterChanges.size).toBe(0)
|
||||
expect(layout.outputAfter.size).toBe(0)
|
||||
})
|
||||
})
|
||||
78
packages/session-ui/src/timeline/script-output.ts
Normal file
78
packages/session-ui/src/timeline/script-output.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import type { SessionMessageAssistant, SessionMessageInfo } from "@opencode/client/promise"
|
||||
import { Predicate } from "effect"
|
||||
import { TimelineRow } from "./timeline-row"
|
||||
|
||||
type Tool = Extract<SessionMessageAssistant["content"][number], { type: "tool" }>
|
||||
|
||||
/**
|
||||
* Where each script's Output row goes. A script whose changes are drawn right after it, as the next items of its group or
|
||||
* as the row after its own, reads steps, then changes, then Output: its Output row follows its last change. Anywhere
|
||||
* else, as when its changes are hidden or grouped apart from it, its Output row stays under its steps.
|
||||
*/
|
||||
export type ScriptOutputLayout = {
|
||||
/** Scripts, by part id, whose Output row follows their changes. */
|
||||
afterChanges: ReadonlySet<string>
|
||||
/** The script whose Output row follows a change, by the change's fact id (`messageID:partID`). */
|
||||
outputAfter: ReadonlyMap<string, Tool>
|
||||
}
|
||||
|
||||
export function scriptOutputLayout(
|
||||
rows: readonly TimelineRow.TimelineRow[],
|
||||
messageByID: ReadonlyMap<string, SessionMessageInfo>,
|
||||
/** The flat execute layout (`full_codemode`); without it every Output row stays under its steps. */
|
||||
flat: boolean,
|
||||
): ScriptOutputLayout {
|
||||
const afterChanges = new Set<string>()
|
||||
const outputAfter = new Map<string, Tool>()
|
||||
|
||||
if (!flat) return { afterChanges, outputAfter }
|
||||
|
||||
const script = (messageID: string, partID: string) => {
|
||||
const message = messageByID.get(messageID)
|
||||
|
||||
const part =
|
||||
message?.type === "assistant"
|
||||
? message.content.find((item) => item.type === "tool" && item.id === partID)
|
||||
: undefined
|
||||
|
||||
return part?.type === "tool" && part.name === "execute" ? part : undefined
|
||||
}
|
||||
|
||||
// The changes of the script at refs[from - 1] that come next, in order.
|
||||
const changesOf = (refs: readonly { messageID: string; partID: string }[], from: number, scriptID: string) => {
|
||||
const end = refs.findIndex((ref, index) => index >= from && !ref.partID.startsWith(`${scriptID}:file:`))
|
||||
|
||||
return refs.slice(from, end < 0 ? refs.length : end)
|
||||
}
|
||||
|
||||
const place = (tool: Tool, changes: readonly { messageID: string; partID: string }[]) => {
|
||||
const last = changes.at(-1)
|
||||
|
||||
if (!last) return
|
||||
afterChanges.add(tool.id)
|
||||
outputAfter.set(`${last.messageID}:${last.partID}`, tool)
|
||||
}
|
||||
|
||||
rows.forEach((row, index) => {
|
||||
if (!Predicate.isTagged(row, "AssistantPart")) return
|
||||
const refs = row.group.type === "part" ? [row.group.ref] : row.group.refs
|
||||
|
||||
refs.forEach((ref, at) => {
|
||||
const tool = script(ref.messageID, ref.partID)
|
||||
|
||||
if (!tool) return
|
||||
|
||||
// Its changes follow it in the same group.
|
||||
if (at < refs.length - 1) return place(tool, changesOf(refs, at + 1, tool.id))
|
||||
const next = rows[index + 1]
|
||||
|
||||
// Or they are the row after its own, drawn as cards.
|
||||
if (!next || !Predicate.isTagged(next, "AssistantPart") || !TimelineRow.scriptChanges(next)) return
|
||||
const nextRefs = next.group.type === "part" ? [next.group.ref] : next.group.refs
|
||||
|
||||
place(tool, changesOf(nextRefs, 0, tool.id))
|
||||
})
|
||||
})
|
||||
|
||||
return { afterChanges, outputAfter }
|
||||
}
|
||||
|
|
@ -50,15 +50,18 @@ import {
|
|||
fileRuns,
|
||||
runDisclosureKey,
|
||||
ScriptChanges,
|
||||
ScriptOutputProvider,
|
||||
taskAgentName,
|
||||
ToolRegistry,
|
||||
type ContextGroupPart,
|
||||
type ScriptOutputPlacement,
|
||||
} from "../tools/tool-renderer"
|
||||
import { GenericTool } from "../components/basic-tool"
|
||||
import { SessionRetry } from "../components/session-retry"
|
||||
import { SessionError } from "../components/session-error"
|
||||
import type { TimelineDetail } from "./detail"
|
||||
import { scriptFileFact, type FileFact } from "./facts"
|
||||
import { scriptOutputLayout } from "./script-output"
|
||||
import { diffOpens, placeContent } from "./place"
|
||||
import { userMessageRuns, userRunSpring } from "./user-runs"
|
||||
import { attached } from "../components/message-file"
|
||||
|
|
@ -806,8 +809,14 @@ export function createSessionTimelineRowRenderer(input: {
|
|||
classList={{
|
||||
"min-w-0 w-full max-w-full": true,
|
||||
"md:max-w-session md:mx-auto": input.centered?.(),
|
||||
"pt-2": Predicate.isTagged(props.row, "AssistantPart") && props.row.spacing === "tool",
|
||||
"pt-4": Predicate.isTagged(props.row, "AssistantPart") && props.row.spacing === "content",
|
||||
// Blocks stand a step further apart than a script stands from its own changes.
|
||||
"pt-2":
|
||||
Predicate.isTagged(props.row, "AssistantPart") &&
|
||||
props.row.spacing === "tool" &&
|
||||
TimelineRow.scriptChanges(props.row),
|
||||
"pt-4":
|
||||
Predicate.isTagged(props.row, "AssistantPart") &&
|
||||
(props.row.spacing === "content" || (props.row.spacing === "tool" && !TimelineRow.scriptChanges(props.row))),
|
||||
"pt-6": Predicate.isTagged(props.row, "Error"),
|
||||
}}
|
||||
>
|
||||
|
|
@ -1548,11 +1557,23 @@ export function createSessionTimelineRowRenderer(input: {
|
|||
)
|
||||
}
|
||||
|
||||
// Where each script's Output row goes, from the rows: after its changes when they are drawn right after it.
|
||||
const scriptOutput = createMemo(() =>
|
||||
scriptOutputLayout(input.projection.rows(), input.projection.messageByID(), data.flag("full_codemode")),
|
||||
)
|
||||
|
||||
const scriptPlacement: ScriptOutputPlacement = {
|
||||
afterChanges: (partID) => scriptOutput().afterChanges.has(partID),
|
||||
outputAfter: (fileID) => scriptOutput().outputAfter.get(fileID),
|
||||
}
|
||||
|
||||
function Row(props: { row: Accessor<TimelineRow.TimelineRow>; onSizeChange?: () => void }) {
|
||||
return (
|
||||
<Show when={TimelineRow.key(props.row())} keyed>
|
||||
{(_key) => render(props.row, props.onSizeChange)}
|
||||
</Show>
|
||||
<ScriptOutputProvider value={scriptPlacement}>
|
||||
<Show when={TimelineRow.key(props.row())} keyed>
|
||||
{(_key) => render(props.row, props.onSizeChange)}
|
||||
</Show>
|
||||
</ScriptOutputProvider>
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { For, createMemo } from "solid-js"
|
|||
import { createStore } from "solid-js/store"
|
||||
import type { SessionDocument } from "../document"
|
||||
import type { SessionUserActions } from "../actions"
|
||||
import { useData } from "../context"
|
||||
import type { TimelineDetail } from "./detail"
|
||||
import { createReactiveTimelineProjection, TimelineRow, type ReasoningMode } from "./projection"
|
||||
import { createSessionTimelineRowRenderer, type SessionUserPresentation } from "./session-timeline-row"
|
||||
|
|
@ -22,6 +23,8 @@ export type SessionTimelineProps = {
|
|||
}
|
||||
|
||||
export function SessionTimeline(props: SessionTimelineProps) {
|
||||
const data = useData()
|
||||
|
||||
const projection = createReactiveTimelineProjection({
|
||||
sessionMessages: () => props.document.messages,
|
||||
status: () => props.document.status,
|
||||
|
|
@ -30,6 +33,7 @@ export function SessionTimeline(props: SessionTimelineProps) {
|
|||
editToolDefaultOpen: () => props.editToolDefaultOpen ?? false,
|
||||
timelineDetail: props.timelineDetail && (() => props.timelineDetail!),
|
||||
turnDiffs: () => props.turnDiffs ?? false,
|
||||
scriptDiffs: () => data.flag("full_codemode"),
|
||||
})
|
||||
|
||||
const [toolOpen, setToolOpen] = createStore<Record<string, boolean | undefined>>({})
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { Data, Match, Predicate } from "effect"
|
||||
import { isScriptFilePartID } from "./facts"
|
||||
|
||||
export type PartRef = {
|
||||
messageID: string
|
||||
|
|
@ -186,6 +187,14 @@ export namespace TimelineRow {
|
|||
Activity: () => (other: TimelineRow) => Predicate.isTagged(other, "Activity"),
|
||||
})
|
||||
|
||||
/** A row of the changes a script made, which belongs to the script's block above it. */
|
||||
export function scriptChanges(row: TimelineRow) {
|
||||
if (!Predicate.isTagged(row, "AssistantPart")) return false
|
||||
const refs = row.group.type === "part" ? [row.group.ref] : row.group.refs
|
||||
|
||||
return refs.length > 0 && refs.every((ref) => isScriptFilePartID(ref.partID))
|
||||
}
|
||||
|
||||
export function equals(a: TimelineRow, b: TimelineRow) {
|
||||
return a === b || (a.userMessageID === b.userMessageID && sameFields(a)(b))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
createEffect,
|
||||
createMemo,
|
||||
createSignal,
|
||||
createContext,
|
||||
createUniqueId,
|
||||
For,
|
||||
Match,
|
||||
|
|
@ -17,6 +18,7 @@ import {
|
|||
Index,
|
||||
on,
|
||||
untrack,
|
||||
useContext,
|
||||
type JSX,
|
||||
} from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
|
|
@ -613,7 +615,14 @@ export function CurrentContextToolGroup(props: {
|
|||
</Show>
|
||||
}
|
||||
>
|
||||
{(part) => <div data-slot="context-tool-group-item">{part.render()}</div>}
|
||||
{(part) => (
|
||||
<div
|
||||
data-slot="context-tool-group-item"
|
||||
data-script-change={part.file.via === "script" ? "" : undefined}
|
||||
>
|
||||
{part.render()}
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
}
|
||||
>
|
||||
|
|
@ -1042,6 +1051,31 @@ export function CurrentFileToolGroup(props: {
|
|||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a script's Output row goes, from the timeline's rows (`scriptOutputLayout`): after its last change when its
|
||||
* changes are drawn right after it, else under its steps.
|
||||
*/
|
||||
export type ScriptOutputPlacement = {
|
||||
afterChanges: (partID: string) => boolean
|
||||
outputAfter: (fileID: string) => SessionMessageAssistantTool | undefined
|
||||
}
|
||||
|
||||
const ScriptOutputContext = createContext<ScriptOutputPlacement>({
|
||||
afterChanges: () => false,
|
||||
outputAfter: () => undefined,
|
||||
})
|
||||
|
||||
export const ScriptOutputProvider = ScriptOutputContext.Provider
|
||||
|
||||
// What a script returned, shown as its Output row. A failure shows on its failing row instead.
|
||||
function scriptOutputText(status: string | undefined, output: string | undefined, metadata: ToolProps["metadata"]) {
|
||||
if (status === "error" || metadata.error === true) return ""
|
||||
|
||||
return stripAnsi(output ?? "")
|
||||
.replace(/\r\n?/g, "\n")
|
||||
.trim()
|
||||
}
|
||||
|
||||
/** A file group holding a script's changes: each run in order, direct calls drawn as their own group. */
|
||||
export function FileChangeRuns(props: {
|
||||
runs: readonly FileRun[]
|
||||
|
|
@ -1109,6 +1143,16 @@ export function ScriptChanges(props: {
|
|||
onSizeChange?: () => void
|
||||
}) {
|
||||
const i18n = useI18n()
|
||||
const placement = useContext(ScriptOutputContext)
|
||||
|
||||
// The Output row of a script whose last change this is, when its changes are drawn right after it.
|
||||
const outputAfter = (file: FileFact) => {
|
||||
const script = placement.outputAfter(file.id)
|
||||
|
||||
return script
|
||||
? scriptOutputText(script.state.status, currentToolOutput(script), currentToolMetadata(script))
|
||||
: undefined
|
||||
}
|
||||
|
||||
// One wrapper, as a direct patch's files share one, so the turn's gap falls around the list and not between changes.
|
||||
return (
|
||||
|
|
@ -1203,6 +1247,13 @@ export function ScriptChanges(props: {
|
|||
)
|
||||
}}
|
||||
</Index>
|
||||
<Show when={props.files.at(-1) && outputAfter(props.files.at(-1)!)}>
|
||||
{(value) => (
|
||||
<div data-component="execute-tool-calls" data-execute-layout="flat" data-script-output="">
|
||||
<ExecuteOutputRow output={value()} flat />
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -1266,6 +1317,8 @@ function currentContextToolTrigger(tool: SessionMessageAssistantTool, i18n: Retu
|
|||
// SAFETY: tool input and metadata are open per-tool records. GenericTool shows arbitrary input keys, and
|
||||
// renderers decode the fields they read with `toolInput` and `toolMetadata`.
|
||||
export interface ToolProps {
|
||||
/** The call's part id, where the timeline passes it. */
|
||||
id?: string
|
||||
// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- see SAFETY above
|
||||
input: Record<string, unknown>
|
||||
error?: string
|
||||
|
|
@ -2049,10 +2102,13 @@ ToolRegistry.register({
|
|||
name: "execute",
|
||||
render(props) {
|
||||
const i18n = useI18n()
|
||||
const data = useData()
|
||||
const dialog = useDialog()
|
||||
const pending = () => props.status === "streaming" || props.status === "running"
|
||||
const count = createMemo(() => executeToolCallCount(props.metadata))
|
||||
const subtitle = createMemo(() => executeToolSubtitle(props.metadata))
|
||||
// `full_codemode` draws the flat layout: a static title over steps that always show, Output after its changes.
|
||||
const flat = () => data.flag("full_codemode")
|
||||
const code = createMemo(() => (toolInput(props.input).code ?? "").trimEnd())
|
||||
|
||||
// A runtime failure shows its output on the failing row; a successful script shows its result below the calls.
|
||||
|
|
@ -2064,13 +2120,10 @@ ToolRegistry.register({
|
|||
return text.replace(/^Error:\s*/, "").trim() || fallback
|
||||
})
|
||||
|
||||
const output = createMemo(() =>
|
||||
error()
|
||||
? ""
|
||||
: stripAnsi(props.output ?? "")
|
||||
.replace(/\r\n?/g, "\n")
|
||||
.trim(),
|
||||
)
|
||||
const output = createMemo(() => scriptOutputText(props.status, props.output, props.metadata))
|
||||
// When its changes are drawn right after it, its Output row follows them: steps, changes, then Output.
|
||||
const placement = useContext(ScriptOutputContext)
|
||||
const outputHere = () => !!output() && !(flat() && props.id && placement.afterChanges(props.id))
|
||||
|
||||
// A runtime failure belongs to the call that raised it; scripts can also fail outside any call.
|
||||
const owner = createMemo(() => executeToolErrorIndex(props.metadata))
|
||||
|
|
@ -2099,23 +2152,28 @@ ToolRegistry.register({
|
|||
const openDetails = () =>
|
||||
dialog.show(() => <ExecuteDetails code={code()} output={output()} error={error()} status={props.status} />)
|
||||
|
||||
// Flat, the title is static and the calls always show under it: the block never collapses, whatever the timeline asks.
|
||||
return (
|
||||
<BasicTool
|
||||
{...props}
|
||||
icon="terminal"
|
||||
rail={false}
|
||||
hasContent={count() > 0 || !!error() || !!output()}
|
||||
hasContent={count() > 0 || !!error() || outputHere()}
|
||||
compact
|
||||
allowOpenWhilePending
|
||||
locked={flat() || props.locked}
|
||||
open={flat() ? true : props.open}
|
||||
forceOpen={flat() || props.forceOpen}
|
||||
onOpenChange={flat() ? undefined : props.onOpenChange}
|
||||
trigger={(open) => (
|
||||
<div data-slot="basic-tool-tool-info-structured">
|
||||
<div data-slot="basic-tool-tool-info-main">
|
||||
<span data-slot="basic-tool-tool-title">
|
||||
<span data-slot="basic-tool-tool-title" data-execute-title={flat() ? "" : undefined}>
|
||||
<Show when={shimmered()} fallback={i18n.t("ui.tool.execute")}>
|
||||
<TextShimmer text={i18n.t("ui.tool.execute")} active={pending()} />
|
||||
</Show>
|
||||
</span>
|
||||
<Show when={!open() && subtitle()}>
|
||||
<Show when={!flat() && !open() && subtitle()}>
|
||||
{(text) => <ShellSubmessage text={text()} animate={sawPending} />}
|
||||
</Show>
|
||||
</div>
|
||||
|
|
@ -2136,7 +2194,7 @@ ToolRegistry.register({
|
|||
) : undefined
|
||||
}
|
||||
>
|
||||
<div data-component="execute-tool-calls">
|
||||
<div data-component="execute-tool-calls" data-execute-layout={flat() ? "flat" : undefined}>
|
||||
<Show when={hidden()}>
|
||||
{(count) => (
|
||||
<button type="button" data-slot="execute-tool-call-more" onClick={reveal}>
|
||||
|
|
@ -2145,11 +2203,13 @@ ToolRegistry.register({
|
|||
)}
|
||||
</Show>
|
||||
<Index each={visible()}>
|
||||
{(item) => <ExecuteCallRow call={item().call} error={item().index === owner() ? error() : undefined} />}
|
||||
{(item) => (
|
||||
<ExecuteCallRow call={item().call} error={item().index === owner() ? error() : undefined} flat={flat()} />
|
||||
)}
|
||||
</Index>
|
||||
{/* A failure with no call, or one that belongs to a call still hidden above, shows on its own. */}
|
||||
<Show when={owner() < hidden() && error()}>{(text) => <ExecuteCallRow error={text()} />}</Show>
|
||||
<Show when={output()}>{(value) => <ExecuteOutputRow output={value()} />}</Show>
|
||||
<Show when={owner() < hidden() && error()}>{(text) => <ExecuteCallRow error={text()} flat={flat()} />}</Show>
|
||||
<Show when={outputHere() && output()}>{(value) => <ExecuteOutputRow output={value()} flat={flat()} />}</Show>
|
||||
</div>
|
||||
</BasicTool>
|
||||
)
|
||||
|
|
@ -2298,7 +2358,7 @@ function selectsRowText(row: HTMLElement) {
|
|||
return row.contains(selection.anchorNode) || row.contains(selection.focusNode)
|
||||
}
|
||||
|
||||
function ExecuteOutputRow(props: { output: string }) {
|
||||
function ExecuteOutputRow(props: { output: string; flat?: boolean }) {
|
||||
const i18n = useI18n()
|
||||
const [open, setOpen] = createSignal(false)
|
||||
const text = createMemo(() => formatExecuteOutput(props.output).text)
|
||||
|
|
@ -2323,9 +2383,11 @@ function ExecuteOutputRow(props: { output: string }) {
|
|||
toggle(event)
|
||||
}}
|
||||
>
|
||||
<span data-slot="execute-tool-call-marker">
|
||||
<span data-slot="execute-tool-call-arrow">›</span>
|
||||
</span>
|
||||
<Show when={!props.flat}>
|
||||
<span data-slot="execute-tool-call-marker">
|
||||
<span data-slot="execute-tool-call-arrow">›</span>
|
||||
</span>
|
||||
</Show>
|
||||
<span data-slot="execute-tool-call-name">{i18n.t("ui.tool.execute.output")}</span>
|
||||
<span data-slot="execute-tool-call-args">
|
||||
{i18n.plural("ui.tool.execute.lines", text().split("\n").length)}
|
||||
|
|
@ -2340,7 +2402,7 @@ function ExecuteOutputRow(props: { output: string }) {
|
|||
)
|
||||
}
|
||||
|
||||
function ExecuteCallRow(props: { call?: ExecuteToolCall; error?: string }) {
|
||||
function ExecuteCallRow(props: { call?: ExecuteToolCall; error?: string; flat?: boolean }) {
|
||||
const [open, setOpen] = createSignal(false)
|
||||
const args = createMemo(() => (props.call ? executeToolCallArgs(props.call) : []))
|
||||
const input = createMemo(() => Object.entries(props.call?.input ?? {}))
|
||||
|
|
@ -2372,10 +2434,12 @@ function ExecuteCallRow(props: { call?: ExecuteToolCall; error?: string }) {
|
|||
toggle(event)
|
||||
}}
|
||||
>
|
||||
<Show when={failed()} fallback={<span data-slot="execute-tool-call-marker">›</span>}>
|
||||
<span data-slot="execute-tool-call-marker">
|
||||
<Icon name="outline-hexagonal-warning" size="small" />
|
||||
</span>
|
||||
<Show when={!props.flat}>
|
||||
<Show when={failed()} fallback={<span data-slot="execute-tool-call-marker">›</span>}>
|
||||
<span data-slot="execute-tool-call-marker">
|
||||
<Icon name="outline-hexagonal-warning" size="small" />
|
||||
</span>
|
||||
</Show>
|
||||
</Show>
|
||||
<Show when={props.call}>
|
||||
{(call) => (
|
||||
|
|
@ -2386,6 +2450,12 @@ function ExecuteCallRow(props: { call?: ExecuteToolCall; error?: string }) {
|
|||
</span>
|
||||
)}
|
||||
</Show>
|
||||
{/* Flat, after the name, so every call's name lines up with the title; a failure without a call leads with it. */}
|
||||
<Show when={props.flat && failed()}>
|
||||
<span data-slot="execute-tool-call-marker">
|
||||
<Icon name="outline-hexagonal-warning" size="small" />
|
||||
</span>
|
||||
</Show>
|
||||
<Show when={!open() && summary()}>
|
||||
{(text) => (
|
||||
<span data-slot="execute-tool-call-args" title={text()}>
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue