Skip to content
5 changes: 5 additions & 0 deletions .github/labeler.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ ci:
- ".github/workflows/**"
- ".github/**"

task:
- changed-files:
- any-glob-to-any-file:
- ".github/workflows/**"

platform:
- changed-files:
- any-glob-to-any-file:
Expand Down
51 changes: 38 additions & 13 deletions packages/app/src/pages/session/use-session-vcs-refresh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,45 @@ import { describe, expect, test } from "bun:test"
import { isFileWatcherVcsRefreshEvent } from "./use-session-vcs-refresh"

describe("session vcs refresh watcher events", () => {
test("refreshes for rescan and non-git file updates only", () => {
test("refreshes for rescan, source updates, and git state updates", () => {
expect(isFileWatcherVcsRefreshEvent({ type: "file.watcher.rescan", properties: { directory: "/repo" } })).toBe(true)
expect(
isFileWatcherVcsRefreshEvent({
type: "file.watcher.updated",
properties: { file: "src/app.ts", event: "change" },
}),
).toBe(true)
expect(
isFileWatcherVcsRefreshEvent({
type: "file.watcher.updated",
properties: { file: ".git/index", event: "change" },
}),
).toBe(false)

for (const file of [
"src/app.ts",
".git/index",
".git/HEAD",
".git/packed-refs",
".git/refs/heads/feature/test",
".git/refs/remotes/origin/dev",
".git/logs/HEAD",
".git/worktrees/review-worktree/gitdir",
".git\\refs\\heads\\feature\\test",
"/repo/.git/index",
"/repo/.git/HEAD",
"C:\\repo\\.git\\refs\\heads\\feature\\test",
]) {
expect(isFileWatcherVcsRefreshEvent({ type: "file.watcher.updated", properties: { file, event: "change" } })).toBe(
true,
)
}

for (const file of [
".git/objects/aa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
".git/refs/tags/v1.0.0",
".git/refs/stash",
".git/FETCH_HEAD",
".git/MERGE_HEAD",
".git/REVERT_HEAD",
".git/CHERRY_PICK_HEAD",
"/repo/.git/objects/aa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"/repo/.git/refs/tags/v1.0.0",
"C:\\repo\\.git\\objects\\aa\\bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
]) {
expect(isFileWatcherVcsRefreshEvent({ type: "file.watcher.updated", properties: { file, event: "change" } })).toBe(
false,
)
}

expect(isFileWatcherVcsRefreshEvent({ type: "session.updated", properties: {} })).toBe(false)
})
})
22 changes: 20 additions & 2 deletions packages/app/src/pages/session/use-session-vcs-refresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,24 @@ export function isFileWatcherVcsRefreshEvent(event: { type: string; properties?:
if (event.type !== "file.watcher.updated") return false
const props =
typeof event.properties === "object" && event.properties ? (event.properties as Record<string, unknown>) : undefined
const file = typeof props?.file === "string" ? props.file : undefined
return !!file && !file.startsWith(".git/")
const file = normalizeWatcherFilePath(typeof props?.file === "string" ? props.file : undefined)
if (!file) return false
if (!file.startsWith(".git/")) return true
return (
file === ".git/index" ||
file === ".git/HEAD" ||
file === ".git/packed-refs" ||
file.startsWith(".git/refs/heads/") ||
file.startsWith(".git/refs/remotes/") ||
file.startsWith(".git/logs/HEAD") ||
file.startsWith(".git/worktrees/")
)
Comment thread
Astro-Han marked this conversation as resolved.
Resolved
}

function normalizeWatcherFilePath(file: string | undefined) {
const normalized = file?.replaceAll("\\", "/")
if (!normalized) return
const gitSegment = normalized.indexOf("/.git/")
if (gitSegment === -1) return normalized
return normalized.slice(gitSegment + 1)
}
29 changes: 22 additions & 7 deletions packages/opencode/src/file/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export namespace FileWatcher {
const log = Log.create({ service: "file.watcher" })
const SUBSCRIBE_TIMEOUT_MS = 10_000
const RESCAN_DEDUPE_MS = 1_000
const VCS_SUBSCRIBE_ENTRIES = new Set(["HEAD", "index", "packed-refs", "refs"])
const VCS_REFRESH_FILES = new Set(["HEAD", "index", "packed-refs"])
const VCS_REFRESH_PREFIXES = ["refs/heads/", "refs/remotes/"]

export const Event = {
Updated: BusEvent.define(
Expand Down Expand Up @@ -124,6 +127,17 @@ export namespace FileWatcher {
}
}

export function vcsWatcherIgnoreEntries(entries: string[]) {
return entries.filter((entry) => !VCS_SUBSCRIBE_ENTRIES.has(entry))
}

export function shouldPublishVcsWatcherPath(file: string, vcsDir: string) {
const relative = path.relative(vcsDir, file).replaceAll(path.sep, "/")
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) return false
if (VCS_REFRESH_FILES.has(relative)) return true
return VCS_REFRESH_PREFIXES.some((prefix) => relative.startsWith(prefix))
}

export interface Interface {
readonly init: () => Effect.Effect<void>
}
Expand Down Expand Up @@ -172,7 +186,9 @@ export namespace FileWatcher {
},
})
yield* Effect.addFinalizer(() => Effect.sync(() => requestRescan.dispose()))
const createCallback = (dir: string): ParcelWatcher.SubscribeCallback => (err, evts) =>
const createCallback =
(dir: string, shouldPublish = (_file: string) => true): ParcelWatcher.SubscribeCallback =>
(err, evts) =>
Comment thread
Astro-Han marked this conversation as resolved.
Resolved
Instance.restore(ctx, () => {
if (err) {
if (isDroppedEventsError(err)) {
Expand All @@ -183,14 +199,15 @@ export namespace FileWatcher {
return
}
for (const evt of evts) {
if (!shouldPublish(evt.path)) continue
if (evt.type === "create") Bus.publish(Event.Updated, { file: evt.path, event: "add" })
if (evt.type === "update") Bus.publish(Event.Updated, { file: evt.path, event: "change" })
if (evt.type === "delete") Bus.publish(Event.Updated, { file: evt.path, event: "unlink" })
}
})

const subscribe = (dir: string, ignore: string[]) => {
const pending = w.subscribe(dir, createCallback(dir), { ignore, backend })
const subscribe = (dir: string, ignore: string[], shouldPublish?: (file: string) => boolean) => {
const pending = w.subscribe(dir, createCallback(dir, shouldPublish), { ignore, backend })
return Effect.gen(function* () {
const sub = yield* Effect.promise(() => pending)
subs.push(sub)
Expand Down Expand Up @@ -222,10 +239,8 @@ export namespace FileWatcher {
const vcsDir =
result.exitCode === 0 ? path.resolve(ctx.project.worktree, result.text().trim()) : undefined
if (vcsDir && !cfgIgnores.includes(".git") && !cfgIgnores.includes(vcsDir)) {
const ignore = (yield* Effect.promise(() => readdir(vcsDir).catch(() => []))).filter(
(entry) => entry !== "HEAD",
)
yield* subscribe(vcsDir, ignore)
const ignore = vcsWatcherIgnoreEntries(yield* Effect.promise(() => readdir(vcsDir).catch(() => [])))
yield* subscribe(vcsDir, ignore, (file) => shouldPublishVcsWatcherPath(file, vcsDir))
}
}
},
Expand Down
29 changes: 27 additions & 2 deletions packages/opencode/src/project/instance-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import {
withLifecycleCloseAction,
} from "@/session/lifecycle-provenance"
import { currentRequestContext } from "@/server/request-context"
import fs from "node:fs"
import path from "node:path"

export interface LoadInput {
directory: string
Expand All @@ -26,6 +28,7 @@ type ContextMismatchReason =
| "worktree_mismatch"
| "project_id_mismatch"
| "project_row_missing"
| "project_vcs_changed"
| "explicit_context_changed"
| "unknown_context_mismatch"

Expand Down Expand Up @@ -70,6 +73,16 @@ function contextMismatchReason(ctx: InstanceContext, input: LoadInput): ContextM
return undefined
}

function hasGitMarker(directory: string) {
let current = directory
while (true) {
if (fs.existsSync(path.join(current, ".git"))) return true
const parent = path.dirname(current)
if (parent === current) return false
current = parent
}
}

export const layer = Layer.effect(
Service,
Effect.gen(function* () {
Expand Down Expand Up @@ -211,8 +224,20 @@ export const layer = Layer.effect(
const mismatchReason = contextMismatchReason(exit.value, input)
if (!mismatchReason) {
const row = yield* project.get(exit.value.project.id)
if (row) return exit.value
return yield* reload(input, "project_row_missing")
if (!row) return yield* reload(input, "project_row_missing")
if (exit.value.project.vcs !== "git" && hasGitMarker(directory)) {
const next = yield* project.fromDirectory(directory)
if (next.project.vcs === "git")
return yield* reload(
{
directory,
worktree: next.sandbox,
project: next.project,
},
"project_vcs_changed",
)
}
return exit.value
}
return yield* reload(input, mismatchReason)
}
Expand Down
60 changes: 57 additions & 3 deletions packages/opencode/test/file/watcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,31 @@ function ready(directory: string) {
// Tests
// ---------------------------------------------------------------------------

describe("FileWatcher git metadata filtering", () => {
test("keeps review-diff git metadata subscribed", () => {
expect(
FileWatcher.vcsWatcherIgnoreEntries(["HEAD", "index", "packed-refs", "refs", "objects", "logs", "hooks"]),
).toEqual(["objects", "logs", "hooks"])
})

test("publishes only review-diff git metadata from the vcs directory", () => {
const gitDir = path.join("/tmp", "repo", ".git")

expect(FileWatcher.shouldPublishVcsWatcherPath(path.join(gitDir, "HEAD"), gitDir)).toBe(true)
expect(FileWatcher.shouldPublishVcsWatcherPath(path.join(gitDir, "index"), gitDir)).toBe(true)
expect(FileWatcher.shouldPublishVcsWatcherPath(path.join(gitDir, "packed-refs"), gitDir)).toBe(true)
expect(FileWatcher.shouldPublishVcsWatcherPath(path.join(gitDir, "refs", "heads", "feature"), gitDir)).toBe(true)
expect(FileWatcher.shouldPublishVcsWatcherPath(path.join(gitDir, "refs", "remotes", "origin", "dev"), gitDir)).toBe(
true,
)

expect(FileWatcher.shouldPublishVcsWatcherPath(path.join(gitDir, "objects", "ab", "hash"), gitDir)).toBe(false)
expect(FileWatcher.shouldPublishVcsWatcherPath(path.join(gitDir, "refs", "tags", "v1"), gitDir)).toBe(false)
expect(FileWatcher.shouldPublishVcsWatcherPath(path.join(gitDir, "refs", "stash"), gitDir)).toBe(false)
expect(FileWatcher.shouldPublishVcsWatcherPath(path.join(gitDir, "MERGE_HEAD"), gitDir)).toBe(false)
})
})

describeWatcher("FileWatcher", () => {
afterEach(async () => {
await Instance.disposeAll()
Expand Down Expand Up @@ -206,21 +231,50 @@ describeWatcher("FileWatcher", () => {
})
})

test("ignores .git/index changes", async () => {
test("publishes .git/index changes", async () => {
await using tmp = await tmpdir({ git: true })
const gitIndex = path.join(tmp.path, ".git", "index")
const edit = path.join(tmp.path, "tracked.txt")

await withWatcher(
tmp.path,
noUpdate(
nextUpdate(
tmp.path,
(e) => e.file === gitIndex,
Effect.promise(async () => {
await fs.writeFile(edit, "a")
await $`git add .`.cwd(tmp.path).quiet().nothrow()
}),
),
).pipe(Effect.tap((evt) => Effect.sync(() => expect(evt.event).not.toBe("unlink")))),
)
})

test("publishes .git refs/heads changes", async () => {
await using tmp = await tmpdir({ git: true })
const branchRef = path.join(tmp.path, ".git", "refs", "heads", "watch-ref")
const hash = await $`git rev-parse HEAD`.cwd(tmp.path).quiet().text()

await withWatcher(
tmp.path,
nextUpdate(
tmp.path,
(evt) => evt.file === branchRef && evt.event !== "unlink",
Effect.promise(() => fs.writeFile(branchRef, hash.trim() + "\n")),
).pipe(Effect.tap((evt) => Effect.sync(() => expect(["add", "change"]).toContain(evt.event)))),
)
})

test("publishes .git/packed-refs changes", async () => {
await using tmp = await tmpdir({ git: true })
const packedRefs = path.join(tmp.path, ".git", "packed-refs")

await withWatcher(
tmp.path,
nextUpdate(
tmp.path,
(evt) => evt.file === packedRefs && evt.event !== "unlink",
Effect.promise(() => fs.writeFile(packedRefs, "# pack-refs with: peeled fully-peeled sorted\n")),
).pipe(Effect.tap((evt) => Effect.sync(() => expect(["add", "change"]).toContain(evt.event)))),
)
})

Expand Down
24 changes: 24 additions & 0 deletions packages/opencode/test/project/instance-store.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { afterEach, describe, expect, test } from "bun:test"
import { $ } from "bun"
import { Effect, Exit, Fiber, Layer, ManagedRuntime } from "effect"
import * as CrossSpawnSpawner from "@opencode-ai/core/cross-spawn-spawner"

Expand Down Expand Up @@ -140,6 +141,29 @@ describe("InstanceStore", () => {
}),
)

it.live("reloads a cached non-git instance when the directory becomes git", () =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
const store = yield* InstanceStore.Service
const disposed: string[] = []
const off = registerDisposer(async (directory) => {
disposed.push(directory)
})
yield* Effect.addFinalizer(() => Effect.sync(off))

const first = yield* store.load({ directory: dir })
expect(first.project.vcs).toBeUndefined()

yield* Effect.promise(() => $`git init --quiet`.cwd(dir).quiet())

const second = yield* store.load({ directory: dir })
expect(second).not.toBe(first)
expect(second.project.vcs).toBe("git")
expect(second.worktree).toBe(dir)
expect(disposed).toEqual([dir])
}),
)

it.live("disposeDirectory disposes loaded entries without loading missing directories", () =>
Effect.gen(function* () {
const loaded = yield* tmpdirScoped()
Expand Down