opencode-change-history 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/CHANGELOG.zh-CN.md +31 -0
- package/LICENSE +21 -0
- package/README.md +103 -2
- package/README.zh-CN.md +104 -0
- package/package.json +70 -4
- package/src/core/diff.ts +54 -0
- package/src/core/history.ts +86 -0
- package/src/core/parser.ts +260 -0
- package/src/core/patch-input.ts +45 -0
- package/src/core/paths.ts +47 -0
- package/src/core/types.ts +52 -0
- package/src/session-history.ts +180 -0
- package/src/tui.tsx +90 -0
- package/src/ui/changes-sidebar.tsx +177 -0
- package/src/ui/changes.tsx +300 -0
- package/src/ui/diff-view.tsx +141 -0
- package/src/ui/explorer.tsx +268 -0
- package/src/ui/file-tree.ts +113 -0
- package/src/ui/history-nav.tsx +216 -0
- package/src/ui/layout.ts +90 -0
- package/src/ui/presentation.tsx +320 -0
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { prefixedLines, snippet, unifiedCounts } from "./diff"
|
|
2
|
+
import { patchOperations } from "./patch-input"
|
|
3
|
+
import type { Change, ChangeKind } from "./types"
|
|
4
|
+
|
|
5
|
+
interface Tool {
|
|
6
|
+
readonly type: "tool"
|
|
7
|
+
readonly id: string
|
|
8
|
+
readonly name: string
|
|
9
|
+
readonly executed?: boolean
|
|
10
|
+
readonly time: { readonly created: number; readonly ran?: number; readonly completed?: number }
|
|
11
|
+
readonly state:
|
|
12
|
+
| { readonly status: "streaming" | "running" | "error" }
|
|
13
|
+
| {
|
|
14
|
+
readonly status: "completed"
|
|
15
|
+
readonly input: Readonly<Record<string, unknown>>
|
|
16
|
+
readonly metadata?: Readonly<Record<string, unknown>> | null
|
|
17
|
+
readonly content: readonly { readonly type: string; readonly text?: string }[]
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type Message =
|
|
22
|
+
| { readonly type: "assistant"; readonly id: string; readonly content: readonly (Tool | { readonly type: "text" | "reasoning" })[] }
|
|
23
|
+
| {
|
|
24
|
+
readonly type: "location-switched"
|
|
25
|
+
readonly id: string
|
|
26
|
+
readonly location: { readonly directory: string }
|
|
27
|
+
readonly previous?: { readonly location: { readonly directory: string } } | null
|
|
28
|
+
}
|
|
29
|
+
| { readonly type: "user" | "synthetic" | "idle" | "system" | "agent-switched" | "model-switched" | "skill" | "shell" | "compaction"; readonly id: string }
|
|
30
|
+
|
|
31
|
+
type Detail = Omit<Change, "id" | "sessionID" | "messageID" | "toolCallID" | "tool" | "time" | "timeSource"> & {
|
|
32
|
+
ordinal?: number
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface ParsedMessage {
|
|
36
|
+
id: string
|
|
37
|
+
type: Message["type"]
|
|
38
|
+
changes: Change[]
|
|
39
|
+
directory?: string
|
|
40
|
+
previousDirectory?: string
|
|
41
|
+
nextCwd?: string | null
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const object = (value: unknown): Record<string, unknown> | undefined =>
|
|
45
|
+
typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined
|
|
46
|
+
|
|
47
|
+
const pathString = (value: unknown) => (typeof value === "string" && value.length > 0 ? value : undefined)
|
|
48
|
+
|
|
49
|
+
const count = (value: unknown) =>
|
|
50
|
+
typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined
|
|
51
|
+
|
|
52
|
+
function kind(value: unknown, fallback: ChangeKind): ChangeKind {
|
|
53
|
+
switch (value) {
|
|
54
|
+
case "add":
|
|
55
|
+
case "added":
|
|
56
|
+
return "added"
|
|
57
|
+
case "delete":
|
|
58
|
+
case "deleted":
|
|
59
|
+
return "deleted"
|
|
60
|
+
case "update":
|
|
61
|
+
case "modified":
|
|
62
|
+
return "modified"
|
|
63
|
+
case "move":
|
|
64
|
+
return "moved"
|
|
65
|
+
default:
|
|
66
|
+
return fallback
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function recorded(
|
|
71
|
+
path: string,
|
|
72
|
+
status: ChangeKind,
|
|
73
|
+
rawDiff: unknown,
|
|
74
|
+
metadata: Record<string, unknown>,
|
|
75
|
+
previousPath?: string,
|
|
76
|
+
): Detail {
|
|
77
|
+
const diff = typeof rawDiff === "string" && rawDiff !== "" ? rawDiff : undefined
|
|
78
|
+
const counts = diff === undefined ? undefined : unifiedCounts(diff)
|
|
79
|
+
const additions = count(metadata.additions) ?? counts?.additions
|
|
80
|
+
const deletions = count(metadata.deletions) ?? counts?.deletions
|
|
81
|
+
const headerOnly = diff && additions === 0 && deletions === 0 && /^--- .+\r?\n\+\+\+ .+\r?\n?$/m.test(diff) && !diff.includes("\n@@")
|
|
82
|
+
return {
|
|
83
|
+
path,
|
|
84
|
+
previousPath,
|
|
85
|
+
kind: previousPath ? "moved" : status,
|
|
86
|
+
diff,
|
|
87
|
+
// OpenCode also emits header-only patches for zero textual changes (e.g. a pure move).
|
|
88
|
+
diffQuality: counts || headerOnly ? "recorded" : "missing",
|
|
89
|
+
additions,
|
|
90
|
+
deletions,
|
|
91
|
+
source: "metadata",
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function fromInput(path: string, status: ChangeKind, fragments: (string | undefined)[], previousPath?: string): Detail {
|
|
96
|
+
const present = fragments.filter((diff): diff is string => diff !== undefined)
|
|
97
|
+
return {
|
|
98
|
+
path,
|
|
99
|
+
previousPath,
|
|
100
|
+
kind: status,
|
|
101
|
+
fragments: present.length ? present : undefined,
|
|
102
|
+
diffQuality: present.length ? "partial" : "missing",
|
|
103
|
+
source: "input",
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function toolDetails(tool: Tool & { state: Extract<Tool["state"], { status: "completed" }> }): Detail[] {
|
|
108
|
+
const { name, state: { input, content } } = tool
|
|
109
|
+
const metadata = tool.state.metadata ?? {}
|
|
110
|
+
if (metadata.error === true && name !== "execute") return []
|
|
111
|
+
const patch = name === "patch" || name === "apply_patch"
|
|
112
|
+
const builtin = name === "edit" || name === "write" || patch
|
|
113
|
+
const operations = patch ? patchOperations(input.patchText ?? input.patch_text) : []
|
|
114
|
+
const patchInput = (op: (typeof operations)[number]) =>
|
|
115
|
+
fromInput(op.path, op.kind, op.chunks.map((lines) => snippet(op.path, lines)), op.previousPath)
|
|
116
|
+
const enrich = (entry: Detail, fallback: Detail): Detail =>
|
|
117
|
+
entry.diffQuality === "recorded" || !fallback.fragments
|
|
118
|
+
? entry
|
|
119
|
+
: { ...entry, fragments: fallback.fragments, diffQuality: "partial" }
|
|
120
|
+
|
|
121
|
+
if (Array.isArray(metadata.files)) {
|
|
122
|
+
// In the built-in V2 patch the result array is in input operation order.
|
|
123
|
+
const aligned = patch && operations.length === metadata.files.length
|
|
124
|
+
const entries = metadata.files.flatMap((raw: unknown, index) => {
|
|
125
|
+
const entry = object(raw)
|
|
126
|
+
const op = aligned ? operations[index] : undefined
|
|
127
|
+
if (!entry || entry.more === true) return op ? [{ ...patchInput(op), ordinal: index }] : []
|
|
128
|
+
const modernPath = pathString(entry.file)
|
|
129
|
+
const modernKind = kind(entry.status, "unknown")
|
|
130
|
+
const legacyPath = patch ? pathString(entry.filePath) : undefined
|
|
131
|
+
const move = legacyPath ? pathString(entry.movePath) : undefined
|
|
132
|
+
const path = move ?? modernPath ?? legacyPath
|
|
133
|
+
if (!path || (!builtin && (!modernPath || modernKind === "unknown"))) {
|
|
134
|
+
return op ? [{ ...patchInput(op), ordinal: index }] : []
|
|
135
|
+
}
|
|
136
|
+
const status = modernKind === "unknown" ? kind(entry.type, op?.kind ?? "unknown") : modernKind
|
|
137
|
+
const previous = move ? legacyPath : modernPath ? op?.previousPath : undefined
|
|
138
|
+
const detail = recorded(path, status, entry.patch ?? (legacyPath ? entry.diff : undefined), entry, previous)
|
|
139
|
+
if (!builtin && name !== "execute" && detail.diffQuality !== "recorded" &&
|
|
140
|
+
detail.additions === undefined && detail.deletions === undefined) return []
|
|
141
|
+
return [{ ...(op ? enrich(detail, patchInput(op)) : detail), ordinal: index }]
|
|
142
|
+
})
|
|
143
|
+
if (entries.length) {
|
|
144
|
+
// V2 passes a file's final formatted text to each earlier write to the same destination.
|
|
145
|
+
// Its earlier hunks can include changes from a later operation, so don't sum their counts.
|
|
146
|
+
if (patch && metadata.files.every((entry) => typeof object(entry)?.file === "string")) {
|
|
147
|
+
const final = new Map<string, ChangeKind>()
|
|
148
|
+
for (const entry of entries.toReversed()) {
|
|
149
|
+
const later = final.get(entry.path)
|
|
150
|
+
if (later && later !== "deleted" && entry.kind !== "deleted") {
|
|
151
|
+
entry.additions = undefined
|
|
152
|
+
entry.deletions = undefined
|
|
153
|
+
entry.note = "OpenCode’s recorded Diff may include a later operation on this path. Line counts are unavailable."
|
|
154
|
+
}
|
|
155
|
+
if (!later) final.set(entry.path, entry.kind)
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return entries
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// `executed: true` describes provider-side execution, not the outcome of a native OpenCode tool.
|
|
163
|
+
if (!builtin || tool.executed === true) return []
|
|
164
|
+
const text = content.find((item) => item.type === "text")?.text ?? ""
|
|
165
|
+
if (patch) {
|
|
166
|
+
if (operations.length) return operations.map(patchInput)
|
|
167
|
+
const summary = /^Success\. Updated the following files:\n([\s\S]+)$/.exec(text)
|
|
168
|
+
if (!summary) return []
|
|
169
|
+
const lines = summary[1].split("\n\nLSP errors detected", 1)[0].replace(/\n+$/, "").split("\n")
|
|
170
|
+
const results = lines.map((line) => /^([ADM]) (.+)$/.exec(line))
|
|
171
|
+
if (results.some((line) => !line)) return []
|
|
172
|
+
return results.flatMap((line) => line ? [{
|
|
173
|
+
path: line[2],
|
|
174
|
+
kind: line[1] === "A" ? "added" : line[1] === "D" ? "deleted" : "modified",
|
|
175
|
+
source: "result",
|
|
176
|
+
diffQuality: "missing",
|
|
177
|
+
}] : [])
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const file = name === "edit" ? object(metadata.filediff) : undefined
|
|
181
|
+
const write = name === "write" ? /^(Created|Wrote) file successfully: ([\s\S]+)$/.exec(text) : null
|
|
182
|
+
const editedPath = name === "edit" ? /^Edited ([\s\S]+) \(\d+ replacements?\)$/.exec(text)?.[1] : undefined
|
|
183
|
+
const path = pathString(file?.file) ?? pathString(metadata.filepath) ?? editedPath ?? write?.[2] ??
|
|
184
|
+
pathString(input.path) ?? pathString(input.filePath)
|
|
185
|
+
if (!path) return []
|
|
186
|
+
if (name === "edit") {
|
|
187
|
+
const oldText = input.oldString
|
|
188
|
+
const newText = input.newString
|
|
189
|
+
const status = oldText === "" ? "write" : "modified"
|
|
190
|
+
const fallback = typeof oldText === "string" && typeof newText === "string" && oldText !== newText
|
|
191
|
+
? fromInput(path, status, [snippet(path, [...prefixedLines(oldText, "-"), ...prefixedLines(newText, "+")])])
|
|
192
|
+
: undefined
|
|
193
|
+
if (file || typeof metadata.diff === "string") {
|
|
194
|
+
const detail = recorded(path, kind(file?.status, status), file?.patch || metadata.diff, file ?? {})
|
|
195
|
+
return [fallback ? enrich(detail, fallback) : detail]
|
|
196
|
+
}
|
|
197
|
+
if (fallback) return [fallback]
|
|
198
|
+
return editedPath || pathString(metadata.filepath)
|
|
199
|
+
? [{ path, kind: status, diffQuality: "missing", source: editedPath ? "result" : "metadata" }]
|
|
200
|
+
: []
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const status = write
|
|
204
|
+
? write[1] === "Created" ? "added" : "modified"
|
|
205
|
+
: typeof metadata.exists === "boolean" ? metadata.exists ? "modified" : "added" : "write"
|
|
206
|
+
if (typeof metadata.diff === "string") return [recorded(path, status, metadata.diff, metadata)]
|
|
207
|
+
if (typeof input.content !== "string" && !write && !pathString(metadata.filepath)) return []
|
|
208
|
+
// A write's input is the proposed content; formatting may have changed it before completion.
|
|
209
|
+
// For a confirmed creation it is still the only available volume estimate, so keep it out of
|
|
210
|
+
// `additions` and expose it as an explicitly approximate count.
|
|
211
|
+
const lines = status === "added" && typeof input.content === "string" ? prefixedLines(input.content, "+") : []
|
|
212
|
+
const preview = snippet(path, lines)
|
|
213
|
+
const estimatedAdditions = status === "added" && lines.length > 0 && metadata.truncated !== true
|
|
214
|
+
? lines.length
|
|
215
|
+
: undefined
|
|
216
|
+
return [{
|
|
217
|
+
...fromInput(path, status, preview ? [preview] : []),
|
|
218
|
+
source: write ? "result" : "input",
|
|
219
|
+
deletions: status === "added" ? 0 : undefined,
|
|
220
|
+
estimatedAdditions,
|
|
221
|
+
}]
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function parseMessage(sessionID: string, message: Message): ParsedMessage {
|
|
225
|
+
const parsed: ParsedMessage = { id: message.id, type: message.type, changes: [] }
|
|
226
|
+
if (message.type === "location-switched") {
|
|
227
|
+
parsed.directory = message.location.directory
|
|
228
|
+
parsed.previousDirectory = message.previous?.location.directory
|
|
229
|
+
}
|
|
230
|
+
if (message.type !== "assistant") return parsed
|
|
231
|
+
|
|
232
|
+
const tools = new Map(message.content.flatMap((part) => part.type === "tool" ? [[part.id, part]] : []))
|
|
233
|
+
let cwdTime = -Infinity
|
|
234
|
+
for (const tool of tools.values()) {
|
|
235
|
+
const state = tool.state
|
|
236
|
+
if (state.status !== "completed") continue
|
|
237
|
+
const time = tool.time.completed ?? tool.time.ran ?? tool.time.created
|
|
238
|
+
if (tool.name === "cd" && tool.executed !== true && time >= cwdTime) {
|
|
239
|
+
const text = state.content.find((part) => part.type === "text")?.text
|
|
240
|
+
const cwd = /^Working directory set to (.+) from the next step\./.exec(text ?? "")?.[1]
|
|
241
|
+
if (cwd || (state.input.path === null && text === "Reset working directory to the session default from the next step.")) {
|
|
242
|
+
parsed.nextCwd = cwd ?? null
|
|
243
|
+
cwdTime = time
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const details = toolDetails({ ...tool, state })
|
|
247
|
+
details.forEach(({ ordinal, ...detail }, index) => parsed.changes.push({
|
|
248
|
+
...detail,
|
|
249
|
+
// Ordinal within the tool result distinguishes multiple operations on one path.
|
|
250
|
+
id: JSON.stringify([sessionID, message.id, tool.id, ordinal ?? index, detail.path]),
|
|
251
|
+
sessionID,
|
|
252
|
+
messageID: message.id,
|
|
253
|
+
toolCallID: tool.id,
|
|
254
|
+
tool: tool.name,
|
|
255
|
+
time,
|
|
256
|
+
timeSource: tool.time.completed !== undefined ? "completion" : "start",
|
|
257
|
+
}))
|
|
258
|
+
}
|
|
259
|
+
return parsed
|
|
260
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ChangeKind } from "./types"
|
|
2
|
+
|
|
3
|
+
interface Operation {
|
|
4
|
+
path: string
|
|
5
|
+
previousPath?: string
|
|
6
|
+
kind: ChangeKind
|
|
7
|
+
chunks: string[][]
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Read only the recorded patch grammar. No attempt to locate hunks in a file. */
|
|
11
|
+
export function patchOperations(input: unknown): Operation[] {
|
|
12
|
+
if (typeof input !== "string") return []
|
|
13
|
+
const lines = input.replaceAll("\r\n", "\n").trimEnd().split("\n")
|
|
14
|
+
if (lines[0] !== "*** Begin Patch" || lines.at(-1) !== "*** End Patch") return []
|
|
15
|
+
const operations: Operation[] = []
|
|
16
|
+
let current: Operation | undefined
|
|
17
|
+
for (const line of lines.slice(1, -1)) {
|
|
18
|
+
const header = /^\*\*\* (Add|Update|Delete) File: (.+)$/.exec(line)
|
|
19
|
+
if (header) {
|
|
20
|
+
current = {
|
|
21
|
+
path: header[2],
|
|
22
|
+
kind: header[1] === "Add" ? "added" : header[1] === "Delete" ? "deleted" : "modified",
|
|
23
|
+
chunks: [[]],
|
|
24
|
+
}
|
|
25
|
+
operations.push(current)
|
|
26
|
+
continue
|
|
27
|
+
}
|
|
28
|
+
if (!current || current.kind === "deleted") return []
|
|
29
|
+
const move = /^\*\*\* Move to: (.+)$/.exec(line)
|
|
30
|
+
if (move && current.kind === "modified" && !current.chunks[0].length) {
|
|
31
|
+
current.previousPath = current.path
|
|
32
|
+
current.path = move[1]
|
|
33
|
+
current.kind = "moved"
|
|
34
|
+
} else if (current.kind !== "added" && (line === "@@" || line.startsWith("@@ "))) {
|
|
35
|
+
if (current.chunks.at(-1)?.length) current.chunks.push([])
|
|
36
|
+
} else if (line === "*** End of File" && current.kind !== "added") {
|
|
37
|
+
continue
|
|
38
|
+
} else if (current.kind === "added" ? line.startsWith("+") : /^[ +\-]/.test(line)) {
|
|
39
|
+
current.chunks.at(-1)?.push(line)
|
|
40
|
+
} else {
|
|
41
|
+
return []
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return operations.filter((entry) => entry.kind !== "added" || entry.chunks[0].length > 0)
|
|
45
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { posix, win32 } from "node:path"
|
|
2
|
+
|
|
3
|
+
const windowsRoot = /^(?:[A-Za-z]:\/|\/\/[^/]+\/[^/]+)/
|
|
4
|
+
|
|
5
|
+
function resource(path: string) {
|
|
6
|
+
const prefix = /^([^/\\:]+):(?=\/(?!\/)|~|[A-Za-z]:[\\/])/.exec(path)?.[0] ?? ""
|
|
7
|
+
if (prefix.length > 2) return { prefix, path: path.slice(prefix.length) }
|
|
8
|
+
return { prefix: "", path }
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function filePath(value: string, directory?: string): string {
|
|
12
|
+
const target = resource(value)
|
|
13
|
+
const base = resource(directory ?? "")
|
|
14
|
+
const path = target.path.replaceAll("\\", "/")
|
|
15
|
+
const root = base.path.replaceAll("\\", "/")
|
|
16
|
+
const windows = windowsRoot.test(path) || /^[A-Za-z]:/.test(path) || (!target.prefix && windowsRoot.test(root))
|
|
17
|
+
|
|
18
|
+
if (windows) {
|
|
19
|
+
// Don't use resolve(): drive-relative paths otherwise use the UI process's cwd.
|
|
20
|
+
const absolute =
|
|
21
|
+
/^[A-Za-z]:[^/]/.test(path) || /^[A-Za-z]:$/.test(path)
|
|
22
|
+
? path
|
|
23
|
+
: windowsRoot.test(path)
|
|
24
|
+
? path
|
|
25
|
+
: path.startsWith("/")
|
|
26
|
+
? win32.parse(root).root + path.slice(1)
|
|
27
|
+
: win32.join(root, path)
|
|
28
|
+
const normalized = win32.normalize(absolute).replaceAll("\\", "/").replace(/^([a-z]):/, (_, drive) => {
|
|
29
|
+
return `${drive.toUpperCase()}:`
|
|
30
|
+
})
|
|
31
|
+
return (target.prefix || base.prefix) + normalized
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const absolute = path.startsWith("/") || target.prefix ? path : posix.join(root, path)
|
|
35
|
+
return (target.prefix || base.prefix) + posix.normalize(absolute)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function relativeLabel(path: string, directory: string): string {
|
|
39
|
+
const base = resource(filePath(directory))
|
|
40
|
+
const target = resource(path)
|
|
41
|
+
const windows = windowsRoot.test(base.path)
|
|
42
|
+
if (target.prefix !== base.prefix || windowsRoot.test(target.path) !== windows) return path
|
|
43
|
+
const root = base.path.endsWith("/") ? base.path : `${base.path}/`
|
|
44
|
+
const prefix = target.path.slice(0, root.length)
|
|
45
|
+
const inside = windows ? prefix.toLowerCase() === root.toLowerCase() : prefix === root
|
|
46
|
+
return inside ? target.path.slice(root.length) : path
|
|
47
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export interface LineCounts {
|
|
2
|
+
additions?: number
|
|
3
|
+
deletions?: number
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export type ChangeKind = "added" | "modified" | "deleted" | "moved" | "write" | "unknown"
|
|
7
|
+
|
|
8
|
+
export interface Change extends LineCounts {
|
|
9
|
+
id: string
|
|
10
|
+
sessionID: string
|
|
11
|
+
messageID: string
|
|
12
|
+
toolCallID: string
|
|
13
|
+
tool: string
|
|
14
|
+
time: number
|
|
15
|
+
timeSource: "completion" | "start"
|
|
16
|
+
path: string
|
|
17
|
+
previousPath?: string
|
|
18
|
+
kind: ChangeKind
|
|
19
|
+
/** Additions inferred from a confirmed write's submitted content, never a recorded count. */
|
|
20
|
+
estimatedAdditions?: number
|
|
21
|
+
diff?: string
|
|
22
|
+
fragments?: string[]
|
|
23
|
+
diffQuality: "recorded" | "partial" | "missing"
|
|
24
|
+
source: "metadata" | "input" | "result"
|
|
25
|
+
note?: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface RecordedChange extends Change {
|
|
29
|
+
turn?: number
|
|
30
|
+
incomplete: boolean
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface Statistics {
|
|
34
|
+
operations: number
|
|
35
|
+
additions: number
|
|
36
|
+
deletions: number
|
|
37
|
+
estimatedAdditions: number
|
|
38
|
+
unknownAdditions: number
|
|
39
|
+
unknownDeletions: number
|
|
40
|
+
incomplete: number
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface FileHistory extends Statistics {
|
|
44
|
+
path: string
|
|
45
|
+
lastModified: number
|
|
46
|
+
changes: RecordedChange[]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface History extends Statistics {
|
|
50
|
+
files: FileHistory[]
|
|
51
|
+
staged: boolean
|
|
52
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import type { OpenCodeClient, OpenCodeEvent } from "@opencode/client"
|
|
2
|
+
import { aggregate } from "./core/history"
|
|
3
|
+
import { parseMessage, type ParsedMessage } from "./core/parser"
|
|
4
|
+
import type { History } from "./core/types"
|
|
5
|
+
|
|
6
|
+
export type HistoryState =
|
|
7
|
+
| { status: "loading" }
|
|
8
|
+
| { status: "error"; message: string }
|
|
9
|
+
| { status: "ready"; directory: string; history: History }
|
|
10
|
+
|
|
11
|
+
export type HistoryClient = {
|
|
12
|
+
message: Pick<OpenCodeClient["message"], "list">
|
|
13
|
+
session: Pick<OpenCodeClient["session"], "get"> & {
|
|
14
|
+
message: Pick<OpenCodeClient["session"]["message"], "get">
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type Listen = (listener: (event: { details: OpenCodeEvent }) => void) => () => void
|
|
19
|
+
|
|
20
|
+
const limit = 100
|
|
21
|
+
|
|
22
|
+
export function openSessionHistory(
|
|
23
|
+
sessionID: string,
|
|
24
|
+
client: HistoryClient,
|
|
25
|
+
listen: Listen,
|
|
26
|
+
publish: (state: HistoryState) => void,
|
|
27
|
+
) {
|
|
28
|
+
const abort = new AbortController()
|
|
29
|
+
const options = { signal: abort.signal }
|
|
30
|
+
const messages = new Map<string, ParsedMessage>()
|
|
31
|
+
const dirty = new Set<string>()
|
|
32
|
+
let newest: string | undefined
|
|
33
|
+
let directory: string
|
|
34
|
+
let boundary: string | undefined
|
|
35
|
+
let boundaryUpdate: { value: string | undefined } | undefined
|
|
36
|
+
let reload = true
|
|
37
|
+
let append = false
|
|
38
|
+
let running = false
|
|
39
|
+
let failed = false
|
|
40
|
+
|
|
41
|
+
// A descending first page fixes the upper bound while older pages load.
|
|
42
|
+
// The reverse-direction cursor subsequently fetches only newly delivered messages.
|
|
43
|
+
const list = (cursor?: string) =>
|
|
44
|
+
client.message.list(cursor === undefined ? { sessionID, limit, order: "desc" } : { sessionID, limit, cursor }, options)
|
|
45
|
+
|
|
46
|
+
async function load() {
|
|
47
|
+
const session = await client.session.get({ sessionID }, options)
|
|
48
|
+
const first = await list()
|
|
49
|
+
newest = first.cursor.previous ?? undefined
|
|
50
|
+
const entries = first.data.map((message) => parseMessage(sessionID, message))
|
|
51
|
+
let cursor = first.cursor.next
|
|
52
|
+
// The 2.4 API can return a cursor even for the last non-empty page.
|
|
53
|
+
while (cursor && !abort.signal.aborted && !reload) {
|
|
54
|
+
const page = await list(cursor)
|
|
55
|
+
if (!page.data.length) break
|
|
56
|
+
cursor = page.cursor.next
|
|
57
|
+
for (const message of page.data) entries.push(parseMessage(sessionID, message))
|
|
58
|
+
}
|
|
59
|
+
if (abort.signal.aborted || reload) return
|
|
60
|
+
directory = session.location.directory
|
|
61
|
+
boundary = session.revert?.messageID
|
|
62
|
+
messages.clear()
|
|
63
|
+
for (const entry of entries.reverse()) messages.set(entry.id, entry)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function update(ids: readonly string[], readTail: boolean) {
|
|
67
|
+
const fresh = new Set<string>()
|
|
68
|
+
if (readTail) {
|
|
69
|
+
// A previous cursor returns the next interval in descending order, nearest the anchor.
|
|
70
|
+
let cursor = newest
|
|
71
|
+
do {
|
|
72
|
+
const page = await list(cursor)
|
|
73
|
+
if (reload || abort.signal.aborted) return
|
|
74
|
+
if (!page.data.length) break
|
|
75
|
+
for (const message of page.data.toReversed()) {
|
|
76
|
+
fresh.add(message.id)
|
|
77
|
+
messages.set(message.id, parseMessage(sessionID, message))
|
|
78
|
+
}
|
|
79
|
+
cursor = page.cursor.previous ?? undefined
|
|
80
|
+
newest = cursor
|
|
81
|
+
} while (cursor)
|
|
82
|
+
}
|
|
83
|
+
await Promise.all(ids.filter((id) => messages.has(id) && !fresh.has(id)).map(async (messageID) => {
|
|
84
|
+
const data = await client.session.message.get({ sessionID, messageID }, options)
|
|
85
|
+
if (!reload && !abort.signal.aborted) messages.set(messageID, parseMessage(sessionID, data))
|
|
86
|
+
}))
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function flush() {
|
|
90
|
+
if (running || abort.signal.aborted) return
|
|
91
|
+
running = true
|
|
92
|
+
try {
|
|
93
|
+
while (!abort.signal.aborted && (reload || append || dirty.size || boundaryUpdate)) {
|
|
94
|
+
const refresh = reload
|
|
95
|
+
const readTail = append
|
|
96
|
+
const ids = [...dirty]
|
|
97
|
+
reload = false
|
|
98
|
+
append = false
|
|
99
|
+
dirty.clear()
|
|
100
|
+
if (refresh || (readTail && !newest)) {
|
|
101
|
+
publish({ status: "loading" })
|
|
102
|
+
await load()
|
|
103
|
+
} else if (readTail || ids.length) {
|
|
104
|
+
await update(ids, readTail)
|
|
105
|
+
}
|
|
106
|
+
if (reload || abort.signal.aborted) continue
|
|
107
|
+
if (boundaryUpdate) {
|
|
108
|
+
boundary = boundaryUpdate.value
|
|
109
|
+
boundaryUpdate = undefined
|
|
110
|
+
}
|
|
111
|
+
failed = false
|
|
112
|
+
publish({ status: "ready", directory, history: aggregate([...messages.values()], directory, boundary) })
|
|
113
|
+
}
|
|
114
|
+
} catch {
|
|
115
|
+
if (!abort.signal.aborted) {
|
|
116
|
+
failed = true
|
|
117
|
+
if (append || dirty.size) reload = true
|
|
118
|
+
if (!reload) publish({ status: "error", message: "Could not read recorded changes from OpenCode." })
|
|
119
|
+
}
|
|
120
|
+
} finally {
|
|
121
|
+
running = false
|
|
122
|
+
if (reload && !abort.signal.aborted) schedule()
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const schedule = () => queueMicrotask(() => void flush())
|
|
127
|
+
const refresh = () => {
|
|
128
|
+
if (abort.signal.aborted) return
|
|
129
|
+
reload = true
|
|
130
|
+
boundaryUpdate = undefined
|
|
131
|
+
schedule()
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const unsubscribe = listen(({ details: event }) => {
|
|
135
|
+
if (event.type === "server.connected") return refresh()
|
|
136
|
+
if (!("sessionID" in event.data) || event.data.sessionID !== sessionID) return
|
|
137
|
+
switch (event.type) {
|
|
138
|
+
case "session.deleted":
|
|
139
|
+
abort.abort()
|
|
140
|
+
messages.clear()
|
|
141
|
+
unsubscribe()
|
|
142
|
+
publish({ status: "error", message: "This session has been deleted." })
|
|
143
|
+
return
|
|
144
|
+
case "session.revert.committed":
|
|
145
|
+
case "session.moved":
|
|
146
|
+
return refresh()
|
|
147
|
+
case "session.revert.staged":
|
|
148
|
+
boundaryUpdate = { value: event.data.revert.messageID }
|
|
149
|
+
break
|
|
150
|
+
case "session.revert.cleared":
|
|
151
|
+
boundaryUpdate = { value: undefined }
|
|
152
|
+
break
|
|
153
|
+
case "session.tool.success":
|
|
154
|
+
case "session.tool.failed":
|
|
155
|
+
dirty.add(event.data.assistantMessageID)
|
|
156
|
+
append = true
|
|
157
|
+
break
|
|
158
|
+
case "session.inbox.delivered":
|
|
159
|
+
case "session.execution.succeeded":
|
|
160
|
+
case "session.execution.failed":
|
|
161
|
+
case "session.execution.interrupted":
|
|
162
|
+
append = true
|
|
163
|
+
break
|
|
164
|
+
default:
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
if (failed) reload = true
|
|
168
|
+
schedule()
|
|
169
|
+
})
|
|
170
|
+
publish({ status: "loading" })
|
|
171
|
+
schedule()
|
|
172
|
+
return {
|
|
173
|
+
refresh,
|
|
174
|
+
dispose() {
|
|
175
|
+
abort.abort()
|
|
176
|
+
unsubscribe()
|
|
177
|
+
messages.clear()
|
|
178
|
+
},
|
|
179
|
+
}
|
|
180
|
+
}
|
package/src/tui.tsx
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { Plugin } from "@opencode/plugin/tui"
|
|
2
|
+
import { createEffect, createMemo, createSignal, onCleanup, Show } from "solid-js"
|
|
3
|
+
import { openSessionHistory, type HistoryState } from "./session-history"
|
|
4
|
+
import { ChangesDialog } from "./ui/changes"
|
|
5
|
+
import { ChangesSidebar } from "./ui/changes-sidebar"
|
|
6
|
+
|
|
7
|
+
const id = "opencode-change-history"
|
|
8
|
+
const openCommand = `${id}.open`
|
|
9
|
+
const loading: HistoryState = { status: "loading" }
|
|
10
|
+
|
|
11
|
+
export default Plugin.define({
|
|
12
|
+
id,
|
|
13
|
+
setup(context) {
|
|
14
|
+
const session = createMemo(() => {
|
|
15
|
+
const route = context.ui.router.current()
|
|
16
|
+
return route.type === "session" ? route.sessionID : undefined
|
|
17
|
+
})
|
|
18
|
+
const [state, setState] = createSignal<{ sessionID: string; value: HistoryState }>()
|
|
19
|
+
let history: { sessionID: string; refresh: () => void } | undefined
|
|
20
|
+
let activeDialog: { sessionID: string; select: (path: string) => void } | undefined
|
|
21
|
+
const dialog = context.ui.dialog
|
|
22
|
+
const stateFor = (sessionID: string) => {
|
|
23
|
+
const current = state()
|
|
24
|
+
return current?.sessionID === sessionID ? current.value : loading
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function open(path?: string) {
|
|
28
|
+
const sessionID = session()
|
|
29
|
+
if (!sessionID) return
|
|
30
|
+
if (activeDialog?.sessionID === sessionID) {
|
|
31
|
+
if (path !== undefined) activeDialog.select(path)
|
|
32
|
+
return
|
|
33
|
+
}
|
|
34
|
+
const [request, setRequest] = createSignal(path === undefined ? undefined : { path })
|
|
35
|
+
const opened = { sessionID, select: (path: string) => setRequest({ path }) }
|
|
36
|
+
activeDialog = opened
|
|
37
|
+
dialog.show(
|
|
38
|
+
() => <ChangesDialog context={context} state={stateFor(sessionID)} request={request()}
|
|
39
|
+
close={() => { if (activeDialog === opened) dialog.clear() }}
|
|
40
|
+
refresh={() => { if (history?.sessionID === sessionID) history.refresh() }} />,
|
|
41
|
+
() => { if (activeDialog === opened) activeDialog = undefined },
|
|
42
|
+
)
|
|
43
|
+
if (activeDialog === opened) dialog.set({ size: "xlarge", centered: true })
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
context.ui.slot({
|
|
47
|
+
append: "app",
|
|
48
|
+
render() {
|
|
49
|
+
createEffect(() => {
|
|
50
|
+
const sessionID = session()
|
|
51
|
+
setState(undefined)
|
|
52
|
+
if (!sessionID) return
|
|
53
|
+
const subscription = openSessionHistory(sessionID, context.client, context.data.listen, (value) => {
|
|
54
|
+
setState({ sessionID, value })
|
|
55
|
+
})
|
|
56
|
+
history = { sessionID, refresh: subscription.refresh }
|
|
57
|
+
onCleanup(() => {
|
|
58
|
+
subscription.dispose()
|
|
59
|
+
history = undefined
|
|
60
|
+
if (activeDialog?.sessionID === sessionID) dialog.clear()
|
|
61
|
+
})
|
|
62
|
+
})
|
|
63
|
+
context.keymap.layer(() => ({
|
|
64
|
+
mode: "global",
|
|
65
|
+
commands: [{
|
|
66
|
+
id: openCommand,
|
|
67
|
+
title: "Session change history",
|
|
68
|
+
group: "Session",
|
|
69
|
+
bind: "<leader>h",
|
|
70
|
+
enabled: () => session() !== undefined,
|
|
71
|
+
palette: true,
|
|
72
|
+
slash: { name: "changes" },
|
|
73
|
+
run: () => open(),
|
|
74
|
+
}],
|
|
75
|
+
bindings: [openCommand],
|
|
76
|
+
}))
|
|
77
|
+
return null
|
|
78
|
+
},
|
|
79
|
+
})
|
|
80
|
+
context.ui.slot({
|
|
81
|
+
append: "sidebar.content",
|
|
82
|
+
render: (input) => (
|
|
83
|
+
<Show when={input.sessionID} keyed>
|
|
84
|
+
{(sessionID) => <ChangesSidebar context={context} state={stateFor(sessionID)} open={open} />}
|
|
85
|
+
</Show>
|
|
86
|
+
),
|
|
87
|
+
})
|
|
88
|
+
return () => { if (activeDialog) dialog.clear() }
|
|
89
|
+
},
|
|
90
|
+
})
|