Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions packages/app/src/pages/session/timeline/rows.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { describe, expect, test } from "bun:test"
import type { SnapshotFileDiff, UserMessage } from "@opencode-ai/sdk/v2"
import { Timeline } from "./rows"

const userMessage = (diffs: SnapshotFileDiff[]) =>
({
id: "msg_user",
sessionID: "ses_test",
role: "user",
time: { created: 1 },
summary: { diffs },
agent: "build",
model: {
providerID: "provider",
modelID: "model",
},
}) satisfies UserMessage

const diff = (file: string, patch: string) =>
({
file,
patch,
additions: 1,
deletions: 0,
status: "modified",
}) satisfies SnapshotFileDiff

class CountedDiff implements SnapshotFileDiff {
readonly patch = ""
readonly additions = 1
readonly deletions = 0
readonly status = "modified"
private reads = 0

constructor(private readonly name: string) {}

get file() {
this.reads += 1
return this.name
}

get fileReads() {
return this.reads
}
}

const diffSummary = (message: UserMessage) =>
Timeline.constructMessageRows(message, () => [], [], 0, true, "idle", false).find((row) => row._tag === "DiffSummary")

describe("timeline rows", () => {
test("keeps the last visible diff for each file in original order", () => {
const row = diffSummary(
userMessage([
diff("alpha.ts", "old alpha"),
diff("beta.ts", "beta"),
{ patch: "missing file", additions: 1, deletions: 0 },
diff("alpha.ts", "new alpha"),
]),
)

expect(row?._tag).toBe("DiffSummary")
expect(row?.diffs).toEqual([diff("beta.ts", "beta"), diff("alpha.ts", "new alpha")])
})

test("builds large unique diff summaries without dropping visible files", () => {
const diffs = Array.from({ length: 12_000 }, (_item, index) => new CountedDiff(`file-${index}.ts`))
const row = diffSummary(userMessage(diffs))

expect(row?._tag).toBe("DiffSummary")
expect(row?.diffs).toHaveLength(12_000)
expect(row?.diffs.at(0)?.file).toBe("file-0.ts")
expect(row?.diffs.at(-1)?.file).toBe("file-11999.ts")
expect(diffs.reduce((total, item) => total + item.fileReads, 0)).toBeLessThanOrEqual(diffs.length + 2)
})
})
23 changes: 13 additions & 10 deletions packages/app/src/pages/session/timeline/rows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,14 +210,7 @@ export namespace Timeline {

if (isActive && status === "retry") rows.push(new TimelineRow.Retry({ userMessageID: userMessage.id }))

const diffs = (userMessage.summary?.diffs ?? [])
.reduceRight<SummaryDiff[]>((result, diff) => {
if (!isSummaryDiff(diff)) return result
if (result.some((item) => item.file === diff.file)) return result
result.push(diff)
return result
}, [])
.reverse()
const diffs = uniqueSummaryDiffs(userMessage.summary?.diffs ?? [])
if (diffs.length > 0 && (status === "idle" || !isActive)) {
rows.push(
new TimelineRow.DiffSummary({
Expand All @@ -242,8 +235,18 @@ export namespace Timeline {
return rows
}

function isSummaryDiff(value: SnapshotFileDiff): value is SummaryDiff {
return typeof value.file === "string"
function uniqueSummaryDiffs(diffs: SnapshotFileDiff[]) {
const files = new Set<string>()
return diffs
.reduceRight<SummaryDiff[]>((result, diff) => {
const file = diff.file
if (typeof file !== "string") return result
if (files.has(file)) return result
files.add(file)
result.push({ ...diff, file })
return result
}, [])
.reverse()
}

function reasoningHeading(text: string) {
Expand Down
3 changes: 2 additions & 1 deletion packages/desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
type SidecarListener,
} from "./server"
import { setupAutoUpdater, showUpdaterDialog } from "./updater"
import { safeWebContentsURL } from "./window-state"
import {
createMainWindow,
registerRendererProtocol,
Expand Down Expand Up @@ -219,7 +220,7 @@ const main = Effect.gen(function* () {
})

app.on("render-process-gone", (_event, webContents, details) => {
writeLog("window", "app render process gone", { url: webContents.getURL(), details }, "error")
writeLog("window", "app render process gone", { url: safeWebContentsURL(webContents), details }, "error")
})

setRelaunchHandler(() => {
Expand Down
3 changes: 2 additions & 1 deletion packages/desktop/src/main/unresponsive.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { BrowserWindow } from "electron"
import { write as writeLog } from "./logging"
import { safeWindowURL } from "./window-state"

const sampleInterval = 1000
const samplePeriod = 15000
Expand Down Expand Up @@ -46,7 +47,7 @@ export function createUnresponsiveSampler(win: BrowserWindow, name: string) {
const message = [
"renderer unresponsive samples",
`Window: ${name}`,
`URL: ${win.isDestroyed() ? "<destroyed>" : win.webContents.getURL()}`,
`URL: ${safeWindowURL(win)}`,
...entries.map((entry) => `<${entry[1]}> ${entry[0]}`),
`Total Samples: ${total}`,
].join("\n")
Expand Down
34 changes: 34 additions & 0 deletions packages/desktop/src/main/window-state.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { describe, expect, test } from "bun:test"
import { destroyedWindowURL, safeWebContentsURL, safeWindowURL } from "./window-state"

const webContents = (input: { destroyed?: boolean; url?: string; throws?: boolean }) => ({
isDestroyed: () => input.destroyed === true,
getURL: () => {
if (input.throws) throw new Error("Object has been destroyed")
return input.url ?? "oc://renderer/index.html"
},
})

const windowState = (input: { destroyed?: boolean; webContents?: ReturnType<typeof webContents>; throws?: boolean }) => ({
isDestroyed: () => input.destroyed === true,
get webContents() {
if (input.throws) throw new Error("Object has been destroyed")
return input.webContents ?? webContents({})
},
})

describe("safeWindowURL", () => {
test("returns the current renderer URL while the window is alive", () => {
expect(safeWindowURL(windowState({ webContents: webContents({ url: "oc://renderer/session" }) }))).toBe(
"oc://renderer/session",
)
})

test("returns a destroyed marker when Electron objects are already disposed", () => {
expect(safeWindowURL(windowState({ destroyed: true }))).toBe(destroyedWindowURL)
expect(safeWindowURL(windowState({ webContents: webContents({ destroyed: true }) }))).toBe(destroyedWindowURL)
expect(safeWindowURL(windowState({ throws: true }))).toBe(destroyedWindowURL)
expect(safeWindowURL(windowState({ webContents: webContents({ throws: true }) }))).toBe(destroyedWindowURL)
expect(safeWebContentsURL(webContents({ destroyed: true }))).toBe(destroyedWindowURL)
})
})
29 changes: 29 additions & 0 deletions packages/desktop/src/main/window-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
export const destroyedWindowURL = "<destroyed>"

type WebContentsURLState = {
isDestroyed(): boolean
getURL(): string
}

type WindowURLState = {
isDestroyed(): boolean
readonly webContents: WebContentsURLState
}

export function safeWebContentsURL(webContents: WebContentsURLState) {
try {
if (webContents.isDestroyed()) return destroyedWindowURL
return webContents.getURL()
} catch {
return destroyedWindowURL
}
}

export function safeWindowURL(win: WindowURLState) {
try {
if (win.isDestroyed()) return destroyedWindowURL
return safeWebContentsURL(win.webContents)
} catch {
return destroyedWindowURL
}
}
9 changes: 5 additions & 4 deletions packages/desktop/src/main/windows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { exportDebugLogs, write as writeLog } from "./logging"
import { getStore } from "./store"
import { PINCH_ZOOM_ENABLED_KEY } from "./store-keys"
import { createUnresponsiveSampler } from "./unresponsive"
import { safeWindowURL } from "./window-state"

const root = dirname(fileURLToPath(import.meta.url))
const rendererRoot = join(root, "../renderer")
Expand Down Expand Up @@ -293,7 +294,7 @@ function wireWindowRecovery(win: BrowserWindow, name: string) {
errorCode,
errorDescription,
validatedURL,
currentURL: win.webContents.getURL(),
currentURL: safeWindowURL(win),
isMainFrame,
},
"error",
Expand All @@ -318,7 +319,7 @@ function wireWindowRecovery(win: BrowserWindow, name: string) {
writeLog(
"window",
"renderer process gone",
{ window: name, currentURL: win.webContents.getURL(), details },
{ window: name, currentURL: safeWindowURL(win), details },
"error",
)
void show(
Expand All @@ -328,12 +329,12 @@ function wireWindowRecovery(win: BrowserWindow, name: string) {
)
})
win.on("unresponsive", () => {
writeLog("window", "renderer unresponsive", { window: name, currentURL: win.webContents.getURL() }, "error")
writeLog("window", "renderer unresponsive", { window: name, currentURL: safeWindowURL(win) }, "error")
sampler.start()
void show("OpenCode is not responding", "You can relaunch the app, open the logs, or keep waiting.", true)
})
win.on("responsive", () => {
writeLog("window", "renderer responsive", { window: name, currentURL: win.webContents.getURL() }, "error")
writeLog("window", "renderer responsive", { window: name, currentURL: safeWindowURL(win) }, "error")
sampler.stopAndFlush()
})
win.webContents.on("console-message", (_event, level, message, line, sourceId) => {
Expand Down
Loading