mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-13 15:03:43 -04:00
Compare commits
7 Commits
electron-audit-6
...
v2
| Author | SHA1 | Date | |
|---|---|---|---|
| ed708f9dc2 | |||
| f2408060b7 | |||
| 9fff6e2b4f | |||
| 2cf20e660e | |||
| fb8b4c4ce6 | |||
| 1b587823b6 | |||
| c7de57ee0e |
@@ -2,6 +2,7 @@ export * as InstructionDiscovery from "./instruction-discovery.js"
|
||||
|
||||
import { Context, Effect, Layer, Schema, Types } from "effect"
|
||||
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
|
||||
import { createPatch } from "diff"
|
||||
import { Bus } from "./bus.js"
|
||||
import { Instructions } from "./instructions/index.js"
|
||||
import { AbsolutePath } from "./schema.js"
|
||||
@@ -81,8 +82,7 @@ export const layer = (options?: Options) =>
|
||||
read: Effect.succeed(value),
|
||||
render: {
|
||||
initial: render,
|
||||
changed: (_previous, current) =>
|
||||
`These instructions replace all previously loaded ambient instructions.\n\n${render(current)}`,
|
||||
changed: renderUpdate,
|
||||
removed: () => "Previously loaded instructions no longer apply.",
|
||||
},
|
||||
})
|
||||
@@ -120,3 +120,27 @@ export const node = configured()
|
||||
function render(files: ReadonlyArray<File>) {
|
||||
return files.map((file) => `Instructions from: ${file.path}\n${file.content}`).join("\n\n")
|
||||
}
|
||||
|
||||
function renderUpdate(previous: ReadonlyArray<File>, current: ReadonlyArray<File>) {
|
||||
const changes = Instructions.diffByKey(
|
||||
previous,
|
||||
current,
|
||||
(file) => file.path,
|
||||
(before, after) => before.content !== after.content,
|
||||
)
|
||||
return [
|
||||
...changes.removed.map((file) => `The instructions from ${file.path} no longer apply.`),
|
||||
...changes.added.map((file) => `New instructions apply from:\n${render([file])}`),
|
||||
...changes.changed.map(({ previous: before, current: after }) => {
|
||||
const patch = createPatch(after.path, before.content, after.content, "", "", { context: 3 })
|
||||
const diff = [
|
||||
`The instructions from ${after.path} changed. Here's the diff:`,
|
||||
"```diff",
|
||||
patch.slice(patch.indexOf("@@")).trimEnd(),
|
||||
"```",
|
||||
].join("\n")
|
||||
const replacement = `The instructions changed:\n${render([after])}`
|
||||
return diff.length < replacement.length ? diff : replacement
|
||||
}),
|
||||
].join("\n\n")
|
||||
}
|
||||
|
||||
@@ -111,6 +111,50 @@ describe("InstructionDiscovery", () => {
|
||||
).toBe(false)
|
||||
}).pipe(Effect.provide(AppNodeBuilder.build(LayerNode.group([InstructionDiscovery.node, Bus.node])))),
|
||||
)
|
||||
|
||||
it.effect("renders granular instruction updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const discovery = yield* InstructionDiscovery.Service
|
||||
yield* discovery.transform((draft) => {
|
||||
draft.add(file("/global/AGENTS.md", "global"))
|
||||
draft.add(
|
||||
file("/repo/AGENTS.md", ["old", ...Array.from({ length: 20 }, (_, index) => `keep ${index}`)].join("\n")),
|
||||
)
|
||||
})
|
||||
const initial = yield* readInitial(yield* discovery.load())
|
||||
|
||||
yield* discovery.transform((draft) => {
|
||||
draft.update("/repo/AGENTS.md", (current) => {
|
||||
current.content = ["new", ...Array.from({ length: 20 }, (_, index) => `keep ${index}`)].join("\n")
|
||||
})
|
||||
})
|
||||
const modified = (yield* readUpdate(yield* discovery.load(), initial)).text
|
||||
expect(modified).toContain("The instructions from /repo/AGENTS.md changed. Here's the diff:")
|
||||
expect(modified).toContain("-old\n+new")
|
||||
expect(modified).not.toContain("global")
|
||||
|
||||
const rewritten = state({
|
||||
"core/instructions": [{ path: "/repo/AGENTS.md", content: "old one\nold two\nold three\nold four" }],
|
||||
})
|
||||
yield* discovery.transform((draft) => {
|
||||
draft.remove("/global/AGENTS.md")
|
||||
draft.update("/repo/AGENTS.md", (current) => {
|
||||
current.content = "new"
|
||||
})
|
||||
})
|
||||
expect((yield* readUpdate(yield* discovery.load(), rewritten)).text).toBe(
|
||||
"The instructions changed:\nInstructions from: /repo/AGENTS.md\nnew",
|
||||
)
|
||||
|
||||
yield* discovery.transform((draft) => {
|
||||
draft.add(file("/repo/packages/AGENTS.md", "package"))
|
||||
})
|
||||
const structural = (yield* readUpdate(yield* discovery.load(), initial)).text
|
||||
expect(structural).toContain("The instructions from /global/AGENTS.md no longer apply.")
|
||||
expect(structural).toContain("New instructions apply from:\nInstructions from: /repo/packages/AGENTS.md\npackage")
|
||||
expect(structural).not.toContain("Instructions from: /global/AGENTS.md\nglobal")
|
||||
}).pipe(Effect.provide(AppNodeBuilder.build(LayerNode.group([InstructionDiscovery.node, Bus.node])))),
|
||||
)
|
||||
})
|
||||
|
||||
describe("ConfigInstructionPlugin.Plugin", () => {
|
||||
@@ -168,20 +212,15 @@ describe("ConfigInstructionPlugin.Plugin", () => {
|
||||
|
||||
yield* Effect.promise(() => fs.writeFile(packageFile, "changed"))
|
||||
yield* emitAndWait({ type: "update", path: packageFile })
|
||||
expect((yield* readUpdate(yield* discovery.load(), initialized)).text).toContain(
|
||||
`Instructions from: ${packageFile}\nchanged`,
|
||||
)
|
||||
const changed = (yield* readUpdate(yield* discovery.load(), initialized)).text
|
||||
expect(changed).toContain(`The instructions changed:\nInstructions from: ${packageFile}\nchanged`)
|
||||
expect(changed).not.toContain(`Instructions from: ${globalFile}\nglobal`)
|
||||
|
||||
yield* Effect.promise(() => fs.rm(packageFile))
|
||||
yield* emitAndWait({ type: "delete", path: packageFile })
|
||||
expect((yield* readUpdate(yield* discovery.load(), initialized)).text).toBe(
|
||||
[
|
||||
"These instructions replace all previously loaded ambient instructions.",
|
||||
`Instructions from: ${globalFile}\nglobal`,
|
||||
`Instructions from: ${projectFile}\nproject`,
|
||||
`Instructions from: ${sharedFile}\nshared`,
|
||||
].join("\n\n"),
|
||||
)
|
||||
const removed = (yield* readUpdate(yield* discovery.load(), initialized)).text
|
||||
expect(removed).toContain(`The instructions from ${packageFile} no longer apply.`)
|
||||
expect(removed).not.toContain(`Instructions from: ${globalFile}\nglobal`)
|
||||
|
||||
yield* Effect.promise(() => fs.rm(globalFile))
|
||||
yield* emitAndWait({ type: "delete", path: globalFile })
|
||||
|
||||
@@ -115,9 +115,10 @@ export function elements(renderer: CliRenderer): Element[] {
|
||||
}
|
||||
|
||||
export function state(harness: Harness) {
|
||||
const renderable = harness.renderer.currentFocusedRenderable?.num
|
||||
return {
|
||||
focused: {
|
||||
renderable: harness.renderer.currentFocusedRenderable?.num,
|
||||
...(renderable === undefined ? {} : { renderable }),
|
||||
editor: Boolean(harness.renderer.currentFocusedEditor),
|
||||
},
|
||||
elements: elements(harness.renderer),
|
||||
|
||||
@@ -14,6 +14,18 @@ test("matches literal screen text", () => {
|
||||
expect(matches(harness, "opencode")).toBe(false)
|
||||
})
|
||||
|
||||
test("omits an absent focused renderable from state", () => {
|
||||
const harness = {
|
||||
renderer: {
|
||||
root: { getChildren: () => [] },
|
||||
currentFocusedRenderable: undefined,
|
||||
currentFocusedEditor: undefined,
|
||||
},
|
||||
} as unknown as Harness
|
||||
|
||||
expect(state(harness)).toEqual({ focused: { editor: false }, elements: [] })
|
||||
})
|
||||
|
||||
test("normalizes named keys for OpenTUI", async () => {
|
||||
const pressed: Array<readonly [string, object | undefined]> = []
|
||||
const harness = {
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
moveSessionTab,
|
||||
NEW_SESSION_TAB_TITLE,
|
||||
sessionTabComplete,
|
||||
sessionTabDetail,
|
||||
sessionTabShortcutLabel,
|
||||
seedSessionTabMotion,
|
||||
sessionTabOverflowWidth,
|
||||
@@ -408,10 +409,20 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
const titleFades = createMemo(() => marqueeOverflows(title(), titleWidth()) && titleWidth() > FADE_WIDTH)
|
||||
const detail = createMemo(() => {
|
||||
const fixture = tabs.detail?.(tab.sessionID)
|
||||
if (fixture !== undefined) return Locale.takeWidth(fixture, titleWidth())
|
||||
if (fixture !== undefined) return fixture
|
||||
const value = session()
|
||||
return Locale.takeWidth(projectName(project(), value?.location.directory) ?? "", titleWidth())
|
||||
const currentProject = project()
|
||||
const projectLabel = projectName(currentProject, value?.location.directory) ?? ""
|
||||
const vcs = value ? data.location.vcs.info(value.location) : undefined
|
||||
const location = value ? data.location.info(value.location) : undefined
|
||||
const worktree = !!location && location.project.directory !== location.project.canonical
|
||||
return sessionTabDetail(projectLabel, vcs?.branch.current, vcs?.branch.default, worktree)
|
||||
})
|
||||
const visibleDetail = createMemo(() => Locale.takeWidth(detail(), titleWidth()))
|
||||
const visibleDetailParts = createMemo(() => Locale.graphemes(visibleDetail()))
|
||||
const detailFades = createMemo(
|
||||
() => marqueeOverflows(detail(), titleWidth()) && titleWidth() > FADE_WIDTH,
|
||||
)
|
||||
const background = createMemo(() => {
|
||||
if (selected()) return theme.background.action.primary.selected
|
||||
if (hovered() === tab.sessionID || dragging() === tab.sessionID)
|
||||
@@ -453,6 +464,10 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
const detailFlashColor = createMemo(() => tint(pulseBackground(), theme.text.default, 0.42))
|
||||
const detailGlowColor = createMemo(() => tint(pulseBackground(), glowHue(), 0.25))
|
||||
const detailColor = createMemo(() => tint(theme.text.subdued, pulseBackground(), 0.35))
|
||||
const detailTextColor = (index: number) =>
|
||||
detailFades()
|
||||
? fadeTitleColor(detailColor(), pulseBackground(), index, visibleDetailParts().length, 0)
|
||||
: detailColor()
|
||||
const glows = () => status().glows
|
||||
const previous = createMemo(() => items()[index() - 1])
|
||||
const previousStatus = createMemo(() => {
|
||||
@@ -670,7 +685,11 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
/>
|
||||
<box zIndex={1} width="100%" flexDirection="row" paddingLeft={numberWidth() + 1} paddingRight={2}>
|
||||
<text fg={detailColor()} wrapMode="none" selectable={false}>
|
||||
{detail()}
|
||||
<Show when={detailFades()} fallback={visibleDetail()}>
|
||||
<For each={visibleDetailParts()}>
|
||||
{(character, index) => <span style={{ fg: detailTextColor(index()) }}>{character}</span>}
|
||||
</For>
|
||||
</Show>
|
||||
</text>
|
||||
</box>
|
||||
</box>
|
||||
|
||||
@@ -94,7 +94,7 @@ type Store = {
|
||||
location: Record<string, LocationData>
|
||||
}
|
||||
|
||||
function locationKey(location: LocationRef) {
|
||||
export function locationKey(location: LocationRef) {
|
||||
return JSON.stringify([location.directory, location.workspaceID])
|
||||
}
|
||||
|
||||
@@ -1214,9 +1214,9 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({
|
||||
default() {
|
||||
return defaultLocation()
|
||||
},
|
||||
async sync(ref?: LocationRef) {
|
||||
syncInfo(ref?: LocationRef) {
|
||||
const current = ref ?? defaultLocation()
|
||||
await sync.run(`location:${locationKey(current)}`, async () => {
|
||||
return sync.run(`location:${locationKey(current)}`, async () => {
|
||||
const location = await client.api.location.get({ location: locationQuery(current) })
|
||||
const key = locationKey(location)
|
||||
if (!store.location[key]) setStore("location", key, {})
|
||||
@@ -1225,6 +1225,9 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({
|
||||
setDefaultLocation({ directory: location.directory, workspaceID: location.workspaceID })
|
||||
}
|
||||
})
|
||||
},
|
||||
async sync(ref?: LocationRef) {
|
||||
await result.location.syncInfo(ref)
|
||||
const location = ref ?? defaultLocation()
|
||||
await Promise.all([
|
||||
result.location.vcs.sync(location),
|
||||
|
||||
@@ -13,6 +13,16 @@ export function sessionTabShortcutLabel(index: number) {
|
||||
return "·"
|
||||
}
|
||||
|
||||
export function sessionTabDetail(
|
||||
project: string,
|
||||
current: string | undefined,
|
||||
defaultBranch: string | undefined,
|
||||
worktree: boolean,
|
||||
) {
|
||||
const branch = worktree && current !== defaultBranch ? current : undefined
|
||||
return branch && project ? `${project} ⎇ ${branch}` : (branch ?? project)
|
||||
}
|
||||
|
||||
export type SessionTabHistory = {
|
||||
entries: readonly string[]
|
||||
index: number
|
||||
|
||||
@@ -2,7 +2,7 @@ import { createEffect, createMemo, createSignal, onCleanup } from "solid-js"
|
||||
import { isDeepEqual } from "remeda"
|
||||
import { createSimpleContext } from "./helper"
|
||||
import { useClient } from "./client"
|
||||
import { useData } from "./data"
|
||||
import { locationKey, useData } from "./data"
|
||||
import { withTimestampedFallback } from "@opencode-ai/util/session-title-fallback"
|
||||
import { useEvent } from "./event"
|
||||
import { useRoute } from "./route"
|
||||
@@ -159,9 +159,9 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
})
|
||||
})
|
||||
|
||||
// Load lightweight session metadata concurrently so persisted tabs can resolve their project
|
||||
// labels immediately. Delay the heavier per-tab data so the visible session keeps the first
|
||||
// connection slots and switches still render from a warm cache.
|
||||
// Load lightweight session and location metadata concurrently so persisted tabs can resolve
|
||||
// their project and branch labels. Delay the heavier per-tab data so the visible session keeps
|
||||
// the first connection slots and switches still render from a warm cache.
|
||||
const openTabSessions = createMemo(() =>
|
||||
state()
|
||||
.tabs.map((tab) => tab.sessionID)
|
||||
@@ -171,10 +171,25 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
createEffect(() => {
|
||||
if (!enabled()) return
|
||||
if (client.connection.status() !== "connected") return
|
||||
const sessionIDs = openTabSessions()
|
||||
if (sessionIDs === "") return
|
||||
void Promise.allSettled(sessionIDs.split("\n").map((sessionID) => data.session.sync(sessionID)))
|
||||
const signature = openTabSessions()
|
||||
if (signature === "") return
|
||||
const sessionIDs = signature.split("\n")
|
||||
let stale = false
|
||||
void (async () => {
|
||||
await Promise.allSettled(sessionIDs.map((sessionID) => data.session.sync(sessionID)))
|
||||
if (stale) return
|
||||
const locations = new Map(
|
||||
sessionIDs
|
||||
.map((sessionID) => data.session.get(sessionID)?.location)
|
||||
.filter((location) => location !== undefined)
|
||||
.map((location) => [locationKey(location), location]),
|
||||
)
|
||||
await Promise.allSettled(
|
||||
Array.from(locations.values(), (location) =>
|
||||
Promise.all([data.location.syncInfo(location), data.location.vcs.sync(location)]),
|
||||
),
|
||||
)
|
||||
})()
|
||||
const timer = setTimeout(async () => {
|
||||
const sessions = state()
|
||||
.tabs.map((tab) => tab.sessionID)
|
||||
|
||||
@@ -94,6 +94,7 @@ export function Composer(props: ComposerProps) {
|
||||
Keymap.createLayer(() => ({
|
||||
mode: "composer",
|
||||
enabled: () => props.open,
|
||||
priority: 1,
|
||||
commands: [
|
||||
{ bind: "left", title: "Previous tab", group: "Composer", run: () => switchTab(-1) },
|
||||
{ bind: "right", title: "Next tab", group: "Composer", run: () => switchTab(1) },
|
||||
|
||||
@@ -50,6 +50,7 @@ export function ShellTab(props: { sessionID: string }) {
|
||||
Keymap.createLayer(() => ({
|
||||
mode: "composer",
|
||||
enabled: () => composer.active("shell"),
|
||||
priority: 1,
|
||||
commands: [
|
||||
{
|
||||
id: "composer.shell.up",
|
||||
|
||||
@@ -164,6 +164,7 @@ export function SubagentsTab(props: { sessionID: string }) {
|
||||
Keymap.createLayer(() => ({
|
||||
mode: "composer",
|
||||
enabled: () => composer.active("subagents"),
|
||||
priority: 1,
|
||||
commands: [
|
||||
{
|
||||
id: "composer.subagent.up",
|
||||
|
||||
@@ -2872,16 +2872,8 @@ function Shell(props: ToolProps) {
|
||||
})
|
||||
const maxLines = 10
|
||||
const maxChars = createMemo(() => maxLines * Math.max(20, ctx.width - 6))
|
||||
const prompt = createMemo(() => (workdir() && workdir() !== "." ? `${workdir()}$` : "$"))
|
||||
const input = createMemo(() => {
|
||||
const cmd = command()
|
||||
if (!cmd) return ""
|
||||
// While running, the workdir prompt shares the spinner's text column; when
|
||||
// settled, the prompt renders as its own column so wrapped command lines
|
||||
// keep a stable hanging indent instead of jumping to the card inset.
|
||||
if (isRunning() && prompt() !== "$") return `${prompt()} ${cmd}`
|
||||
return cmd
|
||||
})
|
||||
const prefix = createMemo(() => (workdir() && workdir() !== "." ? `cd ${workdir()} && ` : ""))
|
||||
const input = createMemo(() => (command() ? `${isRunning() ? "" : "$ "}${prefix()}${command()}` : ""))
|
||||
const content = createMemo(() => [input(), output()].filter(Boolean).join("\n\n"))
|
||||
const collapsed = createMemo(() => collapseToolOutput(content(), maxLines, maxChars()))
|
||||
const limited = createMemo(() => {
|
||||
@@ -2910,15 +2902,7 @@ function Shell(props: ToolProps) {
|
||||
)
|
||||
}
|
||||
>
|
||||
<Show
|
||||
when={isRunning()}
|
||||
fallback={
|
||||
<box flexDirection="row" gap={1}>
|
||||
<text fg={theme.text.default}>{prompt()}</text>
|
||||
<text fg={theme.text.default}>{limitedInput()}</text>
|
||||
</box>
|
||||
}
|
||||
>
|
||||
<Show when={isRunning()} fallback={<text fg={theme.text.default}>{limitedInput()}</text>}>
|
||||
<Spinner color={color()}>{limitedInput()}</Spinner>
|
||||
</Show>
|
||||
<Show when={limitedOutput()}>
|
||||
|
||||
@@ -23,7 +23,11 @@ const sessions = {
|
||||
|
||||
const shells = [shell("sh-a", "bun test"), shell("sh-b", "bun dev")]
|
||||
|
||||
async function renderComposer(defaultTab: "subagents" | "shell", keybinds: Partial<TuiKeybind.Keybinds>) {
|
||||
async function renderComposer(
|
||||
defaultTab: "subagents" | "shell",
|
||||
keybinds: Partial<TuiKeybind.Keybinds>,
|
||||
focusedTextarea = false,
|
||||
) {
|
||||
const events = createEventStream()
|
||||
const interrupted: string[] = []
|
||||
const removed: string[] = []
|
||||
@@ -69,7 +73,21 @@ async function renderComposer(defaultTab: "subagents" | "shell", keybinds: Parti
|
||||
.then(() => wait(() => data.session.status("child-a") === "running"))
|
||||
.then(() => ready.resolve(), ready.reject)
|
||||
})
|
||||
return <Composer sessionID="parent" open={true} defaultTab={defaultTab} onClose={() => closed++} />
|
||||
return (
|
||||
<>
|
||||
{focusedTextarea && <textarea focused={true} initialValue="draft" />}
|
||||
<Composer sessionID="parent" open={true} defaultTab={defaultTab} onClose={() => closed++} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function AppExit() {
|
||||
Keymap.createLayer(() => ({
|
||||
mode: "global",
|
||||
commands: [{ id: "app.exit", title: "Exit", group: "System", run: () => {} }],
|
||||
}))
|
||||
Keymap.createLayer(() => ({ bindings: ["app.exit"] }))
|
||||
return null
|
||||
}
|
||||
|
||||
const app = await testRender(
|
||||
@@ -88,6 +106,7 @@ async function renderComposer(defaultTab: "subagents" | "shell", keybinds: Parti
|
||||
</LocationProvider>
|
||||
</DataProvider>
|
||||
</ClientProvider>
|
||||
<AppExit />
|
||||
</Keymap.Provider>
|
||||
</ConfigProvider>
|
||||
</TestTuiContexts>
|
||||
@@ -154,6 +173,20 @@ test("disabled shell bindings have no component fallbacks", async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("configured composer bindings work with a focused textarea", async () => {
|
||||
const composer = await renderComposer("subagents", { "composer.shell.kill": "ctrl+u" }, true)
|
||||
try {
|
||||
composer.app.mockInput.pressArrow("right")
|
||||
await composer.app.renderOnce()
|
||||
expect(composer.app.captureCharFrame()).toContain("bun test")
|
||||
composer.app.mockInput.pressKey("u", { ctrl: true })
|
||||
await wait(() => composer.removed.length === 1)
|
||||
expect(composer.removed).toEqual(["sh-a"])
|
||||
} finally {
|
||||
composer.app.renderer.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
function session(id: string, title: string, parentID?: string) {
|
||||
return {
|
||||
id,
|
||||
|
||||
@@ -11,11 +11,20 @@ import {
|
||||
reopenSessionTab,
|
||||
seedSessionTabMotion,
|
||||
sessionTabComplete,
|
||||
sessionTabDetail,
|
||||
sessionTabOverflowWidth,
|
||||
sessionTabShortcutLabel,
|
||||
} from "../../src/context/session-tabs-model"
|
||||
|
||||
describe("session tabs", () => {
|
||||
test("appends the branch to the project detail", () => {
|
||||
expect(sessionTabDetail("opencode", "feature/sidebar", "main", true)).toBe("opencode ⎇ feature/sidebar")
|
||||
expect(sessionTabDetail("opencode", "feature/sidebar", undefined, true)).toBe("opencode ⎇ feature/sidebar")
|
||||
expect(sessionTabDetail("opencode", "feature/sidebar", "main", false)).toBe("opencode")
|
||||
expect(sessionTabDetail("opencode", "main", "main", true)).toBe("opencode")
|
||||
expect(sessionTabDetail("opencode", undefined, "main", true)).toBe("opencode")
|
||||
})
|
||||
|
||||
test("labels direct shortcut tabs and marks unbound tabs with a dot", () => {
|
||||
expect(Array.from({ length: 12 }, (_, index) => sessionTabShortcutLabel(index))).toEqual([
|
||||
"1",
|
||||
|
||||
@@ -28,7 +28,14 @@ async function wait(fn: () => boolean | Promise<boolean>, timeout = 2_000) {
|
||||
|
||||
async function renderSessionTabs(
|
||||
initialSessionID: string,
|
||||
options?: { state?: string; title?: string; home?: boolean; persisted?: string[]; sessionGate?: Promise<void> },
|
||||
options?: {
|
||||
state?: string
|
||||
title?: string
|
||||
home?: boolean
|
||||
persisted?: string[]
|
||||
sessionGate?: Promise<void>
|
||||
sessionDirectories?: Record<string, string>
|
||||
},
|
||||
) {
|
||||
const temporary = options?.state ? undefined : await tmpdir()
|
||||
const state = options?.state ?? temporary!.path
|
||||
@@ -45,7 +52,25 @@ async function renderSessionTabs(
|
||||
}
|
||||
const events = createEventStream()
|
||||
const sessions: string[] = []
|
||||
const locations: string[] = []
|
||||
const vcsLocations: string[] = []
|
||||
const calls = createFetch(async (url) => {
|
||||
if (url.pathname === "/api/location") {
|
||||
const requested = url.searchParams.get("location[directory]") ?? directory
|
||||
locations.push(requested)
|
||||
return json({
|
||||
directory: requested,
|
||||
project: { id: "project", directory: requested, canonical: directory },
|
||||
})
|
||||
}
|
||||
if (url.pathname === "/api/vcs") {
|
||||
const requested = url.searchParams.get("location[directory]") ?? directory
|
||||
vcsLocations.push(requested)
|
||||
return json({
|
||||
location: { directory: requested },
|
||||
data: { branch: { current: "main", default: "main" } },
|
||||
})
|
||||
}
|
||||
const sessionID = url.pathname.match(/^\/api\/session\/([^/]+)$/)?.[1]
|
||||
if (!sessionID) return undefined
|
||||
sessions.push(sessionID)
|
||||
@@ -55,7 +80,7 @@ async function renderSessionTabs(
|
||||
id: sessionID,
|
||||
title: sessionID === initialSessionID ? options?.title : undefined,
|
||||
projectID: "project",
|
||||
location: { directory },
|
||||
location: { directory: options?.sessionDirectories?.[sessionID] ?? directory },
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: { created: 0, updated: 0 },
|
||||
@@ -107,6 +132,8 @@ async function renderSessionTabs(
|
||||
route,
|
||||
data,
|
||||
sessions,
|
||||
locations,
|
||||
vcsLocations,
|
||||
state,
|
||||
emit: (event: OpenCodeEvent) => events.emit({ ...event, location: { directory } }),
|
||||
async destroy() {
|
||||
@@ -137,6 +164,22 @@ test("loads persisted tab metadata concurrently on connect", async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("loads VCS metadata for each persisted tab location", async () => {
|
||||
const other = `${directory}/other-worktree`
|
||||
const setup = await renderSessionTabs("first", {
|
||||
home: true,
|
||||
persisted: ["first", "second"],
|
||||
sessionDirectories: { second: other },
|
||||
})
|
||||
|
||||
try {
|
||||
await wait(() => setup.locations.includes(other))
|
||||
await wait(() => setup.vcsLocations.includes(other))
|
||||
} finally {
|
||||
await setup.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("stores session tabs for the current working directory by default", async () => {
|
||||
const setup = await renderSessionTabs("first")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user