Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2c4365fa0 | ||
|
|
1033d0c46c | ||
|
|
00cb8839ae | ||
|
|
689b1a4b3a | ||
|
|
d98be39344 | ||
|
|
7988a76a25 | ||
|
|
5e54c54134 | ||
|
|
0f3a2a7b67 | ||
|
|
186063fbed |
@@ -14,6 +14,7 @@ import type {
|
|||||||
import type { State, VcsCache } from "./types"
|
import type { State, VcsCache } from "./types"
|
||||||
import { trimSessions } from "./session-trim"
|
import { trimSessions } from "./session-trim"
|
||||||
import { dropSessionCaches } from "./session-cache"
|
import { dropSessionCaches } from "./session-cache"
|
||||||
|
import { diffs as list, message as clean } from "@/utils/diffs"
|
||||||
|
|
||||||
const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"])
|
const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"])
|
||||||
|
|
||||||
@@ -162,7 +163,7 @@ export function applyDirectoryEvent(input: {
|
|||||||
}
|
}
|
||||||
case "session.diff": {
|
case "session.diff": {
|
||||||
const props = event.properties as { sessionID: string; diff: SnapshotFileDiff[] }
|
const props = event.properties as { sessionID: string; diff: SnapshotFileDiff[] }
|
||||||
input.setStore("session_diff", props.sessionID, reconcile(props.diff, { key: "file" }))
|
input.setStore("session_diff", props.sessionID, reconcile(list(props.diff), { key: "file" }))
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
case "todo.updated": {
|
case "todo.updated": {
|
||||||
@@ -177,7 +178,7 @@ export function applyDirectoryEvent(input: {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
case "message.updated": {
|
case "message.updated": {
|
||||||
const info = (event.properties as { info: Message }).info
|
const info = clean((event.properties as { info: Message }).info)
|
||||||
const messages = input.store.message[info.sessionID]
|
const messages = input.store.message[info.sessionID]
|
||||||
if (!messages) {
|
if (!messages) {
|
||||||
input.setStore("message", info.sessionID, [info])
|
input.setStore("message", info.sessionID, [info])
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { useGlobalSync } from "./global-sync"
|
|||||||
import { useSDK } from "./sdk"
|
import { useSDK } from "./sdk"
|
||||||
import type { Message, Part } from "@opencode-ai/sdk/v2/client"
|
import type { Message, Part } from "@opencode-ai/sdk/v2/client"
|
||||||
import { SESSION_CACHE_LIMIT, dropSessionCaches, pickSessionCacheEvictions } from "./global-sync/session-cache"
|
import { SESSION_CACHE_LIMIT, dropSessionCaches, pickSessionCacheEvictions } from "./global-sync/session-cache"
|
||||||
|
import { diffs as list, message as clean } from "@/utils/diffs"
|
||||||
|
|
||||||
const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"])
|
const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"])
|
||||||
|
|
||||||
@@ -300,7 +301,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
|
|||||||
input.client.session.messages({ sessionID: input.sessionID, limit: input.limit, before: input.before }),
|
input.client.session.messages({ sessionID: input.sessionID, limit: input.limit, before: input.before }),
|
||||||
)
|
)
|
||||||
const items = (messages.data ?? []).filter((x) => !!x?.info?.id)
|
const items = (messages.data ?? []).filter((x) => !!x?.info?.id)
|
||||||
const session = items.map((x) => x.info).sort((a, b) => cmp(a.id, b.id))
|
const session = items.map((x) => clean(x.info)).sort((a, b) => cmp(a.id, b.id))
|
||||||
const part = items.map((message) => ({ id: message.info.id, part: sortParts(message.parts) }))
|
const part = items.map((message) => ({ id: message.info.id, part: sortParts(message.parts) }))
|
||||||
const cursor = messages.response.headers.get("x-next-cursor") ?? undefined
|
const cursor = messages.response.headers.get("x-next-cursor") ?? undefined
|
||||||
return {
|
return {
|
||||||
@@ -509,7 +510,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
|
|||||||
return runInflight(inflightDiff, key, () =>
|
return runInflight(inflightDiff, key, () =>
|
||||||
retry(() => client.session.diff({ sessionID })).then((diff) => {
|
retry(() => client.session.diff({ sessionID })).then((diff) => {
|
||||||
if (!tracked(directory, sessionID)) return
|
if (!tracked(directory, sessionID)) return
|
||||||
setStore("session_diff", sessionID, reconcile(diff.data ?? [], { key: "file" }))
|
setStore("session_diff", sessionID, reconcile(list(diff.data), { key: "file" }))
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ import { TerminalPanel } from "@/pages/session/terminal-panel"
|
|||||||
import { useSessionCommands } from "@/pages/session/use-session-commands"
|
import { useSessionCommands } from "@/pages/session/use-session-commands"
|
||||||
import { useSessionHashScroll } from "@/pages/session/use-session-hash-scroll"
|
import { useSessionHashScroll } from "@/pages/session/use-session-hash-scroll"
|
||||||
import { Identifier } from "@/utils/id"
|
import { Identifier } from "@/utils/id"
|
||||||
|
import { diffs as list } from "@/utils/diffs"
|
||||||
import { Persist, persisted } from "@/utils/persist"
|
import { Persist, persisted } from "@/utils/persist"
|
||||||
import { extractPromptFromParts } from "@/utils/prompt"
|
import { extractPromptFromParts } from "@/utils/prompt"
|
||||||
import { same } from "@/utils/same"
|
import { same } from "@/utils/same"
|
||||||
@@ -430,7 +431,7 @@ export default function Page() {
|
|||||||
|
|
||||||
const info = createMemo(() => (params.id ? sync.session.get(params.id) : undefined))
|
const info = createMemo(() => (params.id ? sync.session.get(params.id) : undefined))
|
||||||
const isChildSession = createMemo(() => !!info()?.parentID)
|
const isChildSession = createMemo(() => !!info()?.parentID)
|
||||||
const diffs = createMemo(() => (params.id ? (sync.data.session_diff[params.id] ?? []) : []))
|
const diffs = createMemo(() => (params.id ? list(sync.data.session_diff[params.id]) : []))
|
||||||
const sessionCount = createMemo(() => Math.max(info()?.summary?.files ?? 0, diffs().length))
|
const sessionCount = createMemo(() => Math.max(info()?.summary?.files ?? 0, diffs().length))
|
||||||
const hasSessionReview = createMemo(() => sessionCount() > 0)
|
const hasSessionReview = createMemo(() => sessionCount() > 0)
|
||||||
const canReview = createMemo(() => !!sync.project)
|
const canReview = createMemo(() => !!sync.project)
|
||||||
@@ -611,7 +612,7 @@ export default function Page() {
|
|||||||
.diff({ mode })
|
.diff({ mode })
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
if (vcsRun.get(mode) !== run) return
|
if (vcsRun.get(mode) !== run) return
|
||||||
setVcs("diff", mode, result.data ?? [])
|
setVcs("diff", mode, list(result.data))
|
||||||
setVcs("ready", mode, true)
|
setVcs("ready", mode, true)
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
@@ -649,7 +650,7 @@ export default function Page() {
|
|||||||
return open
|
return open
|
||||||
}, desktopReviewOpen())
|
}, desktopReviewOpen())
|
||||||
|
|
||||||
const turnDiffs = createMemo(() => lastUserMessage()?.summary?.diffs ?? [])
|
const turnDiffs = createMemo(() => list(lastUserMessage()?.summary?.diffs))
|
||||||
const nogit = createMemo(() => !!sync.project && sync.project.vcs !== "git")
|
const nogit = createMemo(() => !!sync.project && sync.project.vcs !== "git")
|
||||||
const changesOptions = createMemo<ChangeMode[]>(() => {
|
const changesOptions = createMemo<ChangeMode[]>(() => {
|
||||||
const list: ChangeMode[] = []
|
const list: ChangeMode[] = []
|
||||||
@@ -669,15 +670,11 @@ export default function Page() {
|
|||||||
if (store.changes === "git" || store.changes === "branch") return store.changes
|
if (store.changes === "git" || store.changes === "branch") return store.changes
|
||||||
})
|
})
|
||||||
const reviewDiffs = createMemo(() => {
|
const reviewDiffs = createMemo(() => {
|
||||||
if (store.changes === "git") return vcs.diff.git
|
if (store.changes === "git") return list(vcs.diff.git)
|
||||||
if (store.changes === "branch") return vcs.diff.branch
|
if (store.changes === "branch") return list(vcs.diff.branch)
|
||||||
return turnDiffs()
|
return turnDiffs()
|
||||||
})
|
})
|
||||||
const reviewCount = createMemo(() => {
|
const reviewCount = createMemo(() => reviewDiffs().length)
|
||||||
if (store.changes === "git") return vcs.diff.git.length
|
|
||||||
if (store.changes === "branch") return vcs.diff.branch.length
|
|
||||||
return turnDiffs().length
|
|
||||||
})
|
|
||||||
const hasReview = createMemo(() => reviewCount() > 0)
|
const hasReview = createMemo(() => reviewCount() > 0)
|
||||||
const reviewReady = createMemo(() => {
|
const reviewReady = createMemo(() => {
|
||||||
if (store.changes === "git") return vcs.ready.git
|
if (store.changes === "git") return vcs.ready.git
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { describe, expect, test } from "bun:test"
|
||||||
|
import type { SnapshotFileDiff } from "@opencode-ai/sdk/v2"
|
||||||
|
import type { Message } from "@opencode-ai/sdk/v2/client"
|
||||||
|
import { diffs, message } from "./diffs"
|
||||||
|
|
||||||
|
const item = {
|
||||||
|
file: "src/app.ts",
|
||||||
|
patch: "@@ -1 +1 @@\n-old\n+new\n",
|
||||||
|
additions: 1,
|
||||||
|
deletions: 1,
|
||||||
|
status: "modified",
|
||||||
|
} satisfies SnapshotFileDiff
|
||||||
|
|
||||||
|
describe("diffs", () => {
|
||||||
|
test("keeps valid arrays", () => {
|
||||||
|
expect(diffs([item])).toEqual([item])
|
||||||
|
})
|
||||||
|
|
||||||
|
test("wraps a single diff object", () => {
|
||||||
|
expect(diffs(item)).toEqual([item])
|
||||||
|
})
|
||||||
|
|
||||||
|
test("reads keyed diff objects", () => {
|
||||||
|
expect(diffs({ a: item })).toEqual([item])
|
||||||
|
})
|
||||||
|
|
||||||
|
test("drops invalid entries", () => {
|
||||||
|
expect(
|
||||||
|
diffs([
|
||||||
|
item,
|
||||||
|
{ file: "src/bad.ts", additions: 1, deletions: 1 },
|
||||||
|
{ patch: item.patch, additions: 1, deletions: 1 },
|
||||||
|
]),
|
||||||
|
).toEqual([item])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("message", () => {
|
||||||
|
test("normalizes user summaries with object diffs", () => {
|
||||||
|
const input = {
|
||||||
|
id: "msg_1",
|
||||||
|
sessionID: "ses_1",
|
||||||
|
role: "user",
|
||||||
|
time: { created: 1 },
|
||||||
|
agent: "build",
|
||||||
|
model: { providerID: "openai", modelID: "gpt-5" },
|
||||||
|
summary: {
|
||||||
|
title: "Edit",
|
||||||
|
diffs: { a: item },
|
||||||
|
},
|
||||||
|
} as unknown as Message
|
||||||
|
|
||||||
|
expect(message(input)).toMatchObject({
|
||||||
|
summary: {
|
||||||
|
title: "Edit",
|
||||||
|
diffs: [item],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test("drops invalid user summaries", () => {
|
||||||
|
const input = {
|
||||||
|
id: "msg_1",
|
||||||
|
sessionID: "ses_1",
|
||||||
|
role: "user",
|
||||||
|
time: { created: 1 },
|
||||||
|
agent: "build",
|
||||||
|
model: { providerID: "openai", modelID: "gpt-5" },
|
||||||
|
summary: true,
|
||||||
|
} as unknown as Message
|
||||||
|
|
||||||
|
expect(message(input)).toMatchObject({ summary: undefined })
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import type { SnapshotFileDiff, VcsFileDiff } from "@opencode-ai/sdk/v2"
|
||||||
|
import type { Message } from "@opencode-ai/sdk/v2/client"
|
||||||
|
|
||||||
|
type Diff = SnapshotFileDiff | VcsFileDiff
|
||||||
|
|
||||||
|
function diff(value: unknown): value is Diff {
|
||||||
|
if (!value || typeof value !== "object" || Array.isArray(value)) return false
|
||||||
|
if (!("file" in value) || typeof value.file !== "string") return false
|
||||||
|
if (!("patch" in value) || typeof value.patch !== "string") return false
|
||||||
|
if (!("additions" in value) || typeof value.additions !== "number") return false
|
||||||
|
if (!("deletions" in value) || typeof value.deletions !== "number") return false
|
||||||
|
if (!("status" in value) || value.status === undefined) return true
|
||||||
|
return value.status === "added" || value.status === "deleted" || value.status === "modified"
|
||||||
|
}
|
||||||
|
|
||||||
|
function object(value: unknown): value is Record<string, unknown> {
|
||||||
|
return !!value && typeof value === "object" && !Array.isArray(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function diffs(value: unknown): Diff[] {
|
||||||
|
if (Array.isArray(value) && value.every(diff)) return value
|
||||||
|
if (Array.isArray(value)) return value.filter(diff)
|
||||||
|
if (diff(value)) return [value]
|
||||||
|
if (!object(value)) return []
|
||||||
|
return Object.values(value).filter(diff)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function message(value: Message): Message {
|
||||||
|
if (value.role !== "user") return value
|
||||||
|
|
||||||
|
const raw = value.summary as unknown
|
||||||
|
if (raw === undefined) return value
|
||||||
|
if (!object(raw)) return { ...value, summary: undefined }
|
||||||
|
|
||||||
|
const title = typeof raw.title === "string" ? raw.title : undefined
|
||||||
|
const body = typeof raw.body === "string" ? raw.body : undefined
|
||||||
|
const next = diffs(raw.diffs)
|
||||||
|
|
||||||
|
if (title === raw.title && body === raw.body && next === raw.diffs) return value
|
||||||
|
|
||||||
|
return {
|
||||||
|
...value,
|
||||||
|
summary: {
|
||||||
|
...(title === undefined ? {} : { title }),
|
||||||
|
...(body === undefined ? {} : { body }),
|
||||||
|
diffs: next,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -376,7 +376,8 @@ export namespace ProviderTransform {
|
|||||||
id.includes("mistral") ||
|
id.includes("mistral") ||
|
||||||
id.includes("kimi") ||
|
id.includes("kimi") ||
|
||||||
id.includes("k2p5") ||
|
id.includes("k2p5") ||
|
||||||
id.includes("qwen")
|
id.includes("qwen") ||
|
||||||
|
id.includes("big-pickle")
|
||||||
)
|
)
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|||||||
@@ -600,7 +600,11 @@ NOTE: At any point in time through this workflow you should feel free to ask the
|
|||||||
subagent_type: task.agent,
|
subagent_type: task.agent,
|
||||||
command: task.command,
|
command: task.command,
|
||||||
}
|
}
|
||||||
yield* plugin.trigger("tool.execute.before", { tool: "task", sessionID, callID: part.id }, { args: taskArgs })
|
yield* plugin.trigger(
|
||||||
|
"tool.execute.before",
|
||||||
|
{ tool: TaskTool.id, sessionID, callID: part.id },
|
||||||
|
{ args: taskArgs },
|
||||||
|
)
|
||||||
|
|
||||||
const taskAgent = yield* agents.get(task.agent)
|
const taskAgent = yield* agents.get(task.agent)
|
||||||
if (!taskAgent) {
|
if (!taskAgent) {
|
||||||
@@ -679,7 +683,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the
|
|||||||
|
|
||||||
yield* plugin.trigger(
|
yield* plugin.trigger(
|
||||||
"tool.execute.after",
|
"tool.execute.after",
|
||||||
{ tool: "task", sessionID, callID: part.id, args: taskArgs },
|
{ tool: TaskTool.id, sessionID, callID: part.id, args: taskArgs },
|
||||||
result,
|
result,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -50,6 +50,10 @@ export namespace ToolRegistry {
|
|||||||
export interface Interface {
|
export interface Interface {
|
||||||
readonly ids: () => Effect.Effect<string[]>
|
readonly ids: () => Effect.Effect<string[]>
|
||||||
readonly all: () => Effect.Effect<Tool.Def[]>
|
readonly all: () => Effect.Effect<Tool.Def[]>
|
||||||
|
readonly named: {
|
||||||
|
task: Tool.Info
|
||||||
|
read: Tool.Info
|
||||||
|
}
|
||||||
readonly tools: (model: {
|
readonly tools: (model: {
|
||||||
providerID: ProviderID
|
providerID: ProviderID
|
||||||
modelID: ModelID
|
modelID: ModelID
|
||||||
@@ -67,6 +71,7 @@ export namespace ToolRegistry {
|
|||||||
| Plugin.Service
|
| Plugin.Service
|
||||||
| Question.Service
|
| Question.Service
|
||||||
| Todo.Service
|
| Todo.Service
|
||||||
|
| Agent.Service
|
||||||
| LSP.Service
|
| LSP.Service
|
||||||
| FileTime.Service
|
| FileTime.Service
|
||||||
| Instruction.Service
|
| Instruction.Service
|
||||||
@@ -77,8 +82,10 @@ export namespace ToolRegistry {
|
|||||||
const config = yield* Config.Service
|
const config = yield* Config.Service
|
||||||
const plugin = yield* Plugin.Service
|
const plugin = yield* Plugin.Service
|
||||||
|
|
||||||
const build = <T extends Tool.Info>(tool: T | Effect.Effect<T, never, any>) =>
|
const task = yield* TaskTool
|
||||||
Effect.isEffect(tool) ? tool.pipe(Effect.flatMap(Tool.init)) : Tool.init(tool)
|
const read = yield* ReadTool
|
||||||
|
const question = yield* QuestionTool
|
||||||
|
const todo = yield* TodoWriteTool
|
||||||
|
|
||||||
const state = yield* InstanceState.make<State>(
|
const state = yield* InstanceState.make<State>(
|
||||||
Effect.fn("ToolRegistry.state")(function* (ctx) {
|
Effect.fn("ToolRegistry.state")(function* (ctx) {
|
||||||
@@ -90,11 +97,11 @@ export namespace ToolRegistry {
|
|||||||
parameters: z.object(def.args),
|
parameters: z.object(def.args),
|
||||||
description: def.description,
|
description: def.description,
|
||||||
execute: async (args, toolCtx) => {
|
execute: async (args, toolCtx) => {
|
||||||
const pluginCtx = {
|
const pluginCtx: PluginToolContext = {
|
||||||
...toolCtx,
|
...toolCtx,
|
||||||
directory: ctx.directory,
|
directory: ctx.directory,
|
||||||
worktree: ctx.worktree,
|
worktree: ctx.worktree,
|
||||||
} as unknown as PluginToolContext
|
}
|
||||||
const result = await def.execute(args as any, pluginCtx)
|
const result = await def.execute(args as any, pluginCtx)
|
||||||
const out = await Truncate.output(result, {}, await Agent.get(toolCtx.agent))
|
const out = await Truncate.output(result, {}, await Agent.get(toolCtx.agent))
|
||||||
return {
|
return {
|
||||||
@@ -132,34 +139,50 @@ export namespace ToolRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const cfg = yield* config.get()
|
const cfg = yield* config.get()
|
||||||
const question =
|
const questionEnabled =
|
||||||
["app", "cli", "desktop"].includes(Flag.OPENCODE_CLIENT) || Flag.OPENCODE_ENABLE_QUESTION_TOOL
|
["app", "cli", "desktop"].includes(Flag.OPENCODE_CLIENT) || Flag.OPENCODE_ENABLE_QUESTION_TOOL
|
||||||
|
|
||||||
|
const tool = yield* Effect.all({
|
||||||
|
invalid: Tool.init(InvalidTool),
|
||||||
|
bash: Tool.init(BashTool),
|
||||||
|
read: Tool.init(read),
|
||||||
|
glob: Tool.init(GlobTool),
|
||||||
|
grep: Tool.init(GrepTool),
|
||||||
|
edit: Tool.init(EditTool),
|
||||||
|
write: Tool.init(WriteTool),
|
||||||
|
task: Tool.init(task),
|
||||||
|
fetch: Tool.init(WebFetchTool),
|
||||||
|
todo: Tool.init(todo),
|
||||||
|
search: Tool.init(WebSearchTool),
|
||||||
|
code: Tool.init(CodeSearchTool),
|
||||||
|
skill: Tool.init(SkillTool),
|
||||||
|
patch: Tool.init(ApplyPatchTool),
|
||||||
|
question: Tool.init(question),
|
||||||
|
lsp: Tool.init(LspTool),
|
||||||
|
plan: Tool.init(PlanExitTool),
|
||||||
|
})
|
||||||
|
|
||||||
return {
|
return {
|
||||||
custom,
|
custom,
|
||||||
builtin: yield* Effect.forEach(
|
builtin: [
|
||||||
[
|
tool.invalid,
|
||||||
InvalidTool,
|
...(questionEnabled ? [tool.question] : []),
|
||||||
BashTool,
|
tool.bash,
|
||||||
ReadTool,
|
tool.read,
|
||||||
GlobTool,
|
tool.glob,
|
||||||
GrepTool,
|
tool.grep,
|
||||||
EditTool,
|
tool.edit,
|
||||||
WriteTool,
|
tool.write,
|
||||||
TaskTool,
|
tool.task,
|
||||||
WebFetchTool,
|
tool.fetch,
|
||||||
TodoWriteTool,
|
tool.todo,
|
||||||
WebSearchTool,
|
tool.search,
|
||||||
CodeSearchTool,
|
tool.code,
|
||||||
SkillTool,
|
tool.skill,
|
||||||
ApplyPatchTool,
|
tool.patch,
|
||||||
...(question ? [QuestionTool] : []),
|
...(Flag.OPENCODE_EXPERIMENTAL_LSP_TOOL ? [tool.lsp] : []),
|
||||||
...(Flag.OPENCODE_EXPERIMENTAL_LSP_TOOL ? [LspTool] : []),
|
...(Flag.OPENCODE_EXPERIMENTAL_PLAN_MODE && Flag.OPENCODE_CLIENT === "cli" ? [tool.plan] : []),
|
||||||
...(Flag.OPENCODE_EXPERIMENTAL_PLAN_MODE && Flag.OPENCODE_CLIENT === "cli" ? [PlanExitTool] : []),
|
],
|
||||||
],
|
|
||||||
build,
|
|
||||||
{ concurrency: "unbounded" },
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
@@ -208,7 +231,6 @@ export namespace ToolRegistry {
|
|||||||
id: tool.id,
|
id: tool.id,
|
||||||
description: [
|
description: [
|
||||||
output.description,
|
output.description,
|
||||||
// TODO: remove this hack
|
|
||||||
tool.id === TaskTool.id ? yield* TaskDescription(input.agent) : undefined,
|
tool.id === TaskTool.id ? yield* TaskDescription(input.agent) : undefined,
|
||||||
tool.id === SkillTool.id ? yield* SkillDescription(input.agent) : undefined,
|
tool.id === SkillTool.id ? yield* SkillDescription(input.agent) : undefined,
|
||||||
]
|
]
|
||||||
@@ -223,7 +245,7 @@ export namespace ToolRegistry {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
return Service.of({ ids, tools, all, fromID })
|
return Service.of({ ids, all, named: { task, read }, tools, fromID })
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -234,6 +256,7 @@ export namespace ToolRegistry {
|
|||||||
Layer.provide(Plugin.defaultLayer),
|
Layer.provide(Plugin.defaultLayer),
|
||||||
Layer.provide(Question.defaultLayer),
|
Layer.provide(Question.defaultLayer),
|
||||||
Layer.provide(Todo.defaultLayer),
|
Layer.provide(Todo.defaultLayer),
|
||||||
|
Layer.provide(Agent.defaultLayer),
|
||||||
Layer.provide(LSP.defaultLayer),
|
Layer.provide(LSP.defaultLayer),
|
||||||
Layer.provide(FileTime.defaultLayer),
|
Layer.provide(FileTime.defaultLayer),
|
||||||
Layer.provide(Instruction.defaultLayer),
|
Layer.provide(Instruction.defaultLayer),
|
||||||
|
|||||||
+146
-123
@@ -6,96 +6,101 @@ import { SessionID, MessageID } from "../session/schema"
|
|||||||
import { MessageV2 } from "../session/message-v2"
|
import { MessageV2 } from "../session/message-v2"
|
||||||
import { Agent } from "../agent/agent"
|
import { Agent } from "../agent/agent"
|
||||||
import { SessionPrompt } from "../session/prompt"
|
import { SessionPrompt } from "../session/prompt"
|
||||||
import { iife } from "@/util/iife"
|
|
||||||
import { defer } from "@/util/defer"
|
|
||||||
import { Config } from "../config/config"
|
import { Config } from "../config/config"
|
||||||
import { Permission } from "@/permission"
|
import { Permission } from "@/permission"
|
||||||
import { Effect } from "effect"
|
import { Effect } from "effect"
|
||||||
|
|
||||||
export const TaskTool = Tool.define("task", async () => {
|
const id = "task"
|
||||||
const agents = await Agent.list().then((x) => x.filter((a) => a.mode !== "primary"))
|
|
||||||
const list = agents.toSorted((a, b) => a.name.localeCompare(b.name))
|
|
||||||
const agentList = list
|
|
||||||
.map((a) => `- ${a.name}: ${a.description ?? "This subagent should only be called manually by the user."}`)
|
|
||||||
.join("\n")
|
|
||||||
const description = [`Available agent types and the tools they have access to:`, agentList].join("\n")
|
|
||||||
|
|
||||||
return {
|
const parameters = z.object({
|
||||||
description,
|
description: z.string().describe("A short (3-5 words) description of the task"),
|
||||||
parameters: z.object({
|
prompt: z.string().describe("The task for the agent to perform"),
|
||||||
description: z.string().describe("A short (3-5 words) description of the task"),
|
subagent_type: z.string().describe("The type of specialized agent to use for this task"),
|
||||||
prompt: z.string().describe("The task for the agent to perform"),
|
task_id: z
|
||||||
subagent_type: z.string().describe("The type of specialized agent to use for this task"),
|
.string()
|
||||||
task_id: z
|
.describe(
|
||||||
.string()
|
"This should only be set if you mean to resume a previous task (you can pass a prior task_id and the task will continue the same subagent session as before instead of creating a fresh one)",
|
||||||
.describe(
|
)
|
||||||
"This should only be set if you mean to resume a previous task (you can pass a prior task_id and the task will continue the same subagent session as before instead of creating a fresh one)",
|
.optional(),
|
||||||
)
|
command: z.string().describe("The command that triggered this task").optional(),
|
||||||
.optional(),
|
})
|
||||||
command: z.string().describe("The command that triggered this task").optional(),
|
|
||||||
}),
|
export const TaskTool = Tool.defineEffect(
|
||||||
async execute(params, ctx) {
|
id,
|
||||||
const config = await Config.get()
|
Effect.gen(function* () {
|
||||||
|
const agent = yield* Agent.Service
|
||||||
|
const config = yield* Config.Service
|
||||||
|
|
||||||
|
const run = Effect.fn("TaskTool.execute")(function* (params: z.infer<typeof parameters>, ctx: Tool.Context) {
|
||||||
|
const cfg = yield* config.get()
|
||||||
|
|
||||||
// Skip permission check when user explicitly invoked via @ or command subtask
|
|
||||||
if (!ctx.extra?.bypassAgentCheck) {
|
if (!ctx.extra?.bypassAgentCheck) {
|
||||||
await ctx.ask({
|
yield* Effect.promise(() =>
|
||||||
permission: "task",
|
ctx.ask({
|
||||||
patterns: [params.subagent_type],
|
permission: id,
|
||||||
always: ["*"],
|
patterns: [params.subagent_type],
|
||||||
metadata: {
|
always: ["*"],
|
||||||
description: params.description,
|
metadata: {
|
||||||
subagent_type: params.subagent_type,
|
description: params.description,
|
||||||
},
|
subagent_type: params.subagent_type,
|
||||||
})
|
},
|
||||||
|
}),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const agent = await Agent.get(params.subagent_type)
|
const next = yield* agent.get(params.subagent_type)
|
||||||
if (!agent) throw new Error(`Unknown agent type: ${params.subagent_type} is not a valid agent type`)
|
if (!next) {
|
||||||
|
return yield* Effect.fail(new Error(`Unknown agent type: ${params.subagent_type} is not a valid agent type`))
|
||||||
|
}
|
||||||
|
|
||||||
const hasTaskPermission = agent.permission.some((rule) => rule.permission === "task")
|
const canTask = next.permission.some((rule) => rule.permission === id)
|
||||||
const hasTodoWritePermission = agent.permission.some((rule) => rule.permission === "todowrite")
|
const canTodo = next.permission.some((rule) => rule.permission === "todowrite")
|
||||||
|
|
||||||
const session = await iife(async () => {
|
const taskID = params.task_id
|
||||||
if (params.task_id) {
|
const session = taskID
|
||||||
const found = await Session.get(SessionID.make(params.task_id)).catch(() => {})
|
? yield* Effect.promise(() => {
|
||||||
if (found) return found
|
const id = SessionID.make(taskID)
|
||||||
}
|
return Session.get(id).catch(() => undefined)
|
||||||
|
})
|
||||||
|
: undefined
|
||||||
|
const nextSession =
|
||||||
|
session ??
|
||||||
|
(yield* Effect.promise(() =>
|
||||||
|
Session.create({
|
||||||
|
parentID: ctx.sessionID,
|
||||||
|
title: params.description + ` (@${next.name} subagent)`,
|
||||||
|
permission: [
|
||||||
|
...(canTodo
|
||||||
|
? []
|
||||||
|
: [
|
||||||
|
{
|
||||||
|
permission: "todowrite" as const,
|
||||||
|
pattern: "*" as const,
|
||||||
|
action: "deny" as const,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
...(canTask
|
||||||
|
? []
|
||||||
|
: [
|
||||||
|
{
|
||||||
|
permission: id,
|
||||||
|
pattern: "*" as const,
|
||||||
|
action: "deny" as const,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
...(cfg.experimental?.primary_tools?.map((item) => ({
|
||||||
|
pattern: "*",
|
||||||
|
action: "allow" as const,
|
||||||
|
permission: item,
|
||||||
|
})) ?? []),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
))
|
||||||
|
|
||||||
return await Session.create({
|
const msg = yield* Effect.sync(() => MessageV2.get({ sessionID: ctx.sessionID, messageID: ctx.messageID }))
|
||||||
parentID: ctx.sessionID,
|
if (msg.info.role !== "assistant") return yield* Effect.fail(new Error("Not an assistant message"))
|
||||||
title: params.description + ` (@${agent.name} subagent)`,
|
|
||||||
permission: [
|
|
||||||
...(hasTodoWritePermission
|
|
||||||
? []
|
|
||||||
: [
|
|
||||||
{
|
|
||||||
permission: "todowrite" as const,
|
|
||||||
pattern: "*" as const,
|
|
||||||
action: "deny" as const,
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
...(hasTaskPermission
|
|
||||||
? []
|
|
||||||
: [
|
|
||||||
{
|
|
||||||
permission: "task" as const,
|
|
||||||
pattern: "*" as const,
|
|
||||||
action: "deny" as const,
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
...(config.experimental?.primary_tools?.map((t) => ({
|
|
||||||
pattern: "*",
|
|
||||||
action: "allow" as const,
|
|
||||||
permission: t,
|
|
||||||
})) ?? []),
|
|
||||||
],
|
|
||||||
})
|
|
||||||
})
|
|
||||||
const msg = await MessageV2.get({ sessionID: ctx.sessionID, messageID: ctx.messageID })
|
|
||||||
if (msg.info.role !== "assistant") throw new Error("Not an assistant message")
|
|
||||||
|
|
||||||
const model = agent.model ?? {
|
const model = next.model ?? {
|
||||||
modelID: msg.info.modelID,
|
modelID: msg.info.modelID,
|
||||||
providerID: msg.info.providerID,
|
providerID: msg.info.providerID,
|
||||||
}
|
}
|
||||||
@@ -103,7 +108,7 @@ export const TaskTool = Tool.define("task", async () => {
|
|||||||
ctx.metadata({
|
ctx.metadata({
|
||||||
title: params.description,
|
title: params.description,
|
||||||
metadata: {
|
metadata: {
|
||||||
sessionId: session.id,
|
sessionId: nextSession.id,
|
||||||
model,
|
model,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -111,59 +116,77 @@ export const TaskTool = Tool.define("task", async () => {
|
|||||||
const messageID = MessageID.ascending()
|
const messageID = MessageID.ascending()
|
||||||
|
|
||||||
function cancel() {
|
function cancel() {
|
||||||
SessionPrompt.cancel(session.id)
|
SessionPrompt.cancel(nextSession.id)
|
||||||
}
|
}
|
||||||
ctx.abort.addEventListener("abort", cancel)
|
|
||||||
using _ = defer(() => ctx.abort.removeEventListener("abort", cancel))
|
|
||||||
const promptParts = await SessionPrompt.resolvePromptParts(params.prompt)
|
|
||||||
|
|
||||||
const result = await SessionPrompt.prompt({
|
return yield* Effect.acquireUseRelease(
|
||||||
messageID,
|
Effect.sync(() => {
|
||||||
sessionID: session.id,
|
ctx.abort.addEventListener("abort", cancel)
|
||||||
model: {
|
}),
|
||||||
modelID: model.modelID,
|
() =>
|
||||||
providerID: model.providerID,
|
Effect.gen(function* () {
|
||||||
},
|
const parts = yield* Effect.promise(() => SessionPrompt.resolvePromptParts(params.prompt))
|
||||||
agent: agent.name,
|
const result = yield* Effect.promise(() =>
|
||||||
tools: {
|
SessionPrompt.prompt({
|
||||||
...(hasTodoWritePermission ? {} : { todowrite: false }),
|
messageID,
|
||||||
...(hasTaskPermission ? {} : { task: false }),
|
sessionID: nextSession.id,
|
||||||
...Object.fromEntries((config.experimental?.primary_tools ?? []).map((t) => [t, false])),
|
model: {
|
||||||
},
|
modelID: model.modelID,
|
||||||
parts: promptParts,
|
providerID: model.providerID,
|
||||||
})
|
},
|
||||||
|
agent: next.name,
|
||||||
|
tools: {
|
||||||
|
...(canTodo ? {} : { todowrite: false }),
|
||||||
|
...(canTask ? {} : { task: false }),
|
||||||
|
...Object.fromEntries((cfg.experimental?.primary_tools ?? []).map((item) => [item, false])),
|
||||||
|
},
|
||||||
|
parts,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
const text = result.parts.findLast((x) => x.type === "text")?.text ?? ""
|
return {
|
||||||
|
title: params.description,
|
||||||
|
metadata: {
|
||||||
|
sessionId: nextSession.id,
|
||||||
|
model,
|
||||||
|
},
|
||||||
|
output: [
|
||||||
|
`task_id: ${nextSession.id} (for resuming to continue this task if needed)`,
|
||||||
|
"",
|
||||||
|
"<task_result>",
|
||||||
|
result.parts.findLast((item) => item.type === "text")?.text ?? "",
|
||||||
|
"</task_result>",
|
||||||
|
].join("\n"),
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
() =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
ctx.abort.removeEventListener("abort", cancel)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
const output = [
|
return {
|
||||||
`task_id: ${session.id} (for resuming to continue this task if needed)`,
|
description: DESCRIPTION,
|
||||||
"",
|
parameters,
|
||||||
"<task_result>",
|
async execute(params: z.infer<typeof parameters>, ctx) {
|
||||||
text,
|
return Effect.runPromise(run(params, ctx))
|
||||||
"</task_result>",
|
},
|
||||||
].join("\n")
|
}
|
||||||
|
}),
|
||||||
return {
|
)
|
||||||
title: params.description,
|
|
||||||
metadata: {
|
|
||||||
sessionId: session.id,
|
|
||||||
model,
|
|
||||||
},
|
|
||||||
output,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
export const TaskDescription: Tool.DynamicDescription = (agent) =>
|
export const TaskDescription: Tool.DynamicDescription = (agent) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const agents = yield* Effect.promise(() => Agent.list().then((x) => x.filter((a) => a.mode !== "primary")))
|
const items = yield* Effect.promise(() =>
|
||||||
const accessibleAgents = agents.filter(
|
Agent.list().then((items) => items.filter((item) => item.mode !== "primary")),
|
||||||
(a) => Permission.evaluate("task", a.name, agent.permission).action !== "deny",
|
|
||||||
)
|
)
|
||||||
const list = accessibleAgents.toSorted((a, b) => a.name.localeCompare(b.name))
|
const filtered = items.filter((item) => Permission.evaluate(id, item.name, agent.permission).action !== "deny")
|
||||||
|
const list = filtered.toSorted((a, b) => a.name.localeCompare(b.name))
|
||||||
const description = list
|
const description = list
|
||||||
.map((a) => `- ${a.name}: ${a.description ?? "This subagent should only be called manually by the user."}`)
|
.map(
|
||||||
|
(item) => `- ${item.name}: ${item.description ?? "This subagent should only be called manually by the user."}`,
|
||||||
|
)
|
||||||
.join("\n")
|
.join("\n")
|
||||||
return [`Available agent types and the tools they have access to:`, description].join("\n")
|
return ["Available agent types and the tools they have access to:", description].join("\n")
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -98,24 +98,27 @@ export namespace Tool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function define<Parameters extends z.ZodType, Result extends Metadata>(
|
export function define<Parameters extends z.ZodType, Result extends Metadata, ID extends string = string>(
|
||||||
id: string,
|
id: ID,
|
||||||
init: (() => Promise<DefWithoutID<Parameters, Result>>) | DefWithoutID<Parameters, Result>,
|
init: (() => Promise<DefWithoutID<Parameters, Result>>) | DefWithoutID<Parameters, Result>,
|
||||||
): Info<Parameters, Result> {
|
): Info<Parameters, Result> & { id: ID } {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
init: wrap(id, init),
|
init: wrap(id, init),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function defineEffect<Parameters extends z.ZodType, Result extends Metadata, R>(
|
export function defineEffect<Parameters extends z.ZodType, Result extends Metadata, R, ID extends string = string>(
|
||||||
id: string,
|
id: ID,
|
||||||
init: Effect.Effect<(() => Promise<DefWithoutID<Parameters, Result>>) | DefWithoutID<Parameters, Result>, never, R>,
|
init: Effect.Effect<(() => Promise<DefWithoutID<Parameters, Result>>) | DefWithoutID<Parameters, Result>, never, R>,
|
||||||
): Effect.Effect<Info<Parameters, Result>, never, R> {
|
): Effect.Effect<Info<Parameters, Result>, never, R> & { id: ID } {
|
||||||
return Effect.map(init, (next) => ({ id, init: wrap(id, next) }))
|
return Object.assign(
|
||||||
|
Effect.map(init, (next) => ({ id, init: wrap(id, next) })),
|
||||||
|
{ id },
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function init(info: Info): Effect.Effect<Def, never, any> {
|
export function init(info: Info): Effect.Effect<Def> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const init = yield* Effect.promise(() => info.init())
|
const init = yield* Effect.promise(() => info.init())
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { NodeFileSystem } from "@effect/platform-node"
|
import { NodeFileSystem } from "@effect/platform-node"
|
||||||
import { expect, spyOn } from "bun:test"
|
import { expect } from "bun:test"
|
||||||
import { Cause, Effect, Exit, Fiber, Layer } from "effect"
|
import { Cause, Effect, Exit, Fiber, Layer } from "effect"
|
||||||
import path from "path"
|
import path from "path"
|
||||||
import z from "zod"
|
import z from "zod"
|
||||||
@@ -29,7 +29,6 @@ import { MessageID, PartID, SessionID } from "../../src/session/schema"
|
|||||||
import { SessionStatus } from "../../src/session/status"
|
import { SessionStatus } from "../../src/session/status"
|
||||||
import { Shell } from "../../src/shell/shell"
|
import { Shell } from "../../src/shell/shell"
|
||||||
import { Snapshot } from "../../src/snapshot"
|
import { Snapshot } from "../../src/snapshot"
|
||||||
import { TaskTool } from "../../src/tool/task"
|
|
||||||
import { ToolRegistry } from "../../src/tool/registry"
|
import { ToolRegistry } from "../../src/tool/registry"
|
||||||
import { Truncate } from "../../src/tool/truncate"
|
import { Truncate } from "../../src/tool/truncate"
|
||||||
import { Log } from "../../src/util/log"
|
import { Log } from "../../src/util/log"
|
||||||
@@ -627,11 +626,13 @@ it.live(
|
|||||||
"cancel finalizes subtask tool state",
|
"cancel finalizes subtask tool state",
|
||||||
() =>
|
() =>
|
||||||
provideTmpdirInstance(
|
provideTmpdirInstance(
|
||||||
(dir) =>
|
() =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const ready = defer<void>()
|
const ready = defer<void>()
|
||||||
const aborted = defer<void>()
|
const aborted = defer<void>()
|
||||||
const init = spyOn(TaskTool, "init").mockImplementation(async () => ({
|
const registry = yield* ToolRegistry.Service
|
||||||
|
const init = registry.named.task.init
|
||||||
|
registry.named.task.init = async () => ({
|
||||||
description: "task",
|
description: "task",
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
description: z.string(),
|
description: z.string(),
|
||||||
@@ -653,8 +654,8 @@ it.live(
|
|||||||
output: "",
|
output: "",
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}))
|
})
|
||||||
yield* Effect.addFinalizer(() => Effect.sync(() => init.mockRestore()))
|
yield* Effect.addFinalizer(() => Effect.sync(() => void (registry.named.task.init = init)))
|
||||||
|
|
||||||
const { prompt, chat } = yield* boot()
|
const { prompt, chat } = yield* boot()
|
||||||
const msg = yield* user(chat.id, "hello")
|
const msg = yield* user(chat.id, "hello")
|
||||||
|
|||||||
@@ -1,50 +1,412 @@
|
|||||||
import { Effect } from "effect"
|
import { afterEach, describe, expect } from "bun:test"
|
||||||
import { afterEach, describe, expect, test } from "bun:test"
|
import { Effect, Layer } from "effect"
|
||||||
import { Agent } from "../../src/agent/agent"
|
import { Agent } from "../../src/agent/agent"
|
||||||
|
import { Config } from "../../src/config/config"
|
||||||
|
import * as CrossSpawnSpawner from "../../src/effect/cross-spawn-spawner"
|
||||||
import { Instance } from "../../src/project/instance"
|
import { Instance } from "../../src/project/instance"
|
||||||
import { TaskDescription } from "../../src/tool/task"
|
import { Session } from "../../src/session"
|
||||||
import { tmpdir } from "../fixture/fixture"
|
import { MessageV2 } from "../../src/session/message-v2"
|
||||||
|
import { SessionPrompt } from "../../src/session/prompt"
|
||||||
|
import { MessageID, PartID } from "../../src/session/schema"
|
||||||
|
import { ModelID, ProviderID } from "../../src/provider/schema"
|
||||||
|
import { TaskDescription, TaskTool } from "../../src/tool/task"
|
||||||
|
import { provideTmpdirInstance } from "../fixture/fixture"
|
||||||
|
import { testEffect } from "../lib/effect"
|
||||||
|
|
||||||
afterEach(async () => {
|
afterEach(async () => {
|
||||||
await Instance.disposeAll()
|
await Instance.disposeAll()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const ref = {
|
||||||
|
providerID: ProviderID.make("test"),
|
||||||
|
modelID: ModelID.make("test-model"),
|
||||||
|
}
|
||||||
|
|
||||||
|
const it = testEffect(
|
||||||
|
Layer.mergeAll(Agent.defaultLayer, Config.defaultLayer, CrossSpawnSpawner.defaultLayer, Session.defaultLayer),
|
||||||
|
)
|
||||||
|
|
||||||
|
const seed = Effect.fn("TaskToolTest.seed")(function* (title = "Pinned") {
|
||||||
|
const session = yield* Session.Service
|
||||||
|
const chat = yield* session.create({ title })
|
||||||
|
const user = yield* session.updateMessage({
|
||||||
|
id: MessageID.ascending(),
|
||||||
|
role: "user",
|
||||||
|
sessionID: chat.id,
|
||||||
|
agent: "build",
|
||||||
|
model: ref,
|
||||||
|
time: { created: Date.now() },
|
||||||
|
})
|
||||||
|
const assistant: MessageV2.Assistant = {
|
||||||
|
id: MessageID.ascending(),
|
||||||
|
role: "assistant",
|
||||||
|
parentID: user.id,
|
||||||
|
sessionID: chat.id,
|
||||||
|
mode: "build",
|
||||||
|
agent: "build",
|
||||||
|
cost: 0,
|
||||||
|
path: { cwd: "/tmp", root: "/tmp" },
|
||||||
|
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||||
|
modelID: ref.modelID,
|
||||||
|
providerID: ref.providerID,
|
||||||
|
time: { created: Date.now() },
|
||||||
|
}
|
||||||
|
yield* session.updateMessage(assistant)
|
||||||
|
return { chat, assistant }
|
||||||
|
})
|
||||||
|
|
||||||
|
function reply(input: Parameters<typeof SessionPrompt.prompt>[0], text: string): MessageV2.WithParts {
|
||||||
|
const id = MessageID.ascending()
|
||||||
|
return {
|
||||||
|
info: {
|
||||||
|
id,
|
||||||
|
role: "assistant",
|
||||||
|
parentID: input.messageID ?? MessageID.ascending(),
|
||||||
|
sessionID: input.sessionID,
|
||||||
|
mode: input.agent ?? "general",
|
||||||
|
agent: input.agent ?? "general",
|
||||||
|
cost: 0,
|
||||||
|
path: { cwd: "/tmp", root: "/tmp" },
|
||||||
|
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||||
|
modelID: input.model?.modelID ?? ref.modelID,
|
||||||
|
providerID: input.model?.providerID ?? ref.providerID,
|
||||||
|
time: { created: Date.now() },
|
||||||
|
finish: "stop",
|
||||||
|
},
|
||||||
|
parts: [
|
||||||
|
{
|
||||||
|
id: PartID.ascending(),
|
||||||
|
messageID: id,
|
||||||
|
sessionID: input.sessionID,
|
||||||
|
type: "text",
|
||||||
|
text,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
describe("tool.task", () => {
|
describe("tool.task", () => {
|
||||||
test("description sorts subagents by name and is stable across calls", async () => {
|
it.live("description sorts subagents by name and is stable across calls", () =>
|
||||||
await using tmp = await tmpdir({
|
provideTmpdirInstance(
|
||||||
config: {
|
() =>
|
||||||
agent: {
|
Effect.gen(function* () {
|
||||||
zebra: {
|
const agent = yield* Agent.Service
|
||||||
description: "Zebra agent",
|
const build = yield* agent.get("build")
|
||||||
mode: "subagent",
|
const first = yield* TaskDescription(build)
|
||||||
},
|
const second = yield* TaskDescription(build)
|
||||||
alpha: {
|
|
||||||
description: "Alpha agent",
|
expect(first).toBe(second)
|
||||||
mode: "subagent",
|
|
||||||
|
const alpha = first.indexOf("- alpha: Alpha agent")
|
||||||
|
const explore = first.indexOf("- explore:")
|
||||||
|
const general = first.indexOf("- general:")
|
||||||
|
const zebra = first.indexOf("- zebra: Zebra agent")
|
||||||
|
|
||||||
|
expect(alpha).toBeGreaterThan(-1)
|
||||||
|
expect(explore).toBeGreaterThan(alpha)
|
||||||
|
expect(general).toBeGreaterThan(explore)
|
||||||
|
expect(zebra).toBeGreaterThan(general)
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
config: {
|
||||||
|
agent: {
|
||||||
|
zebra: {
|
||||||
|
description: "Zebra agent",
|
||||||
|
mode: "subagent",
|
||||||
|
},
|
||||||
|
alpha: {
|
||||||
|
description: "Alpha agent",
|
||||||
|
mode: "subagent",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
),
|
||||||
|
)
|
||||||
|
|
||||||
await Instance.provide({
|
it.live("description hides denied subagents for the caller", () =>
|
||||||
directory: tmp.path,
|
provideTmpdirInstance(
|
||||||
fn: async () => {
|
() =>
|
||||||
const agent = { name: "build", mode: "primary" as const, permission: [], options: {} }
|
Effect.gen(function* () {
|
||||||
const first = await Effect.runPromise(TaskDescription(agent))
|
const agent = yield* Agent.Service
|
||||||
const second = await Effect.runPromise(TaskDescription(agent))
|
const build = yield* agent.get("build")
|
||||||
|
const description = yield* TaskDescription(build)
|
||||||
|
|
||||||
expect(first).toBe(second)
|
expect(description).toContain("- alpha: Alpha agent")
|
||||||
|
expect(description).not.toContain("- zebra: Zebra agent")
|
||||||
const alpha = first.indexOf("- alpha: Alpha agent")
|
}),
|
||||||
const explore = first.indexOf("- explore:")
|
{
|
||||||
const general = first.indexOf("- general:")
|
config: {
|
||||||
const zebra = first.indexOf("- zebra: Zebra agent")
|
permission: {
|
||||||
|
task: {
|
||||||
expect(alpha).toBeGreaterThan(-1)
|
"*": "allow",
|
||||||
expect(explore).toBeGreaterThan(alpha)
|
zebra: "deny",
|
||||||
expect(general).toBeGreaterThan(explore)
|
},
|
||||||
expect(zebra).toBeGreaterThan(general)
|
},
|
||||||
|
agent: {
|
||||||
|
zebra: {
|
||||||
|
description: "Zebra agent",
|
||||||
|
mode: "subagent",
|
||||||
|
},
|
||||||
|
alpha: {
|
||||||
|
description: "Alpha agent",
|
||||||
|
mode: "subagent",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
})
|
),
|
||||||
})
|
)
|
||||||
|
|
||||||
|
it.live("execute resumes an existing task session from task_id", () =>
|
||||||
|
provideTmpdirInstance(() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const sessions = yield* Session.Service
|
||||||
|
const { chat, assistant } = yield* seed()
|
||||||
|
const child = yield* sessions.create({ parentID: chat.id, title: "Existing child" })
|
||||||
|
const tool = yield* TaskTool
|
||||||
|
const def = yield* Effect.promise(() => tool.init())
|
||||||
|
const resolve = SessionPrompt.resolvePromptParts
|
||||||
|
const prompt = SessionPrompt.prompt
|
||||||
|
let seen: Parameters<typeof SessionPrompt.prompt>[0] | undefined
|
||||||
|
|
||||||
|
SessionPrompt.resolvePromptParts = async (template) => [{ type: "text", text: template }]
|
||||||
|
SessionPrompt.prompt = async (input) => {
|
||||||
|
seen = input
|
||||||
|
return reply(input, "resumed")
|
||||||
|
}
|
||||||
|
yield* Effect.addFinalizer(() =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
SessionPrompt.resolvePromptParts = resolve
|
||||||
|
SessionPrompt.prompt = prompt
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const result = yield* Effect.promise(() =>
|
||||||
|
def.execute(
|
||||||
|
{
|
||||||
|
description: "inspect bug",
|
||||||
|
prompt: "look into the cache key path",
|
||||||
|
subagent_type: "general",
|
||||||
|
task_id: child.id,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sessionID: chat.id,
|
||||||
|
messageID: assistant.id,
|
||||||
|
agent: "build",
|
||||||
|
abort: new AbortController().signal,
|
||||||
|
messages: [],
|
||||||
|
metadata() {},
|
||||||
|
ask: async () => {},
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
const kids = yield* sessions.children(chat.id)
|
||||||
|
expect(kids).toHaveLength(1)
|
||||||
|
expect(kids[0]?.id).toBe(child.id)
|
||||||
|
expect(result.metadata.sessionId).toBe(child.id)
|
||||||
|
expect(result.output).toContain(`task_id: ${child.id}`)
|
||||||
|
expect(seen?.sessionID).toBe(child.id)
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.live("execute asks by default and skips checks when bypassed", () =>
|
||||||
|
provideTmpdirInstance(() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const { chat, assistant } = yield* seed()
|
||||||
|
const tool = yield* TaskTool
|
||||||
|
const def = yield* Effect.promise(() => tool.init())
|
||||||
|
const resolve = SessionPrompt.resolvePromptParts
|
||||||
|
const prompt = SessionPrompt.prompt
|
||||||
|
const calls: unknown[] = []
|
||||||
|
|
||||||
|
SessionPrompt.resolvePromptParts = async (template) => [{ type: "text", text: template }]
|
||||||
|
SessionPrompt.prompt = async (input) => reply(input, "done")
|
||||||
|
yield* Effect.addFinalizer(() =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
SessionPrompt.resolvePromptParts = resolve
|
||||||
|
SessionPrompt.prompt = prompt
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const exec = (extra?: { bypassAgentCheck?: boolean }) =>
|
||||||
|
Effect.promise(() =>
|
||||||
|
def.execute(
|
||||||
|
{
|
||||||
|
description: "inspect bug",
|
||||||
|
prompt: "look into the cache key path",
|
||||||
|
subagent_type: "general",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sessionID: chat.id,
|
||||||
|
messageID: assistant.id,
|
||||||
|
agent: "build",
|
||||||
|
abort: new AbortController().signal,
|
||||||
|
extra,
|
||||||
|
messages: [],
|
||||||
|
metadata() {},
|
||||||
|
ask: async (input) => {
|
||||||
|
calls.push(input)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
yield* exec()
|
||||||
|
yield* exec({ bypassAgentCheck: true })
|
||||||
|
|
||||||
|
expect(calls).toHaveLength(1)
|
||||||
|
expect(calls[0]).toEqual({
|
||||||
|
permission: "task",
|
||||||
|
patterns: ["general"],
|
||||||
|
always: ["*"],
|
||||||
|
metadata: {
|
||||||
|
description: "inspect bug",
|
||||||
|
subagent_type: "general",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.live("execute creates a child when task_id does not exist", () =>
|
||||||
|
provideTmpdirInstance(() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const sessions = yield* Session.Service
|
||||||
|
const { chat, assistant } = yield* seed()
|
||||||
|
const tool = yield* TaskTool
|
||||||
|
const def = yield* Effect.promise(() => tool.init())
|
||||||
|
const resolve = SessionPrompt.resolvePromptParts
|
||||||
|
const prompt = SessionPrompt.prompt
|
||||||
|
let seen: Parameters<typeof SessionPrompt.prompt>[0] | undefined
|
||||||
|
|
||||||
|
SessionPrompt.resolvePromptParts = async (template) => [{ type: "text", text: template }]
|
||||||
|
SessionPrompt.prompt = async (input) => {
|
||||||
|
seen = input
|
||||||
|
return reply(input, "created")
|
||||||
|
}
|
||||||
|
yield* Effect.addFinalizer(() =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
SessionPrompt.resolvePromptParts = resolve
|
||||||
|
SessionPrompt.prompt = prompt
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const result = yield* Effect.promise(() =>
|
||||||
|
def.execute(
|
||||||
|
{
|
||||||
|
description: "inspect bug",
|
||||||
|
prompt: "look into the cache key path",
|
||||||
|
subagent_type: "general",
|
||||||
|
task_id: "ses_missing",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sessionID: chat.id,
|
||||||
|
messageID: assistant.id,
|
||||||
|
agent: "build",
|
||||||
|
abort: new AbortController().signal,
|
||||||
|
messages: [],
|
||||||
|
metadata() {},
|
||||||
|
ask: async () => {},
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
const kids = yield* sessions.children(chat.id)
|
||||||
|
expect(kids).toHaveLength(1)
|
||||||
|
expect(kids[0]?.id).toBe(result.metadata.sessionId)
|
||||||
|
expect(result.metadata.sessionId).not.toBe("ses_missing")
|
||||||
|
expect(result.output).toContain(`task_id: ${result.metadata.sessionId}`)
|
||||||
|
expect(seen?.sessionID).toBe(result.metadata.sessionId)
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.live("execute shapes child permissions for task, todowrite, and primary tools", () =>
|
||||||
|
provideTmpdirInstance(
|
||||||
|
() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const sessions = yield* Session.Service
|
||||||
|
const { chat, assistant } = yield* seed()
|
||||||
|
const tool = yield* TaskTool
|
||||||
|
const def = yield* Effect.promise(() => tool.init())
|
||||||
|
const resolve = SessionPrompt.resolvePromptParts
|
||||||
|
const prompt = SessionPrompt.prompt
|
||||||
|
let seen: Parameters<typeof SessionPrompt.prompt>[0] | undefined
|
||||||
|
|
||||||
|
SessionPrompt.resolvePromptParts = async (template) => [{ type: "text", text: template }]
|
||||||
|
SessionPrompt.prompt = async (input) => {
|
||||||
|
seen = input
|
||||||
|
return reply(input, "done")
|
||||||
|
}
|
||||||
|
yield* Effect.addFinalizer(() =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
SessionPrompt.resolvePromptParts = resolve
|
||||||
|
SessionPrompt.prompt = prompt
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const result = yield* Effect.promise(() =>
|
||||||
|
def.execute(
|
||||||
|
{
|
||||||
|
description: "inspect bug",
|
||||||
|
prompt: "look into the cache key path",
|
||||||
|
subagent_type: "reviewer",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sessionID: chat.id,
|
||||||
|
messageID: assistant.id,
|
||||||
|
agent: "build",
|
||||||
|
abort: new AbortController().signal,
|
||||||
|
messages: [],
|
||||||
|
metadata() {},
|
||||||
|
ask: async () => {},
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
const child = yield* sessions.get(result.metadata.sessionId)
|
||||||
|
expect(child.parentID).toBe(chat.id)
|
||||||
|
expect(child.permission).toEqual([
|
||||||
|
{
|
||||||
|
permission: "todowrite",
|
||||||
|
pattern: "*",
|
||||||
|
action: "deny",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
permission: "bash",
|
||||||
|
pattern: "*",
|
||||||
|
action: "allow",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
permission: "read",
|
||||||
|
pattern: "*",
|
||||||
|
action: "allow",
|
||||||
|
},
|
||||||
|
])
|
||||||
|
expect(seen?.tools).toEqual({
|
||||||
|
todowrite: false,
|
||||||
|
bash: false,
|
||||||
|
read: false,
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
config: {
|
||||||
|
agent: {
|
||||||
|
reviewer: {
|
||||||
|
mode: "subagent",
|
||||||
|
permission: {
|
||||||
|
task: "allow",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
experimental: {
|
||||||
|
primary_tools: ["bash", "read"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { describe, expect, test } from "bun:test"
|
||||||
|
import { patchFiles } from "./apply-patch-file"
|
||||||
|
import { text } from "./session-diff"
|
||||||
|
|
||||||
|
describe("apply patch file", () => {
|
||||||
|
test("parses patch metadata from the server", () => {
|
||||||
|
const file = patchFiles([
|
||||||
|
{
|
||||||
|
filePath: "/tmp/a.ts",
|
||||||
|
relativePath: "a.ts",
|
||||||
|
type: "update",
|
||||||
|
patch:
|
||||||
|
"Index: a.ts\n===================================================================\n--- a.ts\t\n+++ a.ts\t\n@@ -1,2 +1,2 @@\n one\n-two\n+three\n",
|
||||||
|
additions: 1,
|
||||||
|
deletions: 1,
|
||||||
|
},
|
||||||
|
])[0]
|
||||||
|
|
||||||
|
expect(file).toBeDefined()
|
||||||
|
expect(file?.view.fileDiff.name).toBe("a.ts")
|
||||||
|
expect(text(file!.view, "deletions")).toBe("one\ntwo\n")
|
||||||
|
expect(text(file!.view, "additions")).toBe("one\nthree\n")
|
||||||
|
})
|
||||||
|
|
||||||
|
test("keeps legacy before and after payloads working", () => {
|
||||||
|
const file = patchFiles([
|
||||||
|
{
|
||||||
|
filePath: "/tmp/a.ts",
|
||||||
|
relativePath: "a.ts",
|
||||||
|
type: "update",
|
||||||
|
before: "one\n",
|
||||||
|
after: "two\n",
|
||||||
|
additions: 1,
|
||||||
|
deletions: 1,
|
||||||
|
},
|
||||||
|
])[0]
|
||||||
|
|
||||||
|
expect(file).toBeDefined()
|
||||||
|
expect(file?.view.patch).toContain("@@ -1,1 +1,1 @@")
|
||||||
|
expect(text(file!.view, "deletions")).toBe("one\n")
|
||||||
|
expect(text(file!.view, "additions")).toBe("two\n")
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { normalize, type ViewDiff } from "./session-diff"
|
||||||
|
|
||||||
|
type Kind = "add" | "update" | "delete" | "move"
|
||||||
|
|
||||||
|
type Raw = {
|
||||||
|
filePath?: string
|
||||||
|
relativePath?: string
|
||||||
|
type?: Kind
|
||||||
|
patch?: string
|
||||||
|
diff?: string
|
||||||
|
before?: string
|
||||||
|
after?: string
|
||||||
|
additions?: number
|
||||||
|
deletions?: number
|
||||||
|
movePath?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ApplyPatchFile = {
|
||||||
|
filePath: string
|
||||||
|
relativePath: string
|
||||||
|
type: Kind
|
||||||
|
additions: number
|
||||||
|
deletions: number
|
||||||
|
movePath?: string
|
||||||
|
view: ViewDiff
|
||||||
|
}
|
||||||
|
|
||||||
|
function kind(value: unknown) {
|
||||||
|
if (value === "add" || value === "update" || value === "delete" || value === "move") return value
|
||||||
|
}
|
||||||
|
|
||||||
|
function status(type: Kind): "added" | "deleted" | "modified" {
|
||||||
|
if (type === "add") return "added"
|
||||||
|
if (type === "delete") return "deleted"
|
||||||
|
return "modified"
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchFile(raw: unknown): ApplyPatchFile | undefined {
|
||||||
|
if (!raw || typeof raw !== "object") return
|
||||||
|
|
||||||
|
const value = raw as Raw
|
||||||
|
const type = kind(value.type)
|
||||||
|
const filePath = typeof value.filePath === "string" ? value.filePath : undefined
|
||||||
|
const relativePath = typeof value.relativePath === "string" ? value.relativePath : filePath
|
||||||
|
const patch = typeof value.patch === "string" ? value.patch : typeof value.diff === "string" ? value.diff : undefined
|
||||||
|
const before = typeof value.before === "string" ? value.before : undefined
|
||||||
|
const after = typeof value.after === "string" ? value.after : undefined
|
||||||
|
|
||||||
|
if (!type || !filePath || !relativePath) return
|
||||||
|
if (!patch && before === undefined && after === undefined) return
|
||||||
|
|
||||||
|
const additions = typeof value.additions === "number" ? value.additions : 0
|
||||||
|
const deletions = typeof value.deletions === "number" ? value.deletions : 0
|
||||||
|
const movePath = typeof value.movePath === "string" ? value.movePath : undefined
|
||||||
|
|
||||||
|
return {
|
||||||
|
filePath,
|
||||||
|
relativePath,
|
||||||
|
type,
|
||||||
|
additions,
|
||||||
|
deletions,
|
||||||
|
movePath,
|
||||||
|
view: normalize({
|
||||||
|
file: relativePath,
|
||||||
|
patch,
|
||||||
|
before,
|
||||||
|
after,
|
||||||
|
additions,
|
||||||
|
deletions,
|
||||||
|
status: status(type),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchFiles(raw: unknown) {
|
||||||
|
if (!Array.isArray(raw)) return []
|
||||||
|
return raw.map(patchFile).filter((file): file is ApplyPatchFile => !!file)
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { DIFFS_TAG_NAME, FileDiff } from "@pierre/diffs"
|
import { DIFFS_TAG_NAME, FileDiff, VirtualizedFileDiff } from "@pierre/diffs"
|
||||||
import { type PreloadFileDiffResult, type PreloadMultiFileDiffResult } from "@pierre/diffs/ssr"
|
import { type PreloadFileDiffResult, type PreloadMultiFileDiffResult } from "@pierre/diffs/ssr"
|
||||||
import { createEffect, onCleanup, onMount, Show, splitProps } from "solid-js"
|
import { createEffect, onCleanup, onMount, Show, splitProps } from "solid-js"
|
||||||
import { Dynamic, isServer } from "solid-js/web"
|
import { Dynamic, isServer } from "solid-js/web"
|
||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
notifyShadowReady,
|
notifyShadowReady,
|
||||||
observeViewerScheme,
|
observeViewerScheme,
|
||||||
} from "../pierre/file-runtime"
|
} from "../pierre/file-runtime"
|
||||||
|
import { acquireVirtualizer, virtualMetrics } from "../pierre/virtualizer"
|
||||||
import { File, type DiffFileProps, type FileProps } from "./file"
|
import { File, type DiffFileProps, type FileProps } from "./file"
|
||||||
|
|
||||||
type DiffPreload<T> = PreloadMultiFileDiffResult<T> | PreloadFileDiffResult<T>
|
type DiffPreload<T> = PreloadMultiFileDiffResult<T> | PreloadFileDiffResult<T>
|
||||||
@@ -25,6 +26,7 @@ function DiffSSRViewer<T>(props: SSRDiffFileProps<T>) {
|
|||||||
let container!: HTMLDivElement
|
let container!: HTMLDivElement
|
||||||
let fileDiffRef!: HTMLElement
|
let fileDiffRef!: HTMLElement
|
||||||
let fileDiffInstance: FileDiff<T> | undefined
|
let fileDiffInstance: FileDiff<T> | undefined
|
||||||
|
let sharedVirtualizer: NonNullable<ReturnType<typeof acquireVirtualizer>> | undefined
|
||||||
|
|
||||||
const ready = createReadyWatcher()
|
const ready = createReadyWatcher()
|
||||||
const workerPool = useWorkerPool(props.diffStyle)
|
const workerPool = useWorkerPool(props.diffStyle)
|
||||||
@@ -49,6 +51,14 @@ function DiffSSRViewer<T>(props: SSRDiffFileProps<T>) {
|
|||||||
|
|
||||||
const getRoot = () => fileDiffRef?.shadowRoot ?? undefined
|
const getRoot = () => fileDiffRef?.shadowRoot ?? undefined
|
||||||
|
|
||||||
|
const getVirtualizer = () => {
|
||||||
|
if (sharedVirtualizer) return sharedVirtualizer.virtualizer
|
||||||
|
const result = acquireVirtualizer(container)
|
||||||
|
if (!result) return
|
||||||
|
sharedVirtualizer = result
|
||||||
|
return result.virtualizer
|
||||||
|
}
|
||||||
|
|
||||||
const setSelectedLines = (range: DiffFileProps<T>["selectedLines"], attempt = 0) => {
|
const setSelectedLines = (range: DiffFileProps<T>["selectedLines"], attempt = 0) => {
|
||||||
const diff = fileDiffInstance
|
const diff = fileDiffInstance
|
||||||
if (!diff) return
|
if (!diff) return
|
||||||
@@ -82,15 +92,27 @@ function DiffSSRViewer<T>(props: SSRDiffFileProps<T>) {
|
|||||||
|
|
||||||
onCleanup(observeViewerScheme(() => fileDiffRef))
|
onCleanup(observeViewerScheme(() => fileDiffRef))
|
||||||
|
|
||||||
|
const virtualizer = getVirtualizer()
|
||||||
const annotations = local.annotations ?? local.preloadedDiff.annotations ?? []
|
const annotations = local.annotations ?? local.preloadedDiff.annotations ?? []
|
||||||
fileDiffInstance = new FileDiff<T>(
|
fileDiffInstance = virtualizer
|
||||||
{
|
? new VirtualizedFileDiff<T>(
|
||||||
...createDefaultOptions(props.diffStyle),
|
{
|
||||||
...others,
|
...createDefaultOptions(props.diffStyle),
|
||||||
...(local.preloadedDiff.options ?? {}),
|
...others,
|
||||||
},
|
...(local.preloadedDiff.options ?? {}),
|
||||||
workerPool,
|
},
|
||||||
)
|
virtualizer,
|
||||||
|
virtualMetrics,
|
||||||
|
workerPool,
|
||||||
|
)
|
||||||
|
: new FileDiff<T>(
|
||||||
|
{
|
||||||
|
...createDefaultOptions(props.diffStyle),
|
||||||
|
...others,
|
||||||
|
...(local.preloadedDiff.options ?? {}),
|
||||||
|
},
|
||||||
|
workerPool,
|
||||||
|
)
|
||||||
|
|
||||||
applyViewerScheme(fileDiffRef)
|
applyViewerScheme(fileDiffRef)
|
||||||
|
|
||||||
@@ -141,6 +163,8 @@ function DiffSSRViewer<T>(props: SSRDiffFileProps<T>) {
|
|||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
clearReadyWatcher(ready)
|
clearReadyWatcher(ready)
|
||||||
fileDiffInstance?.cleanUp()
|
fileDiffInstance?.cleanUp()
|
||||||
|
sharedVirtualizer?.release()
|
||||||
|
sharedVirtualizer = undefined
|
||||||
})
|
})
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { sampledChecksum } from "@opencode-ai/util/encode"
|
import { sampledChecksum } from "@opencode-ai/util/encode"
|
||||||
import {
|
import {
|
||||||
|
DEFAULT_VIRTUAL_FILE_METRICS,
|
||||||
type DiffLineAnnotation,
|
type DiffLineAnnotation,
|
||||||
type FileContents,
|
type FileContents,
|
||||||
type FileDiffMetadata,
|
type FileDiffMetadata,
|
||||||
@@ -9,6 +10,10 @@ import {
|
|||||||
type FileOptions,
|
type FileOptions,
|
||||||
type LineAnnotation,
|
type LineAnnotation,
|
||||||
type SelectedLineRange,
|
type SelectedLineRange,
|
||||||
|
type VirtualFileMetrics,
|
||||||
|
VirtualizedFile,
|
||||||
|
VirtualizedFileDiff,
|
||||||
|
Virtualizer,
|
||||||
} from "@pierre/diffs"
|
} from "@pierre/diffs"
|
||||||
import { type PreloadFileDiffResult, type PreloadMultiFileDiffResult } from "@pierre/diffs/ssr"
|
import { type PreloadFileDiffResult, type PreloadMultiFileDiffResult } from "@pierre/diffs/ssr"
|
||||||
import { createMediaQuery } from "@solid-primitives/media"
|
import { createMediaQuery } from "@solid-primitives/media"
|
||||||
@@ -35,10 +40,19 @@ import {
|
|||||||
readShadowLineSelection,
|
readShadowLineSelection,
|
||||||
} from "../pierre/file-selection"
|
} from "../pierre/file-selection"
|
||||||
import { createLineNumberSelectionBridge, restoreShadowTextSelection } from "../pierre/selection-bridge"
|
import { createLineNumberSelectionBridge, restoreShadowTextSelection } from "../pierre/selection-bridge"
|
||||||
|
import { acquireVirtualizer, virtualMetrics } from "../pierre/virtualizer"
|
||||||
import { getWorkerPool } from "../pierre/worker"
|
import { getWorkerPool } from "../pierre/worker"
|
||||||
import { FileMedia, type FileMediaOptions } from "./file-media"
|
import { FileMedia, type FileMediaOptions } from "./file-media"
|
||||||
import { FileSearchBar } from "./file-search"
|
import { FileSearchBar } from "./file-search"
|
||||||
|
|
||||||
|
const VIRTUALIZE_BYTES = 500_000
|
||||||
|
|
||||||
|
const codeMetrics = {
|
||||||
|
...DEFAULT_VIRTUAL_FILE_METRICS,
|
||||||
|
lineHeight: 24,
|
||||||
|
fileGap: 0,
|
||||||
|
} satisfies Partial<VirtualFileMetrics>
|
||||||
|
|
||||||
type SharedProps<T> = {
|
type SharedProps<T> = {
|
||||||
annotations?: LineAnnotation<T>[] | DiffLineAnnotation<T>[]
|
annotations?: LineAnnotation<T>[] | DiffLineAnnotation<T>[]
|
||||||
selectedLines?: SelectedLineRange | null
|
selectedLines?: SelectedLineRange | null
|
||||||
@@ -372,6 +386,11 @@ type AnnotationTarget<A> = {
|
|||||||
rerender: () => void
|
rerender: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type VirtualStrategy = {
|
||||||
|
get: () => Virtualizer | undefined
|
||||||
|
cleanup: () => void
|
||||||
|
}
|
||||||
|
|
||||||
function useModeViewer(config: ModeConfig, adapter: ModeAdapter) {
|
function useModeViewer(config: ModeConfig, adapter: ModeAdapter) {
|
||||||
return useFileViewer({
|
return useFileViewer({
|
||||||
enableLineSelection: config.enableLineSelection,
|
enableLineSelection: config.enableLineSelection,
|
||||||
@@ -513,6 +532,64 @@ function scrollParent(el: HTMLElement): HTMLElement | undefined {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createLocalVirtualStrategy(host: () => HTMLDivElement | undefined, enabled: () => boolean): VirtualStrategy {
|
||||||
|
let virtualizer: Virtualizer | undefined
|
||||||
|
let root: Document | HTMLElement | undefined
|
||||||
|
|
||||||
|
const release = () => {
|
||||||
|
virtualizer?.cleanUp()
|
||||||
|
virtualizer = undefined
|
||||||
|
root = undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
get: () => {
|
||||||
|
if (!enabled()) {
|
||||||
|
release()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (typeof document === "undefined") return
|
||||||
|
|
||||||
|
const wrapper = host()
|
||||||
|
if (!wrapper) return
|
||||||
|
|
||||||
|
const next = scrollParent(wrapper) ?? document
|
||||||
|
if (virtualizer && root === next) return virtualizer
|
||||||
|
|
||||||
|
release()
|
||||||
|
virtualizer = new Virtualizer()
|
||||||
|
root = next
|
||||||
|
virtualizer.setup(next, next instanceof Document ? undefined : wrapper)
|
||||||
|
return virtualizer
|
||||||
|
},
|
||||||
|
cleanup: release,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function createSharedVirtualStrategy(host: () => HTMLDivElement | undefined): VirtualStrategy {
|
||||||
|
let shared: NonNullable<ReturnType<typeof acquireVirtualizer>> | undefined
|
||||||
|
|
||||||
|
const release = () => {
|
||||||
|
shared?.release()
|
||||||
|
shared = undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
get: () => {
|
||||||
|
if (shared) return shared.virtualizer
|
||||||
|
|
||||||
|
const container = host()
|
||||||
|
if (!container) return
|
||||||
|
|
||||||
|
const result = acquireVirtualizer(container)
|
||||||
|
if (!result) return
|
||||||
|
shared = result
|
||||||
|
return result.virtualizer
|
||||||
|
},
|
||||||
|
cleanup: release,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function parseLine(node: HTMLElement) {
|
function parseLine(node: HTMLElement) {
|
||||||
if (!node.dataset.line) return
|
if (!node.dataset.line) return
|
||||||
const value = parseInt(node.dataset.line, 10)
|
const value = parseInt(node.dataset.line, 10)
|
||||||
@@ -611,7 +688,7 @@ function ViewerShell(props: {
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
function TextViewer<T>(props: TextFileProps<T>) {
|
function TextViewer<T>(props: TextFileProps<T>) {
|
||||||
let instance: PierreFile<T> | undefined
|
let instance: PierreFile<T> | VirtualizedFile<T> | undefined
|
||||||
let viewer!: Viewer
|
let viewer!: Viewer
|
||||||
|
|
||||||
const [local, others] = splitProps(props, textKeys)
|
const [local, others] = splitProps(props, textKeys)
|
||||||
@@ -630,12 +707,34 @@ function TextViewer<T>(props: TextFileProps<T>) {
|
|||||||
return Math.max(1, total)
|
return Math.max(1, total)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const bytes = createMemo(() => {
|
||||||
|
const value = local.file.contents as unknown
|
||||||
|
if (typeof value === "string") return value.length
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.reduce(
|
||||||
|
(sum, part) => sum + (typeof part === "string" ? part.length + 1 : String(part).length + 1),
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (value == null) return 0
|
||||||
|
return String(value).length
|
||||||
|
})
|
||||||
|
|
||||||
|
const virtual = createMemo(() => bytes() > VIRTUALIZE_BYTES)
|
||||||
|
|
||||||
|
const virtuals = createLocalVirtualStrategy(() => viewer.wrapper, virtual)
|
||||||
|
|
||||||
const lineFromMouseEvent = (event: MouseEvent): MouseHit => mouseHit(event, parseLine)
|
const lineFromMouseEvent = (event: MouseEvent): MouseHit => mouseHit(event, parseLine)
|
||||||
|
|
||||||
const applySelection = (range: SelectedLineRange | null) => {
|
const applySelection = (range: SelectedLineRange | null) => {
|
||||||
const current = instance
|
const current = instance
|
||||||
if (!current) return false
|
if (!current) return false
|
||||||
|
|
||||||
|
if (virtual()) {
|
||||||
|
current.setSelectedLines(range)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
const root = viewer.getRoot()
|
const root = viewer.getRoot()
|
||||||
if (!root) return false
|
if (!root) return false
|
||||||
|
|
||||||
@@ -734,7 +833,10 @@ function TextViewer<T>(props: TextFileProps<T>) {
|
|||||||
const notify = () => {
|
const notify = () => {
|
||||||
notifyRendered({
|
notifyRendered({
|
||||||
viewer,
|
viewer,
|
||||||
isReady: (root) => root.querySelectorAll("[data-line]").length >= lineCount(),
|
isReady: (root) => {
|
||||||
|
if (virtual()) return root.querySelector("[data-line]") != null
|
||||||
|
return root.querySelectorAll("[data-line]").length >= lineCount()
|
||||||
|
},
|
||||||
onReady: () => {
|
onReady: () => {
|
||||||
applySelection(viewer.lastSelection)
|
applySelection(viewer.lastSelection)
|
||||||
viewer.find.refresh({ reset: true })
|
viewer.find.refresh({ reset: true })
|
||||||
@@ -753,11 +855,17 @@ function TextViewer<T>(props: TextFileProps<T>) {
|
|||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
const opts = options()
|
const opts = options()
|
||||||
const workerPool = getWorkerPool("unified")
|
const workerPool = getWorkerPool("unified")
|
||||||
|
const isVirtual = virtual()
|
||||||
|
|
||||||
|
const virtualizer = virtuals.get()
|
||||||
|
|
||||||
renderViewer({
|
renderViewer({
|
||||||
viewer,
|
viewer,
|
||||||
current: instance,
|
current: instance,
|
||||||
create: () => new PierreFile<T>(opts, workerPool),
|
create: () =>
|
||||||
|
isVirtual && virtualizer
|
||||||
|
? new VirtualizedFile<T>(opts, virtualizer, codeMetrics, workerPool)
|
||||||
|
: new PierreFile<T>(opts, workerPool),
|
||||||
assign: (value) => {
|
assign: (value) => {
|
||||||
instance = value
|
instance = value
|
||||||
},
|
},
|
||||||
@@ -784,6 +892,7 @@ function TextViewer<T>(props: TextFileProps<T>) {
|
|||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
instance?.cleanUp()
|
instance?.cleanUp()
|
||||||
instance = undefined
|
instance = undefined
|
||||||
|
virtuals.cleanup()
|
||||||
})
|
})
|
||||||
|
|
||||||
return <ViewerShell mode="text" viewer={viewer} class={local.class} classList={local.classList} />
|
return <ViewerShell mode="text" viewer={viewer} class={local.class} classList={local.classList} />
|
||||||
@@ -879,6 +988,8 @@ function DiffViewer<T>(props: DiffFileProps<T>) {
|
|||||||
adapter,
|
adapter,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const virtuals = createSharedVirtualStrategy(() => viewer.container)
|
||||||
|
|
||||||
const large = createMemo(() => {
|
const large = createMemo(() => {
|
||||||
if (local.fileDiff) {
|
if (local.fileDiff) {
|
||||||
const before = local.fileDiff.deletionLines.join("")
|
const before = local.fileDiff.deletionLines.join("")
|
||||||
@@ -941,6 +1052,7 @@ function DiffViewer<T>(props: DiffFileProps<T>) {
|
|||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
const opts = options()
|
const opts = options()
|
||||||
const workerPool = large() ? getWorkerPool("unified") : getWorkerPool(props.diffStyle)
|
const workerPool = large() ? getWorkerPool("unified") : getWorkerPool(props.diffStyle)
|
||||||
|
const virtualizer = virtuals.get()
|
||||||
const beforeContents = typeof local.before?.contents === "string" ? local.before.contents : ""
|
const beforeContents = typeof local.before?.contents === "string" ? local.before.contents : ""
|
||||||
const afterContents = typeof local.after?.contents === "string" ? local.after.contents : ""
|
const afterContents = typeof local.after?.contents === "string" ? local.after.contents : ""
|
||||||
const done = preserve(viewer)
|
const done = preserve(viewer)
|
||||||
@@ -955,7 +1067,10 @@ function DiffViewer<T>(props: DiffFileProps<T>) {
|
|||||||
renderViewer({
|
renderViewer({
|
||||||
viewer,
|
viewer,
|
||||||
current: instance,
|
current: instance,
|
||||||
create: () => new FileDiff<T>(opts, workerPool),
|
create: () =>
|
||||||
|
virtualizer
|
||||||
|
? new VirtualizedFileDiff<T>(opts, virtualizer, virtualMetrics, workerPool)
|
||||||
|
: new FileDiff<T>(opts, workerPool),
|
||||||
assign: (value) => {
|
assign: (value) => {
|
||||||
instance = value
|
instance = value
|
||||||
},
|
},
|
||||||
@@ -993,6 +1108,7 @@ function DiffViewer<T>(props: DiffFileProps<T>) {
|
|||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
instance?.cleanUp()
|
instance?.cleanUp()
|
||||||
instance = undefined
|
instance = undefined
|
||||||
|
virtuals.cleanup()
|
||||||
dragSide = undefined
|
dragSide = undefined
|
||||||
dragEndSide = undefined
|
dragEndSide = undefined
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ import { Spinner } from "./spinner"
|
|||||||
import { TextShimmer } from "./text-shimmer"
|
import { TextShimmer } from "./text-shimmer"
|
||||||
import { AnimatedCountList } from "./tool-count-summary"
|
import { AnimatedCountList } from "./tool-count-summary"
|
||||||
import { ToolStatusTitle } from "./tool-status-title"
|
import { ToolStatusTitle } from "./tool-status-title"
|
||||||
|
import { patchFiles } from "./apply-patch-file"
|
||||||
import { animate } from "motion"
|
import { animate } from "motion"
|
||||||
import { useLocation } from "@solidjs/router"
|
import { useLocation } from "@solidjs/router"
|
||||||
import { attached, inline, kind } from "./message-file"
|
import { attached, inline, kind } from "./message-file"
|
||||||
@@ -2014,24 +2015,12 @@ ToolRegistry.register({
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
interface ApplyPatchFile {
|
|
||||||
filePath: string
|
|
||||||
relativePath: string
|
|
||||||
type: "add" | "update" | "delete" | "move"
|
|
||||||
diff: string
|
|
||||||
before: string
|
|
||||||
after: string
|
|
||||||
additions: number
|
|
||||||
deletions: number
|
|
||||||
movePath?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
ToolRegistry.register({
|
ToolRegistry.register({
|
||||||
name: "apply_patch",
|
name: "apply_patch",
|
||||||
render(props) {
|
render(props) {
|
||||||
const i18n = useI18n()
|
const i18n = useI18n()
|
||||||
const fileComponent = useFileComponent()
|
const fileComponent = useFileComponent()
|
||||||
const files = createMemo(() => (props.metadata.files ?? []) as ApplyPatchFile[])
|
const files = createMemo(() => patchFiles(props.metadata.files))
|
||||||
const pending = createMemo(() => props.status === "pending" || props.status === "running")
|
const pending = createMemo(() => props.status === "pending" || props.status === "running")
|
||||||
const single = createMemo(() => {
|
const single = createMemo(() => {
|
||||||
const list = files()
|
const list = files()
|
||||||
@@ -2137,12 +2126,7 @@ ToolRegistry.register({
|
|||||||
<Accordion.Content>
|
<Accordion.Content>
|
||||||
<Show when={visible()}>
|
<Show when={visible()}>
|
||||||
<div data-component="apply-patch-file-diff">
|
<div data-component="apply-patch-file-diff">
|
||||||
<Dynamic
|
<Dynamic component={fileComponent} mode="diff" fileDiff={file.view.fileDiff} />
|
||||||
component={fileComponent}
|
|
||||||
mode="diff"
|
|
||||||
before={{ name: file.filePath, contents: file.before }}
|
|
||||||
after={{ name: file.movePath ?? file.filePath, contents: file.after }}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</Show>
|
</Show>
|
||||||
</Accordion.Content>
|
</Accordion.Content>
|
||||||
@@ -2212,12 +2196,7 @@ ToolRegistry.register({
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<div data-component="apply-patch-file-diff">
|
<div data-component="apply-patch-file-diff">
|
||||||
<Dynamic
|
<Dynamic component={fileComponent} mode="diff" fileDiff={single()!.view.fileDiff} />
|
||||||
component={fileComponent}
|
|
||||||
mode="diff"
|
|
||||||
before={{ name: single()!.filePath, contents: single()!.before }}
|
|
||||||
after={{ name: single()!.movePath ?? single()!.filePath, contents: single()!.after }}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</ToolFileAccordion>
|
</ToolFileAccordion>
|
||||||
</BasicTool>
|
</BasicTool>
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import type { LineCommentEditorProps } from "./line-comment"
|
|||||||
import { normalize, text, type ViewDiff } from "./session-diff"
|
import { normalize, text, type ViewDiff } from "./session-diff"
|
||||||
|
|
||||||
const MAX_DIFF_CHANGED_LINES = 500
|
const MAX_DIFF_CHANGED_LINES = 500
|
||||||
|
const REVIEW_MOUNT_MARGIN = 300
|
||||||
|
|
||||||
export type SessionReviewDiffStyle = "unified" | "split"
|
export type SessionReviewDiffStyle = "unified" | "split"
|
||||||
|
|
||||||
@@ -64,6 +65,26 @@ export type SessionReviewFocus = { file: string; id: string }
|
|||||||
type ReviewDiff = (SnapshotFileDiff | VcsFileDiff) & { preloaded?: PreloadMultiFileDiffResult<any> }
|
type ReviewDiff = (SnapshotFileDiff | VcsFileDiff) & { preloaded?: PreloadMultiFileDiffResult<any> }
|
||||||
type Item = ViewDiff & { preloaded?: PreloadMultiFileDiffResult<any> }
|
type Item = ViewDiff & { preloaded?: PreloadMultiFileDiffResult<any> }
|
||||||
|
|
||||||
|
function diff(value: unknown): value is ReviewDiff {
|
||||||
|
if (!value || typeof value !== "object" || Array.isArray(value)) return false
|
||||||
|
if (!("file" in value) || typeof value.file !== "string") return false
|
||||||
|
if (!("additions" in value) || typeof value.additions !== "number") return false
|
||||||
|
if (!("deletions" in value) || typeof value.deletions !== "number") return false
|
||||||
|
if ("patch" in value && value.patch !== undefined && typeof value.patch !== "string") return false
|
||||||
|
if ("before" in value && value.before !== undefined && typeof value.before !== "string") return false
|
||||||
|
if ("after" in value && value.after !== undefined && typeof value.after !== "string") return false
|
||||||
|
if (!("status" in value) || value.status === undefined) return true
|
||||||
|
return value.status === "added" || value.status === "deleted" || value.status === "modified"
|
||||||
|
}
|
||||||
|
|
||||||
|
function list(value: unknown): ReviewDiff[] {
|
||||||
|
if (Array.isArray(value) && value.every(diff)) return value
|
||||||
|
if (Array.isArray(value)) return value.filter(diff)
|
||||||
|
if (diff(value)) return [value]
|
||||||
|
if (!value || typeof value !== "object") return []
|
||||||
|
return Object.values(value).filter(diff)
|
||||||
|
}
|
||||||
|
|
||||||
export interface SessionReviewProps {
|
export interface SessionReviewProps {
|
||||||
title?: JSX.Element
|
title?: JSX.Element
|
||||||
empty?: JSX.Element
|
empty?: JSX.Element
|
||||||
@@ -138,11 +159,14 @@ type SessionReviewSelection = {
|
|||||||
export const SessionReview = (props: SessionReviewProps) => {
|
export const SessionReview = (props: SessionReviewProps) => {
|
||||||
let scroll: HTMLDivElement | undefined
|
let scroll: HTMLDivElement | undefined
|
||||||
let focusToken = 0
|
let focusToken = 0
|
||||||
|
let frame: number | undefined
|
||||||
const i18n = useI18n()
|
const i18n = useI18n()
|
||||||
const fileComponent = useFileComponent()
|
const fileComponent = useFileComponent()
|
||||||
const anchors = new Map<string, HTMLElement>()
|
const anchors = new Map<string, HTMLElement>()
|
||||||
|
const nodes = new Map<string, HTMLDivElement>()
|
||||||
const [store, setStore] = createStore({
|
const [store, setStore] = createStore({
|
||||||
open: [] as string[],
|
open: [] as string[],
|
||||||
|
visible: {} as Record<string, boolean>,
|
||||||
force: {} as Record<string, boolean>,
|
force: {} as Record<string, boolean>,
|
||||||
selection: null as SessionReviewSelection | null,
|
selection: null as SessionReviewSelection | null,
|
||||||
commenting: null as SessionReviewSelection | null,
|
commenting: null as SessionReviewSelection | null,
|
||||||
@@ -153,7 +177,9 @@ export const SessionReview = (props: SessionReviewProps) => {
|
|||||||
const opened = () => store.opened
|
const opened = () => store.opened
|
||||||
|
|
||||||
const open = () => props.open ?? store.open
|
const open = () => props.open ?? store.open
|
||||||
const items = createMemo<Item[]>(() => props.diffs.map((diff) => ({ ...normalize(diff), preloaded: diff.preloaded })))
|
const items = createMemo<Item[]>(() =>
|
||||||
|
list(props.diffs).map((diff) => ({ ...normalize(diff), preloaded: diff.preloaded })),
|
||||||
|
)
|
||||||
const files = createMemo(() => items().map((diff) => diff.file))
|
const files = createMemo(() => items().map((diff) => diff.file))
|
||||||
const grouped = createMemo(() => {
|
const grouped = createMemo(() => {
|
||||||
const next = new Map<string, SessionReviewComment[]>()
|
const next = new Map<string, SessionReviewComment[]>()
|
||||||
@@ -170,7 +196,44 @@ export const SessionReview = (props: SessionReviewProps) => {
|
|||||||
const diffStyle = () => props.diffStyle ?? (props.split ? "split" : "unified")
|
const diffStyle = () => props.diffStyle ?? (props.split ? "split" : "unified")
|
||||||
const hasDiffs = () => files().length > 0
|
const hasDiffs = () => files().length > 0
|
||||||
|
|
||||||
|
const syncVisible = () => {
|
||||||
|
frame = undefined
|
||||||
|
if (!scroll) return
|
||||||
|
|
||||||
|
const root = scroll.getBoundingClientRect()
|
||||||
|
const top = root.top - REVIEW_MOUNT_MARGIN
|
||||||
|
const bottom = root.bottom + REVIEW_MOUNT_MARGIN
|
||||||
|
const openSet = new Set(open())
|
||||||
|
const next: Record<string, boolean> = {}
|
||||||
|
|
||||||
|
for (const [file, el] of nodes) {
|
||||||
|
if (!openSet.has(file)) continue
|
||||||
|
const rect = el.getBoundingClientRect()
|
||||||
|
if (rect.bottom < top || rect.top > bottom) continue
|
||||||
|
next[file] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const prev = untrack(() => store.visible)
|
||||||
|
const prevKeys = Object.keys(prev)
|
||||||
|
const nextKeys = Object.keys(next)
|
||||||
|
if (prevKeys.length === nextKeys.length && nextKeys.every((file) => prev[file])) return
|
||||||
|
setStore("visible", next)
|
||||||
|
}
|
||||||
|
|
||||||
|
const queue = () => {
|
||||||
|
if (frame !== undefined) return
|
||||||
|
frame = requestAnimationFrame(syncVisible)
|
||||||
|
}
|
||||||
|
|
||||||
|
const pinned = (file: string) =>
|
||||||
|
props.focusedComment?.file === file ||
|
||||||
|
props.focusedFile === file ||
|
||||||
|
selection()?.file === file ||
|
||||||
|
commenting()?.file === file ||
|
||||||
|
opened()?.file === file
|
||||||
|
|
||||||
const handleScroll: JSX.EventHandler<HTMLDivElement, Event> = (event) => {
|
const handleScroll: JSX.EventHandler<HTMLDivElement, Event> = (event) => {
|
||||||
|
queue()
|
||||||
const next = props.onScroll
|
const next = props.onScroll
|
||||||
if (!next) return
|
if (!next) return
|
||||||
if (Array.isArray(next)) {
|
if (Array.isArray(next)) {
|
||||||
@@ -181,9 +244,21 @@ export const SessionReview = (props: SessionReviewProps) => {
|
|||||||
;(next as JSX.EventHandler<HTMLDivElement, Event>)(event)
|
;(next as JSX.EventHandler<HTMLDivElement, Event>)(event)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
onCleanup(() => {
|
||||||
|
if (frame === undefined) return
|
||||||
|
cancelAnimationFrame(frame)
|
||||||
|
})
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
props.open
|
||||||
|
files()
|
||||||
|
queue()
|
||||||
|
})
|
||||||
|
|
||||||
const handleChange = (next: string[]) => {
|
const handleChange = (next: string[]) => {
|
||||||
props.onOpenChange?.(next)
|
props.onOpenChange?.(next)
|
||||||
if (props.open === undefined) setStore("open", next)
|
if (props.open === undefined) setStore("open", next)
|
||||||
|
queue()
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleExpandOrCollapseAll = () => {
|
const handleExpandOrCollapseAll = () => {
|
||||||
@@ -297,6 +372,7 @@ export const SessionReview = (props: SessionReviewProps) => {
|
|||||||
viewportRef={(el) => {
|
viewportRef={(el) => {
|
||||||
scroll = el
|
scroll = el
|
||||||
props.scrollRef?.(el)
|
props.scrollRef?.(el)
|
||||||
|
queue()
|
||||||
}}
|
}}
|
||||||
onScroll={handleScroll}
|
onScroll={handleScroll}
|
||||||
classList={{
|
classList={{
|
||||||
@@ -309,9 +385,11 @@ export const SessionReview = (props: SessionReviewProps) => {
|
|||||||
<Accordion multiple value={open()} onChange={handleChange}>
|
<Accordion multiple value={open()} onChange={handleChange}>
|
||||||
<For each={items()}>
|
<For each={items()}>
|
||||||
{(diff) => {
|
{(diff) => {
|
||||||
|
let wrapper: HTMLDivElement | undefined
|
||||||
const file = diff.file
|
const file = diff.file
|
||||||
|
|
||||||
const expanded = createMemo(() => open().includes(file))
|
const expanded = createMemo(() => open().includes(file))
|
||||||
|
const mounted = createMemo(() => expanded() && (!!store.visible[file] || pinned(file)))
|
||||||
const force = () => !!store.force[file]
|
const force = () => !!store.force[file]
|
||||||
|
|
||||||
const comments = createMemo(() => grouped().get(file) ?? [])
|
const comments = createMemo(() => grouped().get(file) ?? [])
|
||||||
@@ -402,6 +480,8 @@ export const SessionReview = (props: SessionReviewProps) => {
|
|||||||
|
|
||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
anchors.delete(file)
|
anchors.delete(file)
|
||||||
|
nodes.delete(file)
|
||||||
|
queue()
|
||||||
})
|
})
|
||||||
|
|
||||||
const handleLineSelected = (range: SelectedLineRange | null) => {
|
const handleLineSelected = (range: SelectedLineRange | null) => {
|
||||||
@@ -484,11 +564,21 @@ export const SessionReview = (props: SessionReviewProps) => {
|
|||||||
<div
|
<div
|
||||||
data-slot="session-review-diff-wrapper"
|
data-slot="session-review-diff-wrapper"
|
||||||
ref={(el) => {
|
ref={(el) => {
|
||||||
|
wrapper = el
|
||||||
anchors.set(file, el)
|
anchors.set(file, el)
|
||||||
|
nodes.set(file, el)
|
||||||
|
queue()
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Show when={expanded()}>
|
<Show when={expanded()}>
|
||||||
<Switch>
|
<Switch>
|
||||||
|
<Match when={!mounted() && !tooLarge()}>
|
||||||
|
<div
|
||||||
|
data-slot="session-review-diff-placeholder"
|
||||||
|
class="rounded-lg border border-border-weak-base bg-background-stronger/40"
|
||||||
|
style={{ height: "160px" }}
|
||||||
|
/>
|
||||||
|
</Match>
|
||||||
<Match when={tooLarge()}>
|
<Match when={tooLarge()}>
|
||||||
<div data-slot="session-review-large-diff">
|
<div data-slot="session-review-large-diff">
|
||||||
<div data-slot="session-review-large-diff-title">
|
<div data-slot="session-review-large-diff-title">
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import { type VirtualFileMetrics, Virtualizer } from "@pierre/diffs"
|
||||||
|
|
||||||
|
type Target = {
|
||||||
|
key: Document | HTMLElement
|
||||||
|
root: Document | HTMLElement
|
||||||
|
content: HTMLElement | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
type Entry = {
|
||||||
|
virtualizer: Virtualizer
|
||||||
|
refs: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const cache = new WeakMap<Document | HTMLElement, Entry>()
|
||||||
|
|
||||||
|
export const virtualMetrics: Partial<VirtualFileMetrics> = {
|
||||||
|
lineHeight: 24,
|
||||||
|
hunkSeparatorHeight: 24,
|
||||||
|
fileGap: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrollable(value: string) {
|
||||||
|
return value === "auto" || value === "scroll" || value === "overlay"
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrollRoot(container: HTMLElement) {
|
||||||
|
let node = container.parentElement
|
||||||
|
while (node) {
|
||||||
|
const style = getComputedStyle(node)
|
||||||
|
if (scrollable(style.overflowY)) return node
|
||||||
|
node = node.parentElement
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function target(container: HTMLElement): Target | undefined {
|
||||||
|
if (typeof document === "undefined") return
|
||||||
|
|
||||||
|
const review = container.closest("[data-component='session-review']")
|
||||||
|
if (review instanceof HTMLElement) {
|
||||||
|
const root = scrollRoot(container) ?? review
|
||||||
|
const content = review.querySelector("[data-slot='session-review-container']")
|
||||||
|
return {
|
||||||
|
key: review,
|
||||||
|
root,
|
||||||
|
content: content instanceof HTMLElement ? content : undefined,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const root = scrollRoot(container)
|
||||||
|
if (root) {
|
||||||
|
const content = root.querySelector("[role='log']")
|
||||||
|
return {
|
||||||
|
key: root,
|
||||||
|
root,
|
||||||
|
content: content instanceof HTMLElement ? content : undefined,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
key: document,
|
||||||
|
root: document,
|
||||||
|
content: undefined,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function acquireVirtualizer(container: HTMLElement) {
|
||||||
|
const resolved = target(container)
|
||||||
|
if (!resolved) return
|
||||||
|
|
||||||
|
let entry = cache.get(resolved.key)
|
||||||
|
if (!entry) {
|
||||||
|
const virtualizer = new Virtualizer()
|
||||||
|
virtualizer.setup(resolved.root, resolved.content)
|
||||||
|
entry = {
|
||||||
|
virtualizer,
|
||||||
|
refs: 0,
|
||||||
|
}
|
||||||
|
cache.set(resolved.key, entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
entry.refs += 1
|
||||||
|
let done = false
|
||||||
|
|
||||||
|
return {
|
||||||
|
virtualizer: entry.virtualizer,
|
||||||
|
release() {
|
||||||
|
if (done) return
|
||||||
|
done = true
|
||||||
|
|
||||||
|
const current = cache.get(resolved.key)
|
||||||
|
if (!current) return
|
||||||
|
|
||||||
|
current.refs -= 1
|
||||||
|
if (current.refs > 0) return
|
||||||
|
|
||||||
|
current.virtualizer.cleanUp()
|
||||||
|
cache.delete(resolved.key)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user