Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): make the sync panel truthful about push outcomes (#4417)

shagun-singh-inkeep1c405159d0f0
diff --git a/.changeset/sync-panel-truthfulness.md b/.changeset/sync-panel-truthfulness.md
new file mode 100644
index 000000000..0d764b6a0
--- /dev/null
+++ b/.changeset/sync-panel-truthfulness.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+The sync menu no longer shows files waiting to push after they reach GitHub, and explains when another program is using Git, the repository has no commits yet, or its file list may be out of date.
diff --git a/docs/content/features/github-sync.mdx b/docs/content/features/github-sync.mdx
index 0c06023df..d24336dd4 100644
--- a/docs/content/features/github-sync.mdx
+++ b/docs/content/features/github-sync.mdx
@@ -84,7 +84,7 @@ If you want to set a default sync setting for future collaborators, go to the pr
### Manual
-Nothing runs on a schedule. The sync menu's **Pull**, **Push**, and **Pull and Push** buttons cover everything on demand, and the menu's status section shows what each would do before you click: which files a pull would bring in, which files a push would include, and which changed files sit outside OpenKnowledge's commit scope and would be skipped. When sync is paused because your local edits overlap an incoming update, the same menu grows a **Changed here and on the remote** section listing the blocked files with a **Commit and sync** button — see [Conflicts and pending changes](#conflicts-and-pending-changes).
+Nothing runs on a schedule. The sync menu's **Pull**, **Push**, and **Pull and Push** buttons cover everything on demand, and the menu's status section shows what each would do before you click: which files a pull would bring in, which files a push would include, and which changed files sit outside OpenKnowledge's commit scope and would be skipped. If that list cannot be read the section says so, and if a refresh fails it keeps the last list and marks it as possibly out of date rather than showing you nothing. When sync is paused because your local edits overlap an incoming update, the same menu grows a **Changed here and on the remote** section listing the blocked files with a **Commit and sync** button — see [Conflicts and pending changes](#conflicts-and-pending-changes).
### Auto (Pull and Push)
@@ -129,7 +129,7 @@ The username entries above apply to HTTPS remotes only. SSH projects follow the
## Sync status and conflicts
-The sync status indicator in the editor opens the sync menu: the mode selector, the manual **Pull** / **Push** / **Pull and Push** buttons, and a live status section showing how far ahead or behind the remote you are, which files a pull would bring in, which files a push would include (and which it would skip), unresolved conflicts, and when a sync last ran. Opening the menu refreshes the remote counts with a read-only fetch — nothing in your copy moves until you press a button. From a terminal, `ok sync` commits, pulls, and pushes in one pass; `ok pull` and `ok push` cover one direction each. All three work whether or not the editor is open (see the [CLI reference](/docs/reference/cli)).
+The sync status indicator in the editor opens the sync menu: the mode selector, the manual **Pull** / **Push** / **Pull and Push** buttons, and a live status section showing how far ahead or behind the remote you are, which files a pull would bring in, which files a push would include (and which it would skip), unresolved conflicts, and when a sync last ran. Opening the menu refreshes the remote counts with a read-only fetch — nothing in your copy moves until you press a button. That status section also says when it cannot see your files: a working tree it cannot read at all renders **Couldn't read the working tree**, and a refresh that fails after a good read keeps the last list you saw and marks it as possibly out of date, counting up from when that read happened. Neither changes the sync status indicator's color, because the problem is with reading the list rather than with sync. From a terminal, `ok sync` commits, pulls, and pushes in one pass; `ok pull` and `ok push` cover one direction each. All three work whether or not the editor is open (see the [CLI reference](/docs/reference/cli)).
## Resolving a conflict
@@ -147,7 +147,7 @@ In the desktop app you can open several branches of the same project at once, ea
## Common failure modes
-A few situations stop sync from completing successfully. In each case the sync status indicator changes color and tells you what's wrong. Except where noted, sync stays paused until the underlying issue is fixed, then picks back up on its own.
+A few situations stop sync from completing successfully. Most of them change the sync status indicator's color and tell you what's wrong. Two of the local ones below — another program holding the Git index lock, and a project with no commits yet — change the indicator's color in Manual only; in the automatic modes they are reported in the sync menu and the indicator stays as it is. Except where noted, sync stays paused until the underlying issue is fixed, then picks back up on its own.
### Conflicts and pending changes
@@ -161,6 +161,10 @@ A few situations stop sync from completing successfully. In each case the sync s
- **The project is parked on a specific commit, not a branch.** This usually means someone checked out an older commit from the terminal to look around. There's no branch to push to, so sync pauses. Switch back to your normal branch (`main`, your working branch, whichever) and sync resumes.
- **Diverged history.** When the remote has been rewritten (force-push, rebase, branch reset) in a way OpenKnowledge can't reconcile automatically, sync stops and shows the error. This one usually needs a fix from the command line. Ask whoever rewrote the history for help, or restore from the [Timeline](/docs/features/timeline-and-recovery).
+### The project has no commits yet
+
+- **The repository has no commits yet.** The project has a remote, but its branch does not exist yet, so there is nothing to send: **Push** stops before it starts and the sync menu says so. Editing a document does not clear this on its own — auto-save writes to OpenKnowledge's own internal ref, never to your branch. Closing and reopening the project (or restarting the app) makes that first commit for you; running `git commit` yourself does the same. Push works from then on.
+
### GitHub-side blockers
- **Authentication errors.** Your stored credentials expired, were revoked, or don't have access to this repository anymore. Reconnect from the sync indicator (or from **Settings → Account**) to clear the error.
@@ -170,3 +174,4 @@ A few situations stop sync from completing successfully. In each case the sync s
### Temporary problems
- **Network or service hiccups.** Flaky Wi-Fi, a VPN drop, or a brief GitHub outage. OpenKnowledge retries automatically, slowing down progressively as described in [How often sync runs](#how-often-sync-runs). No action needed; a manual trigger from the sync indicator resets the backoff immediately if you want sync to run sooner.
+- **Another program is holding the Git index lock.** Git lets one process at a time write `.git/index`, and it enforces that by creating `.git/index.lock` first. Another tool on your machine — a terminal command, an editor extension, a background indexer — was holding that lock file when sync reached for it. The sync menu names `.git/index.lock` so you know it isn't your work that's wrong. In Auto and Follow modes sync keeps trying and picks up on its own once the other program lets go. In Manual mode nothing runs unattended, so press Sync again after the other program finishes. If the message persists, look for a git command still open in a terminal.
diff --git a/packages/app/src/components/SyncStatusBadge.dom.test.tsx b/packages/app/src/components/SyncStatusBadge.dom.test.tsx
index cca0edac9..c9ef34cfc 100644
--- a/packages/app/src/components/SyncStatusBadge.dom.test.tsx
+++ b/packages/app/src/components/SyncStatusBadge.dom.test.tsx
@@ -75,8 +75,18 @@ let worktree: {
readable?: boolean;
} | null = null;
+let worktreeUnreadable = false;
+let worktreeStale = false;
+let worktreeLastReadAt: number | null = null;
+
vi.doMock('@/hooks/use-git-worktree-status', () => ({
- useGitWorktreeStatus: () => ({ status: worktree, loading: worktree === null }),
+ useGitWorktreeStatus: () => ({
+ status: worktree,
+ loading: worktree === null && !worktreeUnreadable,
+ unreadable: worktreeUnreadable,
+ stale: worktreeStale,
+ lastReadAt: worktreeLastReadAt,
+ }),
}));
const triggered: string[] = [];
@@ -422,12 +432,71 @@ describe('SyncStatusBadge helper behavior', () => {
);
});
+ async function loadPausedReasonCopy() {
+ const mod = await import('./SyncStatusBadge');
+ const translate = renderLinguiTemplate as unknown as Parameters<
+ typeof mod.formatPausedReason
+ >[0];
+ return {
+ PausedReasonNotice: mod.PausedReasonNotice,
+ format: (reason: string) => mod.formatPausedReason(translate, reason),
+ };
+ }
+
test('formatPausedReason explains a pull-only divergence in plain language', async () => {
- const { formatPausedReason } = await import('./SyncStatusBadge');
- expect(formatPausedReason('diverged-local-commits')).toBe(
+ const { format } = await loadPausedReasonCopy();
+ expect(format('diverged-local-commits')).toBe(
'Local commits are keeping this copy from updating',
);
});
+
+ test('the notice renders the same copy the plain-string formatter returns', async () => {
+ const { PausedReasonNotice, format } = await loadPausedReasonCopy();
+ render(<PausedReasonNotice reason="diverged-local-commits" />);
+
+ expect(document.body.textContent).toBe(format('diverged-local-commits'));
+ cleanup();
+ });
+
+ test('a held index lock names the lock file and says it clears itself', async () => {
+ const { PausedReasonNotice } = await import('./SyncStatusBadge');
+ render(<PausedReasonNotice reason="git-index-locked" />);
+
+ const line = document.body.textContent ?? '';
+ expect(line).toContain('.git/index.lock');
+ expect(line).toMatch(/another program/i);
+ expect(line).not.toBe('git-index-locked');
+ cleanup();
+ });
+
+ test('the index-lock reason also has flat copy for callers that cannot render a node', async () => {
+ const { format } = await loadPausedReasonCopy();
+ const line = format('git-index-locked');
+
+ expect(line).toContain('.git/index.lock');
+ expect(line).toMatch(/another program/i);
+ expect(line).not.toBe('git-index-locked');
+ });
+
+ test('an unborn HEAD points at the remedy the product actually offers', async () => {
+ const { format } = await loadPausedReasonCopy();
+ const line = format('no-commits-yet');
+
+ expect(line).toMatch(/no commits yet/i);
+ expect(line).toMatch(/reopen the project/i);
+ expect(line).not.toMatch(/make the first commit/i);
+ expect(line).not.toBe('no-commits-yet');
+ });
+
+ test('a reason this build does not know still renders as its raw token', async () => {
+ const { PausedReasonNotice, format } = await loadPausedReasonCopy();
+
+ expect(format('some-future-reason')).toBe('some-future-reason');
+
+ render(<PausedReasonNotice reason="some-future-reason" />);
+ expect(document.body.textContent).toBe('some-future-reason');
+ cleanup();
+ });
});
describe('SyncStatusBadge runtime behavior', () => {
@@ -439,6 +508,9 @@ describe('SyncStatusBadge runtime behavior', () => {
projectLocalSynced = true;
patches.length = 0;
worktree = emptyWorktree;
+ worktreeUnreadable = false;
+ worktreeStale = false;
+ worktreeLastReadAt = null;
triggered.length = 0;
triggerRejection = null;
});
@@ -508,7 +580,7 @@ describe('SyncStatusBadge runtime behavior', () => {
const copy =
'Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync.';
expect(screen.getByText(copy)).toBeTruthy();
- expect(screen.getByRole('status').textContent).toBe('');
+ expect(screen.getByTestId('sync-popover-status').textContent).toBe('');
expect(screen.getByTestId('sync-popover-pull').hasAttribute('disabled')).toBe(false);
act(() => {
status &&= { ...status, pausedReason: undefined };
@@ -910,7 +982,7 @@ describe('SyncStatusBadge runtime behavior', () => {
expect(screen.getByText(/signed out — sign in to resume syncing/)).toBeTruthy();
const signIn = screen.getByRole('button', { name: 'Sign in' });
expect(signIn).toBeTruthy();
- expect(within(screen.getByRole('status')).queryByRole('button')).toBeNull();
+ expect(within(screen.getByTestId('sync-popover-status')).queryByRole('button')).toBeNull();
});
test('a signed-out denial outranks the paused-reason line when the engine is parked', async () => {
@@ -926,7 +998,7 @@ describe('SyncStatusBadge runtime behavior', () => {
expect(screen.getByText(/signed out — sign in to resume syncing/)).toBeTruthy();
expect(screen.getByRole('button', { name: 'Sync status: Reconnect required' })).toBeTruthy();
expect(screen.queryByText('Reconnect required')).toBeNull();
- expect(within(screen.getByRole('status')).queryByRole('button')).toBeNull();
+ expect(within(screen.getByTestId('sync-popover-status')).queryByRole('button')).toBeNull();
});
test('a probe-401 renders the sign-in-again line and its button', async () => {
@@ -980,7 +1052,7 @@ describe('SyncStatusBadge runtime behavior', () => {
expect(screen.queryByRole('button', { name: 'Sign in' })).toBeNull();
expect(screen.queryByText('Reconnect required')).toBeNull();
expect(screen.getByRole('button', { name: 'Sync status: Repository not found' })).toBeTruthy();
- expect(screen.getByRole('status')).toBeTruthy();
+ expect(screen.getByTestId('sync-popover-status').getAttribute('role')).toBe('status');
});
test('a parked not-found error still names the account when a denied verdict is in hand', async () => {
@@ -1128,6 +1200,9 @@ describe('SyncStatusBadge working-tree listing', () => {
projectLocalSynced = true;
patches.length = 0;
worktree = emptyWorktree;
+ worktreeUnreadable = false;
+ worktreeStale = false;
+ worktreeLastReadAt = null;
triggered.length = 0;
triggerRejection = null;
});
@@ -1354,7 +1429,8 @@ describe('SyncStatusBadge working-tree listing', () => {
test('a tree that could not be read never claims to be clean', async () => {
status = { ...baseStatus, state: 'idle' };
projectLocalConfig = { autoSync: { mode: 'off' } };
- worktree = { ...emptyWorktree, readable: false };
+ worktree = emptyWorktree;
+ worktreeUnreadable = true;
await renderBadge();
await openPopover();
@@ -1666,3 +1742,270 @@ describe('SyncStatusBadge freshness line', () => {
expect(screen.queryByTestId('sync-popover-settings')).not.toBeNull();
});
});
+
+describe('SyncStatusBadge panel-read truthfulness', () => {
+ afterEach(() => {
+ cleanup();
+ status = null;
+ projectLocalConfig = { autoSync: { enabled: false } };
+ worktree = emptyWorktree;
+ worktreeUnreadable = false;
+ worktreeStale = false;
+ worktreeLastReadAt = null;
+ });
+
+ function badgeIsAmber(): boolean {
+ return (
+ screen.getByRole('button', { name: /Sync status:/ }).querySelector('.text-amber-500') !== null
+ );
+ }
+
+ test('a held index lock pauses in amber and names the lock in the popover', async () => {
+ status = {
+ ...baseStatus,
+ state: 'disabled',
+ syncEnabled: false,
+ syncMode: 'off',
+ pausedReason: 'git-index-locked',
+ } as GitSyncStatus;
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ await renderBadge();
+
+ expect(screen.getByRole('button', { name: 'Sync status: Sync paused' })).toBeTruthy();
+ expect(badgeIsAmber()).toBe(true);
+
+ await openPopover();
+ expect(screen.getByText(/\.git\/index\.lock/)).toBeTruthy();
+ });
+
+ test('a repository with no commits pauses in amber and says so in the popover', async () => {
+ status = {
+ ...baseStatus,
+ state: 'disabled',
+ syncEnabled: false,
+ syncMode: 'off',
+ pausedReason: 'no-commits-yet',
+ } as GitSyncStatus;
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ await renderBadge();
+
+ expect(screen.getByRole('button', { name: 'Sync status: Sync paused' })).toBeTruthy();
+ expect(badgeIsAmber()).toBe(true);
+
+ await openPopover();
+ expect(screen.getByText(/no commits yet/i)).toBeTruthy();
+ });
+
+ test('a held index lock outside Manual reports in the popover and leaves the badge neutral', async () => {
+ status = {
+ ...baseStatus,
+ state: 'idle',
+ syncEnabled: true,
+ syncMode: 'full',
+ pausedReason: 'git-index-locked',
+ } as GitSyncStatus;
+ projectLocalConfig = { autoSync: { mode: 'full' } };
+ await renderBadge();
+
+ expect(badgeIsAmber()).toBe(false);
+
+ await openPopover();
+ expect(screen.getByText(/\.git\/index\.lock/)).toBeTruthy();
+ });
+
+ test('a repository with no commits outside Manual reports in the popover and leaves the badge neutral', async () => {
+ status = {
+ ...baseStatus,
+ state: 'idle',
+ syncEnabled: true,
+ syncMode: 'full',
+ pausedReason: 'no-commits-yet',
+ } as GitSyncStatus;
+ projectLocalConfig = { autoSync: { mode: 'full' } };
+ await renderBadge();
+
+ expect(badgeIsAmber()).toBe(false);
+
+ await openPopover();
+ expect(screen.getByText(/no commits yet/i)).toBeTruthy();
+ });
+
+ test('the lock path is isolated from its sentence so an RTL locale cannot reorder it', async () => {
+ status = {
+ ...baseStatus,
+ state: 'disabled',
+ syncEnabled: false,
+ syncMode: 'off',
+ pausedReason: 'git-index-locked',
+ } as GitSyncStatus;
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.getByText('.git/index.lock').getAttribute('dir')).toBe('ltr');
+ });
+
+ test('the branch header goes away with the tree it describes', async () => {
+ status = { ...baseStatus, state: 'idle' };
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ worktree = { ...emptyWorktree };
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.getByTestId('worktree-branch').textContent).toContain('main → origin/main');
+
+ worktreeUnreadable = true;
+ await advanceStatus({ ...baseStatus, state: 'idle' });
+
+ expect(screen.getByTestId('worktree-unreadable')).toBeTruthy();
+ expect(screen.queryByTestId('worktree-branch')).toBeNull();
+ });
+
+ test('an unreadable working tree is reported without alarming the badge', async () => {
+ status = { ...baseStatus, state: 'idle' };
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ worktreeUnreadable = true;
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.getByTestId('worktree-unreadable')).toBeTruthy();
+ expect(badgeIsAmber()).toBe(false);
+ expect(screen.queryByRole('button', { name: /Sync paused/ })).toBeNull();
+ });
+
+ test('a first read that comes back unreadable says so instead of claiming it is still reading', async () => {
+ status = { ...baseStatus, state: 'idle' };
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ worktree = null;
+ worktreeUnreadable = true;
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.getByTestId('worktree-unreadable')).toBeTruthy();
+ expect(screen.queryByText(/Reading working tree/)).toBeNull();
+ });
+
+ test('the reading copy shows only while no verdict has arrived at all', async () => {
+ status = { ...baseStatus, state: 'idle' };
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ worktree = null;
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.getByText(/Reading working tree/)).toBeTruthy();
+ expect(screen.queryByTestId('worktree-unreadable')).toBeNull();
+ expect(screen.queryByTestId('worktree-stale')).toBeNull();
+ });
+
+ test('a failed read keeps the last good list and says when it was last read', async () => {
+ status = { ...baseStatus, state: 'idle' };
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ worktree = {
+ ...emptyWorktree,
+ notStaged: [{ path: 'docs/sync.mdx', code: 'M', syncScoped: true }],
+ };
+ worktreeStale = true;
+ worktreeLastReadAt = Date.now() - 2 * 60_000;
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.getByTestId('worktree-listing')).toBeTruthy();
+ expect(screen.getByTestId('worktree-stale').textContent).toMatch(/2m ago/);
+ expect(badgeIsAmber()).toBe(false);
+ });
+
+ test('an unreadable tree reaches a live region that was already mounted', async () => {
+ status = { ...baseStatus, state: 'idle' };
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ await renderBadge();
+ await openPopover();
+
+ const announcer = screen.getByTestId('worktree-announcer');
+ expect(announcer.getAttribute('aria-live')).toBe('polite');
+ expect(announcer.textContent).toBe('');
+
+ worktreeUnreadable = true;
+ await advanceStatus({ ...baseStatus, state: 'idle' });
+
+ expect(screen.getByTestId('worktree-announcer').textContent).toMatch(
+ /Couldn't read the working tree/,
+ );
+ });
+
+ test('the announced staleness sentence carries no time, so a tick cannot repeat it', async () => {
+ status = { ...baseStatus, state: 'idle' };
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ worktree = {
+ ...emptyWorktree,
+ notStaged: [{ path: 'docs/sync.mdx', code: 'M', syncScoped: true }],
+ };
+ worktreeStale = true;
+ worktreeLastReadAt = Date.now() - 2 * 60_000;
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.getByTestId('worktree-stale').textContent).toMatch(/2m ago/);
+ const announced = screen.getByTestId('worktree-announcer').textContent ?? '';
+ expect(announced).toMatch(/out of date/);
+ expect(announced).not.toMatch(/ago|just now/);
+ });
+
+ test('the staleness line ages while the popover stays open', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ status = { ...baseStatus, state: 'idle' };
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ worktree = {
+ ...emptyWorktree,
+ notStaged: [{ path: 'docs/sync.mdx', code: 'M', syncScoped: true }],
+ };
+ worktreeStale = true;
+ worktreeLastReadAt = Date.now();
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.getByTestId('worktree-stale').textContent).toMatch(/just now/);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3 * 60_000);
+ });
+
+ expect(screen.getByTestId('worktree-stale').textContent).toMatch(/3m ago/);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test('a read that never succeeded does not claim a last-read time', async () => {
+ status = { ...baseStatus, state: 'idle' };
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ worktreeStale = true;
+ worktreeLastReadAt = null;
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.queryByTestId('worktree-stale')).toBeNull();
+ });
+
+ test('the next successful read clears both the staleness line and the unreadable copy', async () => {
+ status = { ...baseStatus, state: 'idle' };
+ projectLocalConfig = { autoSync: { mode: 'off' } };
+ worktreeStale = true;
+ worktreeUnreadable = true;
+ worktreeLastReadAt = Date.now() - 2 * 60_000;
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.getByTestId('worktree-unreadable')).toBeTruthy();
+ expect(screen.queryByTestId('worktree-stale')).toBeNull();
+
+ worktreeStale = false;
+ worktreeUnreadable = false;
+ worktreeLastReadAt = Date.now();
+ await advanceStatus({ ...baseStatus, state: 'idle' });
+
+ expect(screen.queryByTestId('worktree-unreadable')).toBeNull();
+ expect(screen.queryByTestId('worktree-stale')).toBeNull();
+ expect(screen.getByText(/working tree clean/)).toBeTruthy();
+ });
+});
diff --git a/packages/app/src/components/SyncStatusBadge.tsx b/packages/app/src/components/SyncStatusBadge.tsx
index 33e856573..993ad2c5a 100644
--- a/packages/app/src/components/SyncStatusBadge.tsx
+++ b/packages/app/src/components/SyncStatusBadge.tsx
@@ -7,8 +7,10 @@ import {
isSyncMode,
type PushPermissionWire,
type SyncErrorCode,
+ type SyncPausedReason,
} from '@inkeep/open-knowledge-core';
-import { plural, t } from '@lingui/core/macro';
+import type { MessageDescriptor } from '@lingui/core';
+import { msg, plural, t } from '@lingui/core/macro';
import { Plural, Trans, useLingui } from '@lingui/react/macro';
import {
AlertTriangle,
@@ -74,18 +76,35 @@ function hashForOpenTarget(target: GitWorktreeOpenTarget): string {
return target.kind === 'doc' ? hashFromDocName(target.docName) : hashFromAssetPath(target.path);
}
-function formatRelativeCompact(iso: string): string {
- const diff = Date.now() - new Date(iso).getTime();
- if (diff < 60_000) return t`just now`;
+const STALENESS_TICK_MS = 30_000;
+
+type ReactiveTranslate = ReturnType<typeof useLingui>['t'];
+
+function formatRelativeSince(translate: ReactiveTranslate, at: number, now: number): string {
+ const diff = now - at;
+ if (diff < 60_000) return translate(msg`just now`);
if (diff < 3_600_000) {
const minutes = Math.floor(diff / 60_000);
- return t`${minutes}m ago`;
+ return translate(msg`${minutes}m ago`);
}
if (diff < 86_400_000) {
const hours = Math.floor(diff / 3_600_000);
- return t`${hours}h ago`;
+ return translate(msg`${hours}h ago`);
}
- return new Date(iso).toLocaleDateString();
+ return new Date(at).toLocaleDateString();
+}
+
+function formatRelativeCompact(translate: ReactiveTranslate, iso: string): string {
+ return formatRelativeSince(translate, new Date(iso).getTime(), Date.now());
+}
+
+function useNowTick(): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const id = setInterval(() => setNow(Date.now()), STALENESS_TICK_MS);
+ return () => clearInterval(id);
+ }, []);
+ return now;
}
function isFollowingMode(status: GitSyncStatus): boolean {
@@ -194,31 +213,67 @@ function stateLabel(status: GitSyncStatus): string {
}
}
-export function formatPausedReason(reason: string): string {
+const NODE_RENDERED_PAUSED_REASONS = [
+ 'git-index-locked',
+] as const satisfies readonly SyncPausedReason[];
+
+type NodeRenderedPausedReason = (typeof NODE_RENDERED_PAUSED_REASONS)[number];
+
+const PAUSED_REASON_MESSAGES: Record<SyncPausedReason, MessageDescriptor> = {
+ 'git-index-locked': msg`Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)`,
+ 'git-operation-in-progress': msg`Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync.`,
+ 'external-changes-pending': msg`Local changes overlap with incoming sync`,
+ 'dirty-tree': msg`Local changes blocked the merge`,
+ 'non-content-merge-failure': msg`Resolve conflict in your terminal`,
+ 'detached-head': msg`Detached HEAD — checkout a branch to resume`,
+ 'diverged-local-commits': msg`Local commits are keeping this copy from updating`,
+ 'auth-error': msg`Reconnect required`,
+ 'protected-branch': msg`Protected branch — cannot push`,
+ 'no-push-permission': msg`You don't have permission to push to this repo.`,
+ 'no-commits-yet': msg`This repository has no commits yet — reopen the project to create the first commit, then Push will work`,
+};
+
+function isKnownPausedReason(reason: string): reason is SyncPausedReason {
+ return Object.hasOwn(PAUSED_REASON_MESSAGES, reason);
+}
+
+export function formatPausedReason(translate: ReactiveTranslate, reason: string): string {
+ return isKnownPausedReason(reason) ? translate(PAUSED_REASON_MESSAGES[reason]) : reason;
+}
+
+function isNodeRenderedPausedReason(reason: string): reason is NodeRenderedPausedReason {
+ return (NODE_RENDERED_PAUSED_REASONS as readonly string[]).includes(reason);
+}
+
+function assertNeverPausedReasonNode(reason: never): never {
+ throw new Error(`Unhandled node-rendered paused reason: ${String(reason)}`);
+}
+
+function PausedReasonNode({ reason }: { reason: NodeRenderedPausedReason }) {
switch (reason) {
- case 'git-operation-in-progress':
- return t`Git syncing is paused because a Git operation or unresolved conflicts need attention. Your edits still save locally. Finish the operation or resolve the conflicts in your terminal, then retry sync.`;
- case 'external-changes-pending':
- return t`Local changes overlap with incoming sync`;
- case 'dirty-tree':
- return t`Local changes blocked the merge`;
- case 'non-content-merge-failure':
- return t`Resolve conflict in your terminal`;
- case 'detached-head':
- return t`Detached HEAD — checkout a branch to resume`;
- case 'diverged-local-commits':
- return t`Local commits are keeping this copy from updating`;
- case 'auth-error':
- return t`Reconnect required`;
- case 'protected-branch':
- return t`Protected branch — cannot push`;
- case 'no-push-permission':
- return t`You don't have permission to push to this repo.`;
+ case 'git-index-locked':
+ return (
+ <Trans>
+ Another program is using Git here — wait for it to finish, then sync again (it holds{' '}
+ <span dir="ltr" className="font-mono">
+ .git/index.lock
+ </span>
+ )
+ </Trans>
+ );
default:
- return reason;
+ return assertNeverPausedReasonNode(reason);
}
}
+export function PausedReasonNotice({ reason }: { reason: string }) {
+ const { t } = useLingui();
+ if (isNodeRenderedPausedReason(reason)) {
+ return <PausedReasonNode reason={reason} />;
+ }
+ return <>{formatPausedReason(t, reason)}</>;
+}
+
type PushPermissionDeniedIdentity = Pick<
Extract<PushPermissionWire, { checkStatus: 'denied' }>,
'resolvedLogin' | 'declaredLogin' | 'declaredSource'
@@ -744,31 +799,60 @@ function partitionByPushScope(worktree: GitWorktreeStatus): {
return { willPush, wontPush };
}
+function WorktreeStaleLine({ lastReadAt }: { lastReadAt: number }) {
+ const { t } = useLingui();
+ const now = useNowTick();
+ const staleRelative = formatRelativeSince(t, lastReadAt, now);
+ return (
+ <p className="text-2xs text-muted-foreground" data-testid="worktree-stale">
+ <Trans>This list may be out of date — last read {staleRelative}.</Trans>
+ </p>
+ );
+}
+
function WorktreeStatusSection({
status,
worktree,
loading,
+ unreadable,
+ stale,
+ lastReadAt,
}: {
status: GitSyncStatus;
worktree: GitWorktreeStatus | null;
loading: boolean;
+ unreadable: boolean;
+ stale: boolean;
+ lastReadAt: number | null;
}) {
const { willPush, wontPush } = worktree
? partitionByPushScope(worktree)
: { willPush: [], wontPush: [] };
const incoming = worktree?.incoming ?? [];
- const unreadable = worktree !== null && worktree.readable === false;
+ const { t } = useLingui();
+ const showStale = stale && !unreadable && worktree !== null && lastReadAt !== null;
const clean =
worktree !== null && willPush.length === 0 && wontPush.length === 0 && incoming.length === 0;
+ const announcement = unreadable
+ ? t`Couldn't read the working tree. Check the server logs.`
+ : showStale
+ ? t`This list may be out of date.`
+ : '';
return (
<div className="flex flex-col gap-2.5 border-t pt-3">
+ <div className="sr-only" role="status" aria-live="polite" data-testid="worktree-announcer">
+ {announcement}
+ </div>
<div className="flex items-baseline justify-between gap-2">
<SectionLabel id="worktree-status-label">
<Trans>Status</Trans>
</SectionLabel>
- {worktree && (worktree.branch || worktree.detached) && (
- <span className="min-w-0 truncate font-mono text-2xs text-muted-foreground">
+ {!unreadable && worktree && (worktree.branch || worktree.detached) && (
+ <span
+ className="min-w-0 truncate font-mono text-2xs text-muted-foreground"
+ data-testid="worktree-branch"
+ >
{worktree.detached ? (
<Trans>detached HEAD</Trans>
) : worktree.upstream ? (
@@ -787,14 +871,14 @@ function WorktreeStatusSection({
</div>
)}
- {loading ? (
- <p className="text-xs text-muted-foreground">
- <Trans>Reading working tree</Trans>
- </p>
- ) : unreadable ? (
+ {unreadable ? (
<p className="text-xs text-muted-foreground" data-testid="worktree-unreadable">
<Trans>Couldn't read the working tree. Check the server logs.</Trans>
</p>
+ ) : loading ? (
+ <p className="text-xs text-muted-foreground">
+ <Trans>Reading working tree</Trans>
+ </p>
) : clean ? (
<p className="text-xs text-muted-foreground">
<Trans>Nothing to commit — working tree clean.</Trans>
@@ -825,6 +909,8 @@ function WorktreeStatusSection({
</section>
)
)}
+
+ {showStale && lastReadAt !== null && <WorktreeStaleLine lastReadAt={lastReadAt} />}
</div>
);
}
@@ -839,9 +925,9 @@ function UpdatedLine({
combinedAt: string | null;
}) {
const { t } = useLingui();
- const pulled = pulledAt === null ? null : formatRelativeCompact(pulledAt);
- const pushed = pushedAt === null ? null : formatRelativeCompact(pushedAt);
- const updatedRelative = combinedAt === null ? null : formatRelativeCompact(combinedAt);
+ const pulled = pulledAt === null ? null : formatRelativeCompact(t, pulledAt);
+ const pushed = pushedAt === null ? null : formatRelativeCompact(t, pushedAt);
+ const updatedRelative = combinedAt === null ? null : formatRelativeCompact(t, combinedAt);
const label =
pulled !== null && pushed !== null
? t`Pulled ${pulled} · pushed ${pushed}`
@@ -900,7 +986,13 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
onModeSelect,
onConfirm,
} = useBadgeSyncControls(autoSync, status.ahead);
- const { status: worktree, loading: worktreeLoading } = useGitWorktreeStatus(true);
+ const {
+ status: worktree,
+ loading: worktreeLoading,
+ unreadable: worktreeUnreadable,
+ stale: worktreeStale,
+ lastReadAt: worktreeLastReadAt,
+ } = useGitWorktreeStatus(true);
const following = mode === 'follow';
const state = displayState(status);
@@ -1072,7 +1164,12 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
{}
{}
- <div role="status" aria-live="polite" className="flex flex-col gap-3.5 empty:sr-only">
+ <div
+ role="status"
+ aria-live="polite"
+ className="flex flex-col gap-3.5 empty:sr-only"
+ data-testid="sync-popover-status"
+ >
{computeSyncErrorLines(status).map((line) => (
<p key={line.key} className="text-xs text-destructive">
{line.direction === 'push' ? (
@@ -1123,7 +1220,9 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
) : blockingPaths.length > 0 ? (
<SyncBlockingChanges paths={blockingPaths} />
) : isParkedOnNotFoundAsIdentity(status) ? null : status.pausedReason ? (
- <p className="text-xs text-muted-foreground">{formatPausedReason(status.pausedReason)}</p>
+ <p className="text-xs text-muted-foreground">
+ <PausedReasonNotice reason={status.pausedReason} />
+ </p>
) : !following && genuineReadOnly && status.pushPermission?.checkStatus === 'denied' ? (
formatPushPermissionDenied(status.pushPermission.deniedReason, status.pushPermission).map(
(sentence) => (
@@ -1182,7 +1281,14 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
)}
{}
- <WorktreeStatusSection status={status} worktree={worktree} loading={worktreeLoading} />
+ <WorktreeStatusSection
+ status={status}
+ worktree={worktree}
+ loading={worktreeLoading}
+ unreadable={worktreeUnreadable}
+ stale={worktreeStale}
+ lastReadAt={worktreeLastReadAt}
+ />
{}
<div className="flex items-center justify-between gap-2">
diff --git a/packages/app/src/components/settings/SyncSection.tsx b/packages/app/src/components/settings/SyncSection.tsx
index 81b620855..c1ad76163 100644
--- a/packages/app/src/components/settings/SyncSection.tsx
+++ b/packages/app/src/components/settings/SyncSection.tsx
@@ -15,10 +15,10 @@ import { EnableSyncConfirmDialog } from '@/components/EnableSyncConfirmDialog';
import { PublishToGitHubDialog } from '@/components/PublishToGitHubDialog';
import {
formatDeniedIdentitySentences,
- formatPausedReason,
formatSyncFailureCode,
hasNotFoundAsIdentityError,
isParkedOnNotFoundAsIdentity,
+ PausedReasonNotice,
shouldOfferReconnect,
shouldOfferSignInAgain,
} from '@/components/SyncStatusBadge';
@@ -145,13 +145,11 @@ export function SyncSection() {
status?.pushPermission?.checkStatus === 'denied' &&
status.pushPermission.deniedReason === 'not-authenticated';
const parkedOnNotFound = isParkedOnNotFoundAsIdentity(status);
- const pausedNotice = !status?.pausedReason
- ? null
- : parkedOnNotFound
- ? formatSyncFailureCode('auth-not-found-as-identity')
- : isPushDenied
- ? null
- : formatPausedReason(status.pausedReason);
+ const pausedNotice = !status?.pausedReason ? null : parkedOnNotFound ? (
+ formatSyncFailureCode('auth-not-found-as-identity')
+ ) : isPushDenied ? null : (
+ <PausedReasonNotice reason={status.pausedReason} />
+ );
function onModeChange(next: string) {
if (!isSyncMode(next)) return;
diff --git a/packages/app/src/hooks/use-git-worktree-status.dom.test.tsx b/packages/app/src/hooks/use-git-worktree-status.dom.test.tsx
index 01afd9c6d..91d578711 100644
--- a/packages/app/src/hooks/use-git-worktree-status.dom.test.tsx
+++ b/packages/app/src/hooks/use-git-worktree-status.dom.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, renderHook, waitFor } from '@testing-library/react';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
const triggered: string[] = [];
@@ -99,7 +99,10 @@ describe('useGitWorktreeStatus single-flight', () => {
const respond = (index: number, body: unknown) => {
resolvers[index]?.({ ok: true, json: async () => body });
};
- return { fetchMock, resolvers, respond };
+ const respondWithHttpError = (index: number, status: number) => {
+ resolvers[index]?.({ ok: false, status, json: async () => ({}) });
+ };
+ return { fetchMock, resolvers, respond, respondWithHttpError };
}
test('collapses a burst of signals into one trailing re-run', async () => {
@@ -149,8 +152,9 @@ describe('useGitWorktreeStatus single-flight', () => {
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
respond(1, { staged: [], readable: false });
- await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(result.current.unreadable).toBe(true));
expect(result.current.status?.staged?.[0]?.path).toBe('real.md');
+ expect(fetchMock).toHaveBeenCalledTimes(2);
});
test('a server predating the readable field is still trusted', async () => {
@@ -164,3 +168,194 @@ describe('useGitWorktreeStatus single-flight', () => {
await waitFor(() => expect(result.current.status?.staged?.[0]?.path).toBe('old-server.md'));
});
});
+
+describe('useGitWorktreeStatus staleness', () => {
+ function deferredFetch() {
+ const resolvers: ((value: unknown) => void)[] = [];
+ const fetchMock = vi.fn(
+ () =>
+ new Promise((resolve) => {
+ resolvers.push(resolve);
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const respond = (index: number, body: unknown) => {
+ resolvers[index]?.({ ok: true, json: async () => body });
+ };
+ const respondWithHttpError = (index: number, status: number) => {
+ resolvers[index]?.({ ok: false, status, json: async () => ({}) });
+ };
+ return { fetchMock, respond, respondWithHttpError };
+ }
+
+ test('a request that never settles is abandoned so a later refresh can read again', async () => {
+ vi.useFakeTimers();
+ try {
+ const aborted: unknown[] = [];
+ const fetchMock = vi.fn((_url: string, init: { signal: AbortSignal }) => {
+ return new Promise((_resolve, reject) => {
+ init.signal.addEventListener('abort', () => {
+ aborted.push(init.signal.reason);
+ reject(init.signal.reason);
+ });
+ });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const useGitHook = await loadHook();
+ const { result } = renderHook(() => useGitHook(true));
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ signalSyncStatus();
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(15_000);
+ });
+
+ expect(aborted).toHaveLength(1);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(result.current.unreadable).toBe(true);
+ expect(result.current.loading).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test('an http error keeps the last good listing and reports it as possibly out of date', async () => {
+ const { fetchMock, respond, respondWithHttpError } = deferredFetch();
+ const useGitHook = await loadHook();
+ const { result } = renderHook(() => useGitHook(true));
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ respond(0, { staged: [{ path: 'real.md', code: 'M' }], readable: true });
+ await waitFor(() => expect(result.current.status?.staged?.[0]?.path).toBe('real.md'));
+ const firstReadAt = result.current.lastReadAt;
+ expect(firstReadAt).toBeTypeOf('number');
+ expect(result.current.stale).toBe(false);
+
+ signalSyncStatus();
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ respondWithHttpError(1, 500);
+
+ await waitFor(() => expect(result.current.stale).toBe(true));
+ expect(result.current.status?.staged?.[0]?.path).toBe('real.md');
+ expect(result.current.lastReadAt).toBe(firstReadAt);
+ });
+
+ test('a network error reports staleness without discarding the listing', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ staged: [], readable: true }) })
+ .mockRejectedValueOnce(new Error('offline'));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const useGitHook = await loadHook();
+ const { result } = renderHook(() => useGitHook(true));
+
+ await waitFor(() => expect(result.current.status).not.toBeNull());
+ signalSyncStatus();
+
+ await waitFor(() => expect(result.current.stale).toBe(true));
+ expect(result.current.status).not.toBeNull();
+ });
+
+ test('an unreadable tree is never also reported as a stale listing', async () => {
+ const { fetchMock, respond, respondWithHttpError } = deferredFetch();
+ const useGitHook = await loadHook();
+ const { result } = renderHook(() => useGitHook(true));
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ respond(0, { staged: [{ path: 'real.md', code: 'M' }], readable: true });
+ await waitFor(() => expect(result.current.status?.staged?.[0]?.path).toBe('real.md'));
+
+ signalSyncStatus();
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ respond(1, { staged: [], readable: false });
+ await waitFor(() => expect(result.current.unreadable).toBe(true));
+ expect(result.current.stale).toBe(false);
+
+ signalSyncStatus();
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));
+ respondWithHttpError(2, 403);
+ signalSyncStatus();
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(4));
+ expect(result.current.unreadable).toBe(true);
+ expect(result.current.stale).toBe(false);
+ });
+
+ test('a later readable response clears both the unreadable and the stale signals', async () => {
+ const { fetchMock, respond, respondWithHttpError } = deferredFetch();
+ const useGitHook = await loadHook();
+ const { result } = renderHook(() => useGitHook(true));
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ respond(0, { staged: [{ path: 'real.md', code: 'M' }], readable: true });
+ await waitFor(() => expect(result.current.status?.staged?.[0]?.path).toBe('real.md'));
+
+ signalSyncStatus();
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ respondWithHttpError(1, 403);
+ await waitFor(() => expect(result.current.stale).toBe(true));
+
+ signalSyncStatus();
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));
+ respond(2, { staged: [], readable: false });
+ await waitFor(() => expect(result.current.unreadable).toBe(true));
+ expect(result.current.stale).toBe(false);
+
+ signalSyncStatus();
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(4));
+ respond(3, { staged: [{ path: 'fresh.md', code: 'M' }], readable: true });
+
+ await waitFor(() => expect(result.current.status?.staged?.[0]?.path).toBe('fresh.md'));
+ expect(result.current.unreadable).toBe(false);
+ expect(result.current.stale).toBe(false);
+ expect(result.current.lastReadAt).toBeTypeOf('number');
+ });
+
+ test('a first read that fails outright stops claiming the tree is still being read', async () => {
+ const { fetchMock, respondWithHttpError } = deferredFetch();
+ const useGitHook = await loadHook();
+ const { result } = renderHook(() => useGitHook(true));
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ expect(result.current.loading).toBe(true);
+ respondWithHttpError(0, 500);
+
+ await waitFor(() => expect(result.current.unreadable).toBe(true));
+ expect(result.current.loading).toBe(false);
+ expect(result.current.status).toBeNull();
+ expect(result.current.stale).toBe(false);
+ });
+
+ test('a cold start that fails and then succeeds drops the unreadable verdict', async () => {
+ const { fetchMock, respond, respondWithHttpError } = deferredFetch();
+ const useGitHook = await loadHook();
+ const { result } = renderHook(() => useGitHook(true));
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ respondWithHttpError(0, 500);
+ await waitFor(() => expect(result.current.unreadable).toBe(true));
+
+ signalSyncStatus();
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ respond(1, { staged: [{ path: 'fresh.md', code: 'M' }], readable: true });
+
+ await waitFor(() => expect(result.current.status?.staged?.[0]?.path).toBe('fresh.md'));
+ expect(result.current.unreadable).toBe(false);
+ expect(result.current.loading).toBe(false);
+ });
+
+ test('the first read still reports loading until a listing arrives', async () => {
+ const { fetchMock, respond } = deferredFetch();
+ const useGitHook = await loadHook();
+ const { result } = renderHook(() => useGitHook(true));
+
+ expect(result.current.loading).toBe(true);
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ respond(0, { staged: [], readable: true });
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ });
+});
diff --git a/packages/app/src/hooks/use-git-worktree-status.ts b/packages/app/src/hooks/use-git-worktree-status.ts
index ac14eb117..4f46a4085 100644
--- a/packages/app/src/hooks/use-git-worktree-status.ts
+++ b/packages/app/src/hooks/use-git-worktree-status.ts
@@ -7,6 +7,8 @@ export type GitWorktreeStatus = GitWorktreeStatusSuccess;
const WORKTREE_POLL_MS = 5_000;
+const WORKTREE_READ_TIMEOUT_MS = 15_000;
+
const FETCH_THROTTLE_MS = 30_000;
let lastFetchAt = 0;
@@ -20,21 +22,55 @@ function maybeFetch(): void {
});
}
-async function fetchWorktreeStatus(): Promise<GitWorktreeStatus | null> {
+type WorktreeReadFailure = 'http' | 'aborted' | 'network';
+
+type WorktreeRead =
+ | { kind: 'ok'; status: GitWorktreeStatus }
+ | { kind: 'unreadable' }
+ | { kind: 'failed'; reason: WorktreeReadFailure };
+
+async function fetchWorktreeStatus(signal: AbortSignal): Promise<WorktreeRead> {
try {
- const res = await fetch('/api/git/worktree-status');
- if (!res.ok) return null;
- return (await res.json()) as GitWorktreeStatus;
- } catch {
- return null;
+ const res = await fetch('/api/git/worktree-status', { signal });
+ if (!res.ok) {
+ console.warn('[sync] worktree status read failed: http', res.status);
+ return { kind: 'failed', reason: 'http' };
+ }
+ const body = (await res.json()) as GitWorktreeStatus;
+ if (body.readable === false) return { kind: 'unreadable' };
+ return { kind: 'ok', status: body };
+ } catch (err) {
+ if (signal.aborted) return { kind: 'failed', reason: 'aborted' };
+ console.warn(
+ '[sync] worktree status read failed: network',
+ err instanceof Error ? err.message : err,
+ );
+ return { kind: 'failed', reason: 'network' };
}
}
+type WorktreeReadState = {
+ status: GitWorktreeStatus | null;
+ unreadable: boolean;
+ stale: boolean;
+ lastReadAt: number | null;
+};
+
+const INITIAL_READ: WorktreeReadState = {
+ status: null,
+ unreadable: false,
+ stale: false,
+ lastReadAt: null,
+};
+
export function useGitWorktreeStatus(enabled: boolean): {
status: GitWorktreeStatus | null;
loading: boolean;
+ unreadable: boolean;
+ stale: boolean;
+ lastReadAt: number | null;
} {
- const [status, setStatus] = useState<GitWorktreeStatus | null>(null);
+ const [read, setRead] = useState<WorktreeReadState>(INITIAL_READ);
useEffect(() => {
if (!enabled) return;
@@ -42,20 +78,49 @@ export function useGitWorktreeStatus(enabled: boolean): {
let inFlight = false;
let rerunQueued = false;
+ let activeController: AbortController | null = null;
function refresh() {
if (inFlight) {
rerunQueued = true;
return;
}
inFlight = true;
- void fetchWorktreeStatus().then((next) => {
- inFlight = false;
- if (!cancelled && next && next.readable !== false) setStatus(next);
- if (rerunQueued && !cancelled) {
- rerunQueued = false;
- refresh();
- }
- });
+ const controller = new AbortController();
+ activeController = controller;
+ const timeout = setTimeout(() => controller.abort(), WORKTREE_READ_TIMEOUT_MS);
+ void fetchWorktreeStatus(controller.signal)
+ .then((result) => {
+ if (cancelled) return;
+ if (result.kind === 'ok') {
+ setRead({
+ status: result.status,
+ unreadable: false,
+ stale: false,
+ lastReadAt: Date.now(),
+ });
+ return;
+ }
+ if (result.kind === 'unreadable') {
+ setRead((prev) => ({ ...prev, unreadable: true, stale: false }));
+ return;
+ }
+ setRead((prev) => {
+ if (prev.status === null) {
+ return prev.unreadable ? prev : { ...prev, unreadable: true, stale: false };
+ }
+ if (prev.unreadable) return prev;
+ return prev.stale ? prev : { ...prev, stale: true };
+ });
+ })
+ .finally(() => {
+ clearTimeout(timeout);
+ if (activeController === controller) activeController = null;
+ inFlight = false;
+ if (rerunQueued && !cancelled) {
+ rerunQueued = false;
+ refresh();
+ }
+ });
}
refresh();
@@ -70,8 +135,15 @@ export function useGitWorktreeStatus(enabled: boolean): {
cancelled = true;
clearInterval(interval);
unsubscribe();
+ activeController?.abort();
};
}, [enabled]);
- return { status, loading: enabled && status === null };
+ return {
+ status: read.status,
+ loading: enabled && read.status === null && !read.unreadable,
+ unreadable: read.unreadable,
+ stale: read.stale,
+ lastReadAt: read.lastReadAt,
+ };
}
diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.json
index 69e6a3d82..f828414e0 100644
--- a/packages/app/src/locales/ar/messages.json
+++ b/packages/app/src/locales/ar/messages.json
@@ -45,6 +45,9 @@
"-WeuHF": ["إزالة الرسالة من الطابور"],
"-X1eoK": ["تم فحص تكاملات OpenKnowledge."],
"-YV1Uo": ["النمط ", ["patternNumber"]],
+ "-ZVU5v": [
+ "لا يحتوي هذا المستودع على أي إيداعات بعد — أعد فتح المشروع لإنشاء أول إيداع، وعندها سيعمل الدفع"
+ ],
"-bFGPF": ["التغيير التالي"],
"-dNlfM": ["تم التراجع عن آخر تعديل في ", ["docName"]],
"-g6KIS": ["رابط غير معروف"],
@@ -2570,6 +2573,9 @@
"QWdKwH": ["نقل"],
"QYTOaN": ["يمكنك تغيير هذا لاحقًا من <0>الإعدادات ← المزامنة</0>."],
"QYfQdv": ["واجهة ", ["displayName"], " السطرية"],
+ "Qca--K": [
+ "برنامج آخر يستخدم Git هنا — انتظر حتى ينتهي، ثم أعد المزامنة (يحتجز <0>.git/index.lock</0>)"
+ ],
"QcpeeE": ["الانتقال إلى ", ["docName"]],
"Qe47G0": [
["componentLabel"],
@@ -3539,6 +3545,7 @@
"_IX_7x": ["أخرى"],
"_IfSZn": ["توجد سمة محفوظة بهذا الاسم بالفعل."],
"_JOGC0": ["إرسال ملاحظات…"],
+ "_LK4d6": ["قد تكون هذه القائمة قديمة."],
"_LczaQ": ["مرفوض — ", ["optionName"]],
"_NWEid": ["ابحث في ملفات المخططات بالمسار"],
"_O7dJS": ["نسخة مختلفة هنا — انقر للمقارنة والحل"],
@@ -4005,6 +4012,7 @@
"dw_dUJ": ["فشل تكرار المسار"],
"dx-TwN": ["تجري مراجعة المشروع"],
"dyfMJN": ["تم نسخ الرمز"],
+ "e-pP6g": ["قد تكون هذه القائمة قديمة — آخر قراءة ", ["staleRelative"], "."],
"e0NrBM": ["المشروع"],
"e1Rn_k": ["فتح المجلد الحاوي"],
"e1hptq": ["ضمّن مقطع فيديو بعناصر تحكم مشغّل أصلية."],
@@ -5466,6 +5474,9 @@
"sKHiNR": [["count"], " للخلف"],
"sNeKjP": ["فشل تخزين الرمز — أعد المحاولة"],
"sOafXU": ["تحرير وإرسال مرة أخرى"],
+ "sOcMdy": [
+ "برنامج آخر يستخدم Git هنا — انتظر حتى ينتهي، ثم أعد المزامنة (يحتجز .git/index.lock)"
+ ],
"sOxZaS": ["فشل تحميل الرسم البياني"],
"sQoLn0": ["إنهاء"],
"sR0I-f": ["طيّ كل الملفات"],
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index d5599a2da..076ffc72b 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -1971,6 +1971,14 @@ msgstr "و{remaining} أخرى"
msgid "and more"
msgstr "والمزيد"
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr "برنامج آخر يستخدم Git هنا — انتظر حتى ينتهي، ثم أعد المزامنة (يحتجز .git/index.lock)"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr "برنامج آخر يستخدم Git هنا — انتظر حتى ينتهي، ثم أعد المزامنة (يحتجز <0>.git/index.lock</0>)"
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr "توجد عملية مزامنة أخرى قيد التنفيذ. أعد المحاولة بعد قليل."
@@ -14540,6 +14548,14 @@ msgstr "هذا ليس إصدارًا مدعومًا من Slidev."
msgid "this item"
msgstr "هذا العنصر"
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr "قد تكون هذه القائمة قديمة — آخر قراءة {staleRelative}."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr "قد تكون هذه القائمة قديمة."
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr "يبدو هذا جذر قرص (مثل C:\\). سيفحص البناء هنا قرصًا كاملًا."
@@ -14686,6 +14702,10 @@ msgstr "يزيل هذا إعدادات OpenKnowledge وتكاملاته من ج
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr "هذا التقرير في طريقه بالفعل. ستظهر نتيجته في سجل تقارير العلل."
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr "لا يحتوي هذا المستودع على أي إيداعات بعد — أعد فتح المشروع لإنشاء أول إيداع، وعندها سيعمل الدفع"
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr "لم يعد هذا الطلب نشطًا."
diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.json
index 65d2a2f4a..c194c4b67 100644
--- a/packages/app/src/locales/bn/messages.json
+++ b/packages/app/src/locales/bn/messages.json
@@ -21,6 +21,9 @@
"-WeuHF": ["সারিতে থাকা বার্তা সরান"],
"-X1eoK": ["OpenKnowledge ইন্টিগ্রেশন যাচাই করা হয়েছে।"],
"-YV1Uo": ["প্যাটার্ন ", ["patternNumber"]],
+ "-ZVU5v": [
+ "এই রিপোজিটরিতে এখনও কোনো কমিট নেই — প্রথম কমিটটি তৈরি করতে প্রকল্পটি আবার খুলুন, তারপর পাঠান কাজ করবে"
+ ],
"-bFGPF": ["পরবর্তী পরিবর্তন"],
"-dNlfM": [["docName"], "-এর শেষ সম্পাদনাটি পূর্বাবস্থায় ফেরানো হয়েছে"],
"-g6KIS": ["অচেনা লিংক"],
@@ -2182,6 +2185,9 @@
"QWdKwH": ["সরান"],
"QYTOaN": ["আপনি এটি পরে <0>Settings → Sync</0>-এ বদলাতে পারেন।"],
"QYfQdv": [["displayName"], " CLI"],
+ "Qca--K": [
+ "অন্য একটি প্রোগ্রাম এখানে Git ব্যবহার করছে — সেটি শেষ হওয়া পর্যন্ত অপেক্ষা করুন, তারপর আবার সিঙ্ক করুন (এটি <0>.git/index.lock</0> ধরে রেখেছে)"
+ ],
"QcpeeE": [["docName"], "-এ যান"],
"Qe47G0": [
["componentLabel"],
@@ -2991,6 +2997,7 @@
"_IX_7x": ["অন্যান্য"],
"_IfSZn": ["এই নামে ইতিমধ্যেই একটি সংরক্ষিত থিম আছে।"],
"_JOGC0": ["মতামত পাঠান…"],
+ "_LK4d6": ["এই তালিকা পুরোনো হতে পারে।"],
"_LczaQ": ["প্রত্যাখ্যাত — ", ["optionName"]],
"_NWEid": ["পথ দিয়ে স্কিমা ফাইল খুঁজুন"],
"_O7dJS": ["এখানে ভিন্ন সংস্করণ — তুলনা করে মীমাংসা করতে ক্লিক করুন"],
@@ -3359,6 +3366,7 @@
"dw_dUJ": ["পথের প্রতিলিপি করতে ব্যর্থ"],
"dx-TwN": ["প্রকল্প নিরীক্ষা চালানো হচ্ছে"],
"dyfMJN": ["কোড কপি হয়েছে"],
+ "e-pP6g": ["এই তালিকা পুরোনো হতে পারে — শেষ পড়া হয়েছে ", ["staleRelative"], "।"],
"e0NrBM": ["প্রকল্প"],
"e1Rn_k": ["যে ফোল্ডারে আছে সেটি খুলুন"],
"e1hptq": ["নিজস্ব প্লেয়ার নিয়ন্ত্রণসহ একটি ভিডিও এমবেড করুন।"],
@@ -4643,6 +4651,9 @@
"sKHiNR": [["count"], " পিছিয়ে"],
"sNeKjP": ["টোকেন সংরক্ষণ করতে ব্যর্থ — আবার চেষ্টা করুন"],
"sOafXU": ["সম্পাদনা করে আবার পাঠান"],
+ "sOcMdy": [
+ "অন্য একটি প্রোগ্রাম এখানে Git ব্যবহার করছে — সেটি শেষ হওয়া পর্যন্ত অপেক্ষা করুন, তারপর আবার সিঙ্ক করুন (এটি .git/index.lock ধরে রেখেছে)"
+ ],
"sOxZaS": ["গ্রাফ লোড করতে ব্যর্থ"],
"sQoLn0": ["প্রস্থান"],
"sR0I-f": ["সব ফাইল গুটিয়ে নিন"],
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index b29b4776c..e2c3c770f 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -1967,6 +1967,14 @@ msgstr "এবং আরও {remaining}টি"
msgid "and more"
msgstr "এবং আরও"
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr "অন্য একটি প্রোগ্রাম এখানে Git ব্যবহার করছে — সেটি শেষ হওয়া পর্যন্ত অপেক্ষা করুন, তারপর আবার সিঙ্ক করুন (এটি .git/index.lock ধরে রেখেছে)"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr "অন্য একটি প্রোগ্রাম এখানে Git ব্যবহার করছে — সেটি শেষ হওয়া পর্যন্ত অপেক্ষা করুন, তারপর আবার সিঙ্ক করুন (এটি <0>.git/index.lock</0> ধরে রেখেছে)"
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr "আরেকটি সিঙ্ক কাজ চলছে। একটু পরে আবার চেষ্টা করুন।"
@@ -14536,6 +14544,14 @@ msgstr "এটি Slidev-এর সমর্থিত সংস্করণ ন
msgid "this item"
msgstr "এই আইটেমটি"
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr "এই তালিকা পুরোনো হতে পারে — শেষ পড়া হয়েছে {staleRelative}।"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr "এই তালিকা পুরোনো হতে পারে।"
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr "এটি একটি ড্রাইভের রুট মনে হচ্ছে (যেমন C:\\)। এখানে কাঠামো গড়লে পুরো ড্রাইভ স্ক্যান হবে।"
@@ -14682,6 +14698,10 @@ msgstr "এটি আপনার Mac থেকে এবং নিচে আপ
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr "এই রিপোর্ট ইতিমধ্যেই পথে আছে। এর ফলাফল বাগ রিপোর্টের ইতিহাসে দেখা যাবে।"
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr "এই রিপোজিটরিতে এখনও কোনো কমিট নেই — প্রথম কমিটটি তৈরি করতে প্রকল্পটি আবার খুলুন, তারপর পাঠান কাজ করবে"
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr "এই অনুরোধটি আর সক্রিয় নয়।"
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index dd27d1e39..884c58957 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -25,6 +25,9 @@
"-WeuHF": ["Remove queued message"],
"-X1eoK": ["OpenKnowledge integrations checked."],
"-YV1Uo": ["Pattern ", ["patternNumber"]],
+ "-ZVU5v": [
+ "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+ ],
"-bFGPF": ["Next change"],
"-dNlfM": ["Undid the last edit on ", ["docName"]],
"-g6KIS": ["Unrecognized link"],
@@ -2252,6 +2255,9 @@
"QWdKwH": ["Move"],
"QYTOaN": ["You can change this later in <0>Settings → Sync</0>."],
"QYfQdv": [["displayName"], " CLI"],
+ "Qca--K": [
+ "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+ ],
"QcpeeE": ["Navigate to ", ["docName"]],
"Qe47G0": [
["componentLabel"],
@@ -3067,6 +3073,7 @@
"_IX_7x": ["Other"],
"_IfSZn": ["A saved theme already uses this name."],
"_JOGC0": ["Send feedback…"],
+ "_LK4d6": ["This list may be out of date."],
"_LczaQ": ["Denied — ", ["optionName"]],
"_NWEid": ["Search schema files by path"],
"_O7dJS": ["Different version here — click to compare and resolve"],
@@ -3463,6 +3470,7 @@
"dw_dUJ": ["Failed to duplicate path"],
"dx-TwN": ["Running project audit"],
"dyfMJN": ["Code copied"],
+ "e-pP6g": ["This list may be out of date — last read ", ["staleRelative"], "."],
"e0NrBM": ["Project"],
"e1Rn_k": ["Open containing folder"],
"e1hptq": ["Embed a video with native player controls."],
@@ -4810,6 +4818,9 @@
"sKHiNR": [["count"], " behind"],
"sNeKjP": ["Failed to store the token — try again"],
"sOafXU": ["Edit and send again"],
+ "sOcMdy": [
+ "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+ ],
"sOxZaS": ["Failed to load graph"],
"sQoLn0": ["Quit"],
"sR0I-f": ["Collapse all files"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index ecde63b94..756bd25ac 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -1971,6 +1971,14 @@ msgstr "and {remaining} more"
msgid "and more"
msgstr "and more"
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr "Another sync operation is in progress. Try again in a moment."
@@ -14540,6 +14548,14 @@ msgstr "This isn't a supported version of Slidev."
msgid "this item"
msgstr "this item"
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr "This list may be out of date — last read {staleRelative}."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr "This list may be out of date."
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
@@ -14686,6 +14702,10 @@ msgstr "This removes OpenKnowledge’s settings and integrations from your Mac a
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr "This report is already on its way. Its result will appear in your bug report history."
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr "This request is no longer active."
diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.json
index d7c93e429..ebbb76ca0 100644
--- a/packages/app/src/locales/es/messages.json
+++ b/packages/app/src/locales/es/messages.json
@@ -35,6 +35,9 @@
"-WeuHF": ["Quitar el mensaje en cola"],
"-X1eoK": ["Se comprobaron las integraciones de OpenKnowledge."],
"-YV1Uo": ["Patrón ", ["patternNumber"]],
+ "-ZVU5v": [
+ "Este repositorio aún no tiene commits: vuelve a abrir el proyecto para crear el primer commit y entonces Push funcionará"
+ ],
"-bFGPF": ["Cambio siguiente"],
"-dNlfM": ["Se deshizo la última edición en ", ["docName"]],
"-g6KIS": ["Enlace no reconocido"],
@@ -2599,6 +2602,9 @@
"QWdKwH": ["Mover"],
"QYTOaN": ["Puedes cambiarlo más adelante en <0>Ajustes → Sincronización</0>."],
"QYfQdv": ["CLI de ", ["displayName"]],
+ "Qca--K": [
+ "Otro programa está usando Git aquí: espera a que termine y vuelve a sincronizar (está reteniendo <0>.git/index.lock</0>)"
+ ],
"QcpeeE": ["Ir a ", ["docName"]],
"Qe47G0": [
["componentLabel"],
@@ -3560,6 +3566,7 @@
"_IX_7x": ["Otro"],
"_IfSZn": ["Ya existe un tema guardado con este nombre."],
"_JOGC0": ["Enviar comentarios…"],
+ "_LK4d6": ["Puede que esta lista esté desactualizada."],
"_LczaQ": ["Denegado — ", ["optionName"]],
"_NWEid": ["Busca archivos de esquema por ruta"],
"_O7dJS": ["Aquí hay otra versión: haz clic para compararla y resolverla"],
@@ -4024,6 +4031,11 @@
"dw_dUJ": ["No se pudo duplicar la ruta"],
"dx-TwN": ["Ejecutando la auditoría del proyecto"],
"dyfMJN": ["Código copiado"],
+ "e-pP6g": [
+ "Puede que esta lista esté desactualizada; última lectura: ",
+ ["staleRelative"],
+ "."
+ ],
"e0NrBM": ["Proyecto"],
"e1Rn_k": ["Abrir la carpeta contenedora"],
"e1hptq": ["Incrusta un vídeo con los controles nativos del reproductor."],
@@ -5546,6 +5558,9 @@
"sKHiNR": [["count"], " por detrás"],
"sNeKjP": ["No se pudo guardar el token: inténtalo de nuevo"],
"sOafXU": ["Editar y enviar de nuevo"],
+ "sOcMdy": [
+ "Otro programa está usando Git aquí: espera a que termine y vuelve a sincronizar (está reteniendo .git/index.lock)"
+ ],
"sOxZaS": ["No se pudo cargar el grafo"],
"sQoLn0": ["Salir"],
"sR0I-f": ["Contraer todos los archivos"],
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index 4792fe24a..2201ec104 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -1971,6 +1971,14 @@ msgstr "y {remaining} más"
msgid "and more"
msgstr "y más"
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr "Otro programa está usando Git aquí: espera a que termine y vuelve a sincronizar (está reteniendo .git/index.lock)"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr "Otro programa está usando Git aquí: espera a que termine y vuelve a sincronizar (está reteniendo <0>.git/index.lock</0>)"
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr "Hay otra operación de sincronización en curso. Inténtalo de nuevo en un momento."
@@ -14540,6 +14548,14 @@ msgstr "Esta no es una versión compatible de Slidev."
msgid "this item"
msgstr "este elemento"
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr "Puede que esta lista esté desactualizada; última lectura: {staleRelative}."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr "Puede que esta lista esté desactualizada."
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr "Esto parece la raíz de una unidad (p. ej. C:\\). Preparar el proyecto aquí analizará una unidad entera."
@@ -14686,6 +14702,10 @@ msgstr "Esto quita de tu Mac los ajustes y las integraciones de OpenKnowledge, y
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr "Este informe ya va en camino. Su resultado aparecerá en el historial de informes de error."
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr "Este repositorio aún no tiene commits: vuelve a abrir el proyecto para crear el primer commit y entonces Push funcionará"
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr "Esta solicitud ya no está activa."
diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.json
index d54d7cb6c..1a9004337 100644
--- a/packages/app/src/locales/fr/messages.json
+++ b/packages/app/src/locales/fr/messages.json
@@ -35,6 +35,9 @@
"-WeuHF": ["Retirer le message en file d'attente"],
"-X1eoK": ["Intégrations OpenKnowledge vérifiées."],
"-YV1Uo": ["Motif ", ["patternNumber"]],
+ "-ZVU5v": [
+ "Ce dépôt ne contient encore aucun commit — rouvrez le projet pour créer le premier commit, puis Pousser fonctionnera"
+ ],
"-bFGPF": ["Modification suivante"],
"-dNlfM": ["Dernière modification annulée sur ", ["docName"]],
"-g6KIS": ["Lien non reconnu"],
@@ -2638,6 +2641,9 @@
"QWdKwH": ["Déplacer"],
"QYTOaN": ["Vous pourrez changer cela plus tard dans <0>Paramètres → Synchronisation</0>."],
"QYfQdv": ["CLI ", ["displayName"]],
+ "Qca--K": [
+ "Un autre programme utilise Git ici — attendez qu'il termine, puis relancez la synchronisation (il retient <0>.git/index.lock</0>)"
+ ],
"QcpeeE": ["Aller à ", ["docName"]],
"Qe47G0": [
["componentLabel"],
@@ -3607,6 +3613,7 @@
"_IX_7x": ["Autre"],
"_IfSZn": ["Un thème enregistré utilise déjà ce nom."],
"_JOGC0": ["Envoyer un retour…"],
+ "_LK4d6": ["Cette liste n'est peut-être pas à jour."],
"_LczaQ": ["Refusé — ", ["optionName"]],
"_NWEid": ["Rechercher des fichiers de schéma par chemin"],
"_O7dJS": ["Version différente ici — cliquez pour comparer et résoudre"],
@@ -4073,6 +4080,11 @@
"dw_dUJ": ["Échec de la duplication du chemin"],
"dx-TwN": ["Audit du projet en cours"],
"dyfMJN": ["Code copié"],
+ "e-pP6g": [
+ "Cette liste n'est peut-être pas à jour — dernière lecture ",
+ ["staleRelative"],
+ "."
+ ],
"e0NrBM": ["Projet"],
"e1Rn_k": ["Ouvrir le dossier contenant"],
"e1hptq": ["Intègre une vidéo avec les contrôles natifs du lecteur."],
@@ -5613,6 +5625,9 @@
"sKHiNR": [["count"], " en retard"],
"sNeKjP": ["Échec de l'enregistrement du jeton — réessayez"],
"sOafXU": ["Modifier et renvoyer"],
+ "sOcMdy": [
+ "Un autre programme utilise Git ici — attendez qu'il termine, puis relancez la synchronisation (il retient .git/index.lock)"
+ ],
"sOxZaS": ["Échec du chargement du graphe"],
"sQoLn0": ["Quitter"],
"sR0I-f": ["Réduire tous les fichiers"],
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index 6928805b4..db529afe7 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -1971,6 +1971,14 @@ msgstr "et {remaining} de plus"
msgid "and more"
msgstr "et plus encore"
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr "Un autre programme utilise Git ici — attendez qu'il termine, puis relancez la synchronisation (il retient .git/index.lock)"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr "Un autre programme utilise Git ici — attendez qu'il termine, puis relancez la synchronisation (il retient <0>.git/index.lock</0>)"
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr "Une autre opération de synchronisation est en cours. Réessayez dans un instant."
@@ -14540,6 +14548,14 @@ msgstr "Cette version de Slidev n'est pas prise en charge."
msgid "this item"
msgstr "cet élément"
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr "Cette liste n'est peut-être pas à jour — dernière lecture {staleRelative}."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr "Cette liste n'est peut-être pas à jour."
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr "Cela ressemble à la racine d'un disque (par ex. C:\\). Créer un projet ici analysera tout le disque."
@@ -14686,6 +14702,10 @@ msgstr "Ceci retire les paramètres et les intégrations d'OpenKnowledge de votr
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr "Ce rapport est déjà en route. Son résultat apparaîtra dans l'historique des rapports de bug."
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr "Ce dépôt ne contient encore aucun commit — rouvrez le projet pour créer le premier commit, puis Pousser fonctionnera"
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr "Cette requête n'est plus active."
diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.json
index 7524daea9..f0e1feba4 100644
--- a/packages/app/src/locales/hi/messages.json
+++ b/packages/app/src/locales/hi/messages.json
@@ -25,6 +25,9 @@
"-WeuHF": ["कतार में लगा संदेश हटाएँ"],
"-X1eoK": ["OpenKnowledge इंटीग्रेशन जाँच लिए गए।"],
"-YV1Uo": ["पैटर्न ", ["patternNumber"]],
+ "-ZVU5v": [
+ "इस रिपॉज़िटरी में अभी कोई कमिट नहीं है — पहला कमिट बनाने के लिए प्रोजेक्ट दोबारा खोलें, फिर भेजें काम करेगा"
+ ],
"-bFGPF": ["अगला बदलाव"],
"-dNlfM": [["docName"], " पर आख़िरी संपादन पूर्ववत किया गया"],
"-g6KIS": ["अपरिचित लिंक"],
@@ -2185,6 +2188,9 @@
"QWdKwH": ["हिलाएँ"],
"QYTOaN": ["आप इसे बाद में <0>Settings → Sync</0> में बदल सकते हैं।"],
"QYfQdv": [["displayName"], " CLI"],
+ "Qca--K": [
+ "कोई दूसरा प्रोग्राम यहाँ Git का उपयोग कर रहा है — उसके पूरा होने की प्रतीक्षा करें, फिर दोबारा सिंक करें (वह <0>.git/index.lock</0> रोके हुए है)"
+ ],
"QcpeeE": [["docName"], " पर जाएँ"],
"Qe47G0": [
["componentLabel"],
@@ -2984,6 +2990,7 @@
"_IX_7x": ["अन्य"],
"_IfSZn": ["एक सहेजी गई थीम पहले से इस नाम का उपयोग कर रही है।"],
"_JOGC0": ["प्रतिक्रिया भेजें…"],
+ "_LK4d6": ["यह सूची पुरानी हो सकती है।"],
"_LczaQ": ["अस्वीकृत — ", ["optionName"]],
"_NWEid": ["स्कीमा फ़ाइलें पथ से खोजें"],
"_O7dJS": ["यहाँ अलग संस्करण — तुलना करने और सुलझाने के लिए क्लिक करें"],
@@ -3353,6 +3360,7 @@
"dw_dUJ": ["पथ की नकल बनाने में विफल"],
"dx-TwN": ["प्रोजेक्ट ऑडिट चलाया जा रहा है"],
"dyfMJN": ["कोड कॉपी हो गया"],
+ "e-pP6g": ["यह सूची पुरानी हो सकती है — पिछली बार पढ़ा गया ", ["staleRelative"], "।"],
"e0NrBM": ["प्रोजेक्ट"],
"e1Rn_k": ["जिसमें है वह फ़ोल्डर खोलें"],
"e1hptq": ["मूल प्लेयर नियंत्रणों के साथ एक वीडियो एम्बेड करें।"],
@@ -4629,6 +4637,9 @@
"sKHiNR": [["count"], " पीछे"],
"sNeKjP": ["टोकन सहेजने में विफल — फिर कोशिश करें"],
"sOafXU": ["संपादित करके फिर भेजें"],
+ "sOcMdy": [
+ "कोई दूसरा प्रोग्राम यहाँ Git का उपयोग कर रहा है — उसके पूरा होने की प्रतीक्षा करें, फिर दोबारा सिंक करें (वह .git/index.lock रोके हुए है)"
+ ],
"sOxZaS": ["ग्राफ़ लोड करने में विफल"],
"sQoLn0": ["बाहर निकलें"],
"sR0I-f": ["सभी फ़ाइलें समेटें"],
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index e929fe649..cf4a3e6ef 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -1967,6 +1967,14 @@ msgstr "और {remaining} अन्य"
msgid "and more"
msgstr "और अन्य"
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr "कोई दूसरा प्रोग्राम यहाँ Git का उपयोग कर रहा है — उसके पूरा होने की प्रतीक्षा करें, फिर दोबारा सिंक करें (वह .git/index.lock रोके हुए है)"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr "कोई दूसरा प्रोग्राम यहाँ Git का उपयोग कर रहा है — उसके पूरा होने की प्रतीक्षा करें, फिर दोबारा सिंक करें (वह <0>.git/index.lock</0> रोके हुए है)"
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr "एक और सिंक कार्रवाई चल रही है। कुछ देर बाद फिर कोशिश करें।"
@@ -14536,6 +14544,14 @@ msgstr "यह Slidev का समर्थित संस्करण नह
msgid "this item"
msgstr "यह आइटम"
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr "यह सूची पुरानी हो सकती है — पिछली बार पढ़ा गया {staleRelative}।"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr "यह सूची पुरानी हो सकती है।"
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr "यह किसी ड्राइव का रूट लगता है (जैसे C:\\)। यहाँ ढाँचा बनाने पर पूरी ड्राइव स्कैन होगी।"
@@ -14682,6 +14698,10 @@ msgstr "यह आपके Mac से और नीचे चुने गए
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr "यह रिपोर्ट पहले ही रास्ते में है। इसका नतीजा बग रिपोर्ट इतिहास में दिखेगा।"
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr "इस रिपॉज़िटरी में अभी कोई कमिट नहीं है — पहला कमिट बनाने के लिए प्रोजेक्ट दोबारा खोलें, फिर भेजें काम करेगा"
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr "यह अनुरोध अब सक्रिय नहीं है।"
diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.json
index 9cbab0833..194b5d2f9 100644
--- a/packages/app/src/locales/id/messages.json
+++ b/packages/app/src/locales/id/messages.json
@@ -19,6 +19,9 @@
"-WeuHF": ["Hapus pesan dari antrean"],
"-X1eoK": ["Integrasi OpenKnowledge telah diperiksa."],
"-YV1Uo": ["Pola ", ["patternNumber"]],
+ "-ZVU5v": [
+ "Repositori ini belum punya commit — buka lagi proyeknya untuk membuat commit pertama, lalu Push akan berfungsi"
+ ],
"-bFGPF": ["Perubahan berikutnya"],
"-dNlfM": ["Suntingan terakhir pada ", ["docName"], " dibatalkan"],
"-g6KIS": ["Tautan tidak dikenali"],
@@ -2270,6 +2273,9 @@
"QWdKwH": ["Pindahkan"],
"QYTOaN": ["Anda bisa mengubah ini nanti di <0>Pengaturan → Sinkronisasi</0>."],
"QYfQdv": ["CLI ", ["displayName"]],
+ "Qca--K": [
+ "Program lain sedang memakai Git di sini — tunggu sampai selesai, lalu sinkronkan lagi (program itu menahan <0>.git/index.lock</0>)"
+ ],
"QcpeeE": ["Pergi ke ", ["docName"]],
"Qe47G0": [
["componentLabel"],
@@ -3088,6 +3094,7 @@
"_IX_7x": ["Lainnya"],
"_IfSZn": ["Tema tersimpan lain sudah menggunakan nama ini."],
"_JOGC0": ["Kirim masukan…"],
+ "_LK4d6": ["Daftar ini mungkin tidak mutakhir."],
"_LczaQ": ["Ditolak — ", ["optionName"]],
"_NWEid": ["Cari berkas skema berdasarkan jalur"],
"_O7dJS": ["Versi berbeda di sini — klik untuk membandingkan dan menyelesaikannya"],
@@ -3478,6 +3485,7 @@
"dw_dUJ": ["Gagal menggandakan jalur"],
"dx-TwN": ["Menjalankan audit proyek"],
"dyfMJN": ["Kode disalin"],
+ "e-pP6g": ["Daftar ini mungkin tidak mutakhir — terakhir dibaca ", ["staleRelative"], "."],
"e0NrBM": ["Proyek"],
"e1Rn_k": ["Buka folder induknya"],
"e1hptq": ["Menyematkan video dengan kendali pemutar bawaan."],
@@ -4832,6 +4840,9 @@
"sKHiNR": [["count"], " di belakang"],
"sNeKjP": ["Gagal menyimpan token — coba lagi"],
"sOafXU": ["Sunting dan kirim lagi"],
+ "sOcMdy": [
+ "Program lain sedang memakai Git di sini — tunggu sampai selesai, lalu sinkronkan lagi (program itu menahan .git/index.lock)"
+ ],
"sOxZaS": ["Gagal memuat graf"],
"sQoLn0": ["Keluar"],
"sR0I-f": ["Ciutkan semua berkas"],
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index 93c332d5b..903378c07 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -1967,6 +1967,14 @@ msgstr "dan {remaining} lagi"
msgid "and more"
msgstr "dan lainnya"
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr "Program lain sedang memakai Git di sini — tunggu sampai selesai, lalu sinkronkan lagi (program itu menahan .git/index.lock)"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr "Program lain sedang memakai Git di sini — tunggu sampai selesai, lalu sinkronkan lagi (program itu menahan <0>.git/index.lock</0>)"
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr "Operasi sinkronisasi lain sedang berjalan. Coba lagi sebentar."
@@ -14536,6 +14544,14 @@ msgstr "Ini bukan versi Slidev yang didukung."
msgid "this item"
msgstr "item ini"
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr "Daftar ini mungkin tidak mutakhir — terakhir dibaca {staleRelative}."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr "Daftar ini mungkin tidak mutakhir."
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr "Ini tampak seperti akar sebuah drive (mis. C:\\). Menyusun proyek di sini akan memindai seluruh drive."
@@ -14682,6 +14698,10 @@ msgstr "Ini menghapus pengaturan dan integrasi OpenKnowledge dari Mac Anda serta
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr "Laporan ini sudah dalam perjalanan. Hasilnya akan muncul di riwayat laporan bug."
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr "Repositori ini belum punya commit — buka lagi proyeknya untuk membuat commit pertama, lalu Push akan berfungsi"
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr "Permintaan ini sudah tidak aktif."
diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.json
index 57ea6b58b..abab6fe7e 100644
--- a/packages/app/src/locales/ko/messages.json
+++ b/packages/app/src/locales/ko/messages.json
@@ -19,6 +19,9 @@
"-WeuHF": ["대기 중인 메시지 제거"],
"-X1eoK": ["OpenKnowledge 통합을 확인했습니다."],
"-YV1Uo": ["패턴 ", ["patternNumber"]],
+ "-ZVU5v": [
+ "이 저장소에는 아직 커밋이 없습니다. 프로젝트를 다시 열면 첫 커밋이 만들어지고, 그때부터 푸시가 동작합니다."
+ ],
"-bFGPF": ["다음 변경"],
"-dNlfM": [["docName"], "에서 마지막 편집을 실행 취소했습니다."],
"-g6KIS": ["인식할 수 없는 링크"],
@@ -2171,6 +2174,9 @@
"QWdKwH": ["이동"],
"QYTOaN": ["나중에 <0>설정 → 동기화</0>에서 변경할 수 있습니다."],
"QYfQdv": [["displayName"], " CLI"],
+ "Qca--K": [
+ "다른 프로그램이 여기서 Git을 사용 중입니다. 끝날 때까지 기다린 후 다시 동기화하세요(<0>.git/index.lock</0>을 잡고 있습니다)."
+ ],
"QcpeeE": [["docName"], "로 이동"],
"Qe47G0": [["componentLabel"], ", 항목 ", ["childCount", "plural", { "other": ["#", "개"] }]],
"QeREu8": ["이름 변경됨"],
@@ -2958,6 +2964,7 @@
"_IX_7x": ["기타"],
"_IfSZn": ["이미 이 이름을 사용하는 저장된 테마가 있습니다."],
"_JOGC0": ["피드백 보내기…"],
+ "_LK4d6": ["이 목록은 최신 상태가 아닐 수 있습니다."],
"_LczaQ": ["거부됨: ", ["optionName"]],
"_NWEid": ["경로로 스키마 파일 검색"],
"_O7dJS": ["여기에는 다른 버전이 있습니다. 비교하고 해결하려면 클릭하세요"],
@@ -3327,6 +3334,11 @@
"dw_dUJ": ["경로를 복제하지 못했습니다"],
"dx-TwN": ["프로젝트 감사 실행 중"],
"dyfMJN": ["코드 복사됨"],
+ "e-pP6g": [
+ "이 목록은 최신 상태가 아닐 수 있습니다. 마지막으로 읽은 시각: ",
+ ["staleRelative"],
+ "."
+ ],
"e0NrBM": ["프로젝트"],
"e1Rn_k": ["포함 폴더 열기"],
"e1hptq": ["기본 플레이어 컨트롤이 있는 동영상을 삽입합니다."],
@@ -4614,6 +4626,9 @@
"sKHiNR": [["count"], "개 뒤처짐"],
"sNeKjP": ["토큰 저장 실패. 다시 시도하세요."],
"sOafXU": ["편집 후 다시 전송"],
+ "sOcMdy": [
+ "다른 프로그램이 여기서 Git을 사용 중입니다. 끝날 때까지 기다린 후 다시 동기화하세요(.git/index.lock을 잡고 있습니다)."
+ ],
"sOxZaS": ["그래프 불러오기 실패"],
"sQoLn0": ["종료"],
"sR0I-f": ["모든 파일 접기"],
diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.po
index 750fd7acc..7db36a3b3 100644
--- a/packages/app/src/locales/ko/messages.po
+++ b/packages/app/src/locales/ko/messages.po
@@ -1971,6 +1971,14 @@ msgstr "및 {remaining}개 더"
msgid "and more"
msgstr "그리고 더"
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr "다른 프로그램이 여기서 Git을 사용 중입니다. 끝날 때까지 기다린 후 다시 동기화하세요(.git/index.lock을 잡고 있습니다)."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr "다른 프로그램이 여기서 Git을 사용 중입니다. 끝날 때까지 기다린 후 다시 동기화하세요(<0>.git/index.lock</0>을 잡고 있습니다)."
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr "다른 동기화 작업이 진행 중입니다. 잠시 후 다시 시도하세요."
@@ -14540,6 +14548,14 @@ msgstr "지원되는 Slidev 버전이 아닙니다."
msgid "this item"
msgstr "이 항목"
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr "이 목록은 최신 상태가 아닐 수 있습니다. 마지막으로 읽은 시각: {staleRelative}."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr "이 목록은 최신 상태가 아닐 수 있습니다."
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr "드라이브 루트처럼 보입니다(예: Windows 드라이브 루트). 여기서 뼈대를 만들면 드라이브 전체를 검사합니다."
@@ -14686,6 +14702,10 @@ msgstr "이 작업은 Mac과 아래에서 선택한 프로젝트에서 OpenKnowl
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr "이 보고서는 이미 전송 중입니다. 결과는 버그 신고 기록에 표시됩니다."
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr "이 저장소에는 아직 커밋이 없습니다. 프로젝트를 다시 열면 첫 커밋이 만들어지고, 그때부터 푸시가 동작합니다."
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr "요청 만료 또는 비활성 상태."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 82bc4c833..6ced6ed6f 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -25,6 +25,9 @@
"-WeuHF": ["Ŕēḿōvē ǫũēũēď ḿēśśàĝē"],
"-X1eoK": ["ŌƥēńĶńōŵĺēďĝē ĩńţēĝŕàţĩōńś ćĥēćķēď."],
"-YV1Uo": ["Ƥàţţēŕń ", ["patternNumber"]],
+ "-ZVU5v": [
+ "Ţĥĩś ŕēƥōśĩţōŕŷ ĥàś ńō ćōḿḿĩţś ŷēţ — ŕēōƥēń ţĥē ƥŕōĴēćţ ţō ćŕēàţē ţĥē ƒĩŕśţ ćōḿḿĩţ, ţĥēń Ƥũśĥ ŵĩĺĺ ŵōŕķ"
+ ],
"-bFGPF": ["Ńēxţ ćĥàńĝē"],
"-dNlfM": ["Ũńďĩď ţĥē ĺàśţ ēďĩţ ōń ", ["docName"]],
"-g6KIS": ["Ũńŕēćōĝńĩźēď ĺĩńķ"],
@@ -2252,6 +2255,9 @@
"QWdKwH": ["Ḿōvē"],
"QYTOaN": ["Ŷōũ ćàń ćĥàńĝē ţĥĩś ĺàţēŕ ĩń <0>Śēţţĩńĝś → Śŷńć</0>."],
"QYfQdv": [["displayName"], " ĆĹĨ"],
+ "Qca--K": [
+ "Àńōţĥēŕ ƥŕōĝŕàḿ ĩś ũśĩńĝ Ĝĩţ ĥēŕē — ŵàĩţ ƒōŕ ĩţ ţō ƒĩńĩśĥ, ţĥēń śŷńć àĝàĩń (ĩţ ĥōĺďś <0>.ĝĩţ/ĩńďēx.ĺōćķ</0>)"
+ ],
"QcpeeE": ["Ńàvĩĝàţē ţō ", ["docName"]],
"Qe47G0": [
["componentLabel"],
@@ -3067,6 +3073,7 @@
"_IX_7x": ["Ōţĥēŕ"],
"_IfSZn": ["À śàvēď ţĥēḿē àĺŕēàďŷ ũśēś ţĥĩś ńàḿē."],
"_JOGC0": ["Śēńď ƒēēďƀàćķ…"],
+ "_LK4d6": ["Ţĥĩś ĺĩśţ ḿàŷ ƀē ōũţ ōƒ ďàţē."],
"_LczaQ": ["Ďēńĩēď — ", ["optionName"]],
"_NWEid": ["Śēàŕćĥ śćĥēḿà ƒĩĺēś ƀŷ ƥàţĥ"],
"_O7dJS": ["Ďĩƒƒēŕēńţ vēŕśĩōń ĥēŕē — ćĺĩćķ ţō ćōḿƥàŕē àńď ŕēśōĺvē"],
@@ -3463,6 +3470,7 @@
"dw_dUJ": ["Ƒàĩĺēď ţō ďũƥĺĩćàţē ƥàţĥ"],
"dx-TwN": ["Ŕũńńĩńĝ ƥŕōĴēćţ àũďĩţ"],
"dyfMJN": ["Ćōďē ćōƥĩēď"],
+ "e-pP6g": ["Ţĥĩś ĺĩśţ ḿàŷ ƀē ōũţ ōƒ ďàţē — ĺàśţ ŕēàď ", ["staleRelative"], "."],
"e0NrBM": ["ƤŕōĴēćţ"],
"e1Rn_k": ["Ōƥēń ćōńţàĩńĩńĝ ƒōĺďēŕ"],
"e1hptq": ["Ēḿƀēď à vĩďēō ŵĩţĥ ńàţĩvē ƥĺàŷēŕ ćōńţŕōĺś."],
@@ -4810,6 +4818,9 @@
"sKHiNR": [["count"], " ƀēĥĩńď"],
"sNeKjP": ["Ƒàĩĺēď ţō śţōŕē ţĥē ţōķēń — ţŕŷ àĝàĩń"],
"sOafXU": ["Ēďĩţ àńď śēńď àĝàĩń"],
+ "sOcMdy": [
+ "Àńōţĥēŕ ƥŕōĝŕàḿ ĩś ũśĩńĝ Ĝĩţ ĥēŕē — ŵàĩţ ƒōŕ ĩţ ţō ƒĩńĩśĥ, ţĥēń śŷńć àĝàĩń (ĩţ ĥōĺďś .ĝĩţ/ĩńďēx.ĺōćķ)"
+ ],
"sOxZaS": ["Ƒàĩĺēď ţō ĺōàď ĝŕàƥĥ"],
"sQoLn0": ["Ǫũĩţ"],
"sR0I-f": ["Ćōĺĺàƥśē àĺĺ ƒĩĺēś"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 96c949ceb..50c659115 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -1967,6 +1967,14 @@ msgstr ""
msgid "and more"
msgstr ""
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr ""
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr ""
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr ""
@@ -14536,6 +14544,14 @@ msgstr ""
msgid "this item"
msgstr ""
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr ""
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr ""
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr ""
@@ -14682,6 +14698,10 @@ msgstr ""
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr ""
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr ""
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr ""
diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.json
index 75813dc53..4ae02b392 100644
--- a/packages/app/src/locales/pt-BR/messages.json
+++ b/packages/app/src/locales/pt-BR/messages.json
@@ -35,6 +35,9 @@
"-WeuHF": ["Remover a mensagem da fila"],
"-X1eoK": ["Integrações do OpenKnowledge verificadas."],
"-YV1Uo": ["Padrão ", ["patternNumber"]],
+ "-ZVU5v": [
+ "Este repositório ainda não tem commits — abra o projeto de novo para criar o primeiro commit e então o Push vai funcionar"
+ ],
"-bFGPF": ["Próxima alteração"],
"-dNlfM": ["A última edição em ", ["docName"], " foi desfeita"],
"-g6KIS": ["Link não reconhecido"],
@@ -2568,6 +2571,9 @@
"QWdKwH": ["Mover"],
"QYTOaN": ["Você pode mudar isto depois em <0>Configurações → Sincronização</0>."],
"QYfQdv": ["CLI do ", ["displayName"]],
+ "Qca--K": [
+ "Outro programa está usando o Git aqui — espere ele terminar e sincronize de novo (ele está segurando o <0>.git/index.lock</0>)"
+ ],
"QcpeeE": ["Ir para ", ["docName"]],
"Qe47G0": [
["componentLabel"],
@@ -3498,6 +3504,7 @@
"_IX_7x": ["Outro"],
"_IfSZn": ["Um tema salvo já usa este nome."],
"_JOGC0": ["Enviar comentários…"],
+ "_LK4d6": ["Esta lista pode estar desatualizada."],
"_LczaQ": ["Negado — ", ["optionName"]],
"_NWEid": ["Busque arquivos de esquema por caminho"],
"_O7dJS": ["Versão diferente aqui — clique para comparar e resolver"],
@@ -3946,6 +3953,7 @@
"dw_dUJ": ["Falha ao duplicar o caminho"],
"dx-TwN": ["Rodando a auditoria do projeto"],
"dyfMJN": ["Código copiado"],
+ "e-pP6g": ["Esta lista pode estar desatualizada — última leitura ", ["staleRelative"], "."],
"e0NrBM": ["Projeto"],
"e1Rn_k": ["Abrir a pasta que o contém"],
"e1hptq": ["Incorpora um vídeo com os controles nativos do player."],
@@ -5446,6 +5454,9 @@
"sKHiNR": [["count"], " atrás"],
"sNeKjP": ["Falha ao guardar o token — tente de novo"],
"sOafXU": ["Editar e enviar de novo"],
+ "sOcMdy": [
+ "Outro programa está usando o Git aqui — espere ele terminar e sincronize de novo (ele está segurando o .git/index.lock)"
+ ],
"sOxZaS": ["Falha ao carregar o grafo"],
"sQoLn0": ["Sair"],
"sR0I-f": ["Recolher todos os arquivos"],
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index 0c2d18127..2700c68dd 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -1967,6 +1967,14 @@ msgstr "e mais {remaining}"
msgid "and more"
msgstr "e mais"
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr "Outro programa está usando o Git aqui — espere ele terminar e sincronize de novo (ele está segurando o .git/index.lock)"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr "Outro programa está usando o Git aqui — espere ele terminar e sincronize de novo (ele está segurando o <0>.git/index.lock</0>)"
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr "Outra operação de sincronização está em andamento. Tente de novo em instantes."
@@ -14536,6 +14544,14 @@ msgstr "Esta não é uma versão compatível do Slidev."
msgid "this item"
msgstr "este item"
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr "Esta lista pode estar desatualizada — última leitura {staleRelative}."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr "Esta lista pode estar desatualizada."
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr "Isto parece a raiz de uma unidade (ex.: C:\\). Preparar o projeto aqui vai varrer uma unidade inteira."
@@ -14682,6 +14698,10 @@ msgstr "Isto remove do seu Mac as configurações e integrações do OpenKnowled
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr "Este relatório já está a caminho. O resultado vai aparecer no histórico de relatórios de erro."
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr "Este repositório ainda não tem commits — abra o projeto de novo para criar o primeiro commit e então o Push vai funcionar"
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr "Esta requisição não está mais ativa."
diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.json
index 837c09b80..d0828cddc 100644
--- a/packages/app/src/locales/ur/messages.json
+++ b/packages/app/src/locales/ur/messages.json
@@ -21,6 +21,9 @@
"-WeuHF": ["قطار میں موجود پیغام ہٹائیں"],
"-X1eoK": ["OpenKnowledge انٹیگریشنز جانچ لی گئیں۔"],
"-YV1Uo": ["پیٹرن ", ["patternNumber"]],
+ "-ZVU5v": [
+ "اس ریپازٹری میں ابھی کوئی کمٹ نہیں ہے — پہلا کمٹ بنانے کے لیے پروجیکٹ دوبارہ کھولیں، پھر پُش کام کرے گا"
+ ],
"-bFGPF": ["اگلی تبدیلی"],
"-dNlfM": [["docName"], " پر آخری ترمیم واپس لے لی گئی"],
"-g6KIS": ["ناقابلِ شناخت لنک"],
@@ -2291,6 +2294,9 @@
"QWdKwH": ["منتقل کریں"],
"QYTOaN": ["آپ اسے بعد میں <0>ترتیبات ← مطابقت پذیری</0> میں بدل سکتے ہیں۔"],
"QYfQdv": [["displayName"], " CLI"],
+ "Qca--K": [
+ "کوئی دوسرا پروگرام یہاں Git استعمال کر رہا ہے — اس کے مکمل ہونے کا انتظار کریں، پھر دوبارہ مطابقت پذیری کریں (وہ <0>.git/index.lock</0> روکے ہوئے ہے)"
+ ],
"QcpeeE": [["docName"], " پر جائیں"],
"Qe47G0": [
["componentLabel"],
@@ -3132,6 +3138,7 @@
"_IX_7x": ["دیگر"],
"_IfSZn": ["اس نام کی ایک محفوظ شدہ تھیم پہلے سے موجود ہے۔"],
"_JOGC0": ["رائے بھیجیں…"],
+ "_LK4d6": ["یہ فہرست پرانی ہو سکتی ہے۔"],
"_LczaQ": ["مسترد — ", ["optionName"]],
"_NWEid": ["اسکیما فائلیں راستے سے تلاش کریں"],
"_O7dJS": ["یہاں مختلف ورژن ہے — موازنے اور حل کے لیے کلک کریں"],
@@ -3538,6 +3545,7 @@
"dw_dUJ": ["راستے کی نقل نہیں بن سکی"],
"dx-TwN": ["پروجیکٹ کا آڈٹ چل رہا ہے"],
"dyfMJN": ["کوڈ کاپی ہو گیا"],
+ "e-pP6g": ["یہ فہرست پرانی ہو سکتی ہے — آخری بار پڑھا گیا ", ["staleRelative"], "۔"],
"e0NrBM": ["پروجیکٹ"],
"e1Rn_k": ["پر مشتمل فولڈر کھولیں"],
"e1hptq": ["مقامی پلیئر کنٹرولز کے ساتھ ویڈیو شامل کریں۔"],
@@ -4892,6 +4900,9 @@
"sKHiNR": [["count"], " پیچھے"],
"sNeKjP": ["ٹوکن محفوظ نہیں ہو سکا — دوبارہ کوشش کریں"],
"sOafXU": ["ترمیم کر کے دوبارہ بھیجیں"],
+ "sOcMdy": [
+ "کوئی دوسرا پروگرام یہاں Git استعمال کر رہا ہے — اس کے مکمل ہونے کا انتظار کریں، پھر دوبارہ مطابقت پذیری کریں (وہ .git/index.lock روکے ہوئے ہے)"
+ ],
"sOxZaS": ["گراف لوڈ نہیں ہو سکا"],
"sQoLn0": ["باہر نکلیں"],
"sR0I-f": ["سب فائلیں سکیڑیں"],
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index d30b73dc8..ceb111aad 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -1971,6 +1971,14 @@ msgstr "اور {remaining} مزید"
msgid "and more"
msgstr "اور مزید"
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr "کوئی دوسرا پروگرام یہاں Git استعمال کر رہا ہے — اس کے مکمل ہونے کا انتظار کریں، پھر دوبارہ مطابقت پذیری کریں (وہ .git/index.lock روکے ہوئے ہے)"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr "کوئی دوسرا پروگرام یہاں Git استعمال کر رہا ہے — اس کے مکمل ہونے کا انتظار کریں، پھر دوبارہ مطابقت پذیری کریں (وہ <0>.git/index.lock</0> روکے ہوئے ہے)"
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr "ایک اور مطابقت پذیری جاری ہے۔ تھوڑی دیر بعد دوبارہ کوشش کریں۔"
@@ -14540,6 +14548,14 @@ msgstr "یہ Slidev کا معاون ورژن نہیں ہے۔"
msgid "this item"
msgstr "یہ آئٹم"
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr "یہ فہرست پرانی ہو سکتی ہے — آخری بار پڑھا گیا {staleRelative}۔"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr "یہ فہرست پرانی ہو سکتی ہے۔"
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr "یہ کسی ڈرائیو کی جڑ لگتی ہے (مثلاً C:\\)۔ یہاں ڈھانچہ بنانا پوری ڈرائیو اسکین کرے گا۔"
@@ -14686,6 +14702,10 @@ msgstr "یہ OpenKnowledge کی ترتیبات اور انضمامات کو آپ
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr "یہ رپورٹ پہلے ہی راستے میں ہے۔ اس کا نتیجہ بگ رپورٹ کی تاریخ میں نظر آئے گا۔"
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr "اس ریپازٹری میں ابھی کوئی کمٹ نہیں ہے — پہلا کمٹ بنانے کے لیے پروجیکٹ دوبارہ کھولیں، پھر پُش کام کرے گا"
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr "یہ درخواست اب فعال نہیں۔"
diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.json
index 3c0f2caed..e8a2a0a37 100644
--- a/packages/app/src/locales/zh-Hans/messages.json
+++ b/packages/app/src/locales/zh-Hans/messages.json
@@ -19,6 +19,7 @@
"-WeuHF": ["移除排队中的消息"],
"-X1eoK": ["已检查 OpenKnowledge 集成。"],
"-YV1Uo": ["模式 ", ["patternNumber"]],
+ "-ZVU5v": ["此仓库还没有任何提交——重新打开项目即可创建第一个提交,之后就能推送了"],
"-bFGPF": ["下一处改动"],
"-dNlfM": ["已撤销 ", ["docName"], " 上的最后一次编辑"],
"-g6KIS": ["无法识别的链接"],
@@ -1971,6 +1972,9 @@
"QWdKwH": ["移动"],
"QYTOaN": ["之后可以在<0>「设置 → 同步」</0>中更改。"],
"QYfQdv": [["displayName"], " CLI"],
+ "Qca--K": [
+ "另一个程序正在这里使用 Git——等它完成后再同步一次(它占用着 <0>.git/index.lock</0>)"
+ ],
"QcpeeE": ["跳转到 ", ["docName"]],
"Qe47G0": [
["componentLabel"],
@@ -2699,6 +2703,7 @@
"_IX_7x": ["其他"],
"_IfSZn": ["已有一个已保存的主题使用此名称。"],
"_JOGC0": ["发送反馈…"],
+ "_LK4d6": ["此列表可能不是最新的。"],
"_LczaQ": ["已拒绝 — ", ["optionName"]],
"_NWEid": ["按路径搜索架构文件"],
"_O7dJS": ["这里的版本不同——点击可比较并解决"],
@@ -3028,6 +3033,7 @@
"dw_dUJ": ["复制路径失败"],
"dx-TwN": ["正在运行项目审查"],
"dyfMJN": ["代码已复制"],
+ "e-pP6g": ["此列表可能不是最新的——上次读取:", ["staleRelative"], "。"],
"e0NrBM": ["项目"],
"e1Rn_k": ["打开所在文件夹"],
"e1hptq": ["嵌入一段视频,带原生播放器控件。"],
@@ -4188,6 +4194,7 @@
"sKHiNR": ["落后 ", ["count"], " 个提交"],
"sNeKjP": ["保存令牌失败——请重试"],
"sOafXU": ["编辑后重新发送"],
+ "sOcMdy": ["另一个程序正在这里使用 Git——等它完成后再同步一次(它占用着 .git/index.lock)"],
"sOxZaS": ["加载关系图失败"],
"sQoLn0": ["退出"],
"sR0I-f": ["折叠全部文件"],
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index 3dce23b5b..ab40562fb 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -1971,6 +1971,14 @@ msgstr "另外还有 {remaining} 个"
msgid "and more"
msgstr "以及更多"
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr "另一个程序正在这里使用 Git——等它完成后再同步一次(它占用着 .git/index.lock)"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr "另一个程序正在这里使用 Git——等它完成后再同步一次(它占用着 <0>.git/index.lock</0>)"
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr "另一个同步操作正在进行中。请稍后再试。"
@@ -14540,6 +14548,14 @@ msgstr "这不是受支持的 Slidev 版本。"
msgid "this item"
msgstr "这个项目"
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr "此列表可能不是最新的——上次读取:{staleRelative}。"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr "此列表可能不是最新的。"
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr "这看起来像是驱动器根目录(例如 C:\\)。在这里搭建项目会扫描整个驱动器。"
@@ -14686,6 +14702,10 @@ msgstr "这会从你的 Mac 以及你在下方选择的项目中移除 OpenKnowl
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr "该报告已经在发送途中,结果会显示在错误报告历史里。"
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr "此仓库还没有任何提交——重新打开项目即可创建第一个提交,之后就能推送了"
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr "这个请求已不再有效。"
diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.json
index 957ad39db..a1c68511c 100644
--- a/packages/app/src/locales/zh-Hant/messages.json
+++ b/packages/app/src/locales/zh-Hant/messages.json
@@ -19,6 +19,7 @@
"-WeuHF": ["移除排隊中的訊息"],
"-X1eoK": ["已檢查 OpenKnowledge 整合。"],
"-YV1Uo": ["模式 ", ["patternNumber"]],
+ "-ZVU5v": ["這個儲存庫還沒有任何提交——重新開啟專案即可建立第一個提交,之後就能推送了"],
"-bFGPF": ["下一處變更"],
"-dNlfM": ["已復原 ", ["docName"], " 上的最後一次編輯"],
"-g6KIS": ["無法辨識的連結"],
@@ -1989,6 +1990,9 @@
"QWdKwH": ["移動"],
"QYTOaN": ["之後可以在<0>「設定 → 同步」</0>中變更。"],
"QYfQdv": [["displayName"], " CLI"],
+ "Qca--K": [
+ "另一個程式正在這裡使用 Git——等它完成後再同步一次(它佔用著 <0>.git/index.lock</0>)"
+ ],
"QcpeeE": ["前往 ", ["docName"]],
"Qe47G0": [
["componentLabel"],
@@ -2715,6 +2719,7 @@
"_IX_7x": ["其他"],
"_IfSZn": ["已有已儲存的主題使用這個名稱。"],
"_JOGC0": ["傳送意見回饋…"],
+ "_LK4d6": ["這份清單可能不是最新的。"],
"_LczaQ": ["已拒絕 — ", ["optionName"]],
"_NWEid": ["依路徑搜尋結構描述檔案"],
"_O7dJS": ["這裡的版本不同——點一下可比較並解決"],
@@ -3046,6 +3051,7 @@
"dw_dUJ": ["複製路徑失敗"],
"dx-TwN": ["正在執行專案稽核"],
"dyfMJN": ["代碼已複製"],
+ "e-pP6g": ["這份清單可能不是最新的——上次讀取:", ["staleRelative"], "。"],
"e0NrBM": ["專案"],
"e1Rn_k": ["開啟所在的資料夾"],
"e1hptq": ["嵌入一段影片,附原生播放器控制項。"],
@@ -4208,6 +4214,7 @@
"sKHiNR": ["落後 ", ["count"], " 個提交"],
"sNeKjP": ["儲存權杖失敗——請再試一次"],
"sOafXU": ["編輯後重新傳送"],
+ "sOcMdy": ["另一個程式正在這裡使用 Git——等它完成後再同步一次(它佔用著 .git/index.lock)"],
"sOxZaS": ["載入關係圖失敗"],
"sQoLn0": ["結束"],
"sR0I-f": ["摺疊全部檔案"],
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index 0155febef..2f89ea4f7 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -1971,6 +1971,14 @@ msgstr "另外還有 {remaining} 個"
msgid "and more"
msgstr "以及更多"
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds .git/index.lock)"
+msgstr "另一個程式正在這裡使用 Git——等它完成後再同步一次(它佔用著 .git/index.lock)"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Another program is using Git here — wait for it to finish, then sync again (it holds <0>.git/index.lock</0>)"
+msgstr "另一個程式正在這裡使用 Git——等它完成後再同步一次(它佔用著 <0>.git/index.lock</0>)"
+
#: src/components/share-receive-miss-content.tsx
msgid "Another sync operation is in progress. Try again in a moment."
msgstr "另一個同步作業正在進行中。請稍候再試。"
@@ -14540,6 +14548,14 @@ msgstr "這不是支援的 Slidev 版本。"
msgid "this item"
msgstr "這個項目"
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date — last read {staleRelative}."
+msgstr "這份清單可能不是最新的——上次讀取:{staleRelative}。"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "This list may be out of date."
+msgstr "這份清單可能不是最新的。"
+
#: src/components/ConsentDialogBody.tsx
msgid "This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
msgstr "這看起來像是磁碟機根目錄(例如 C:\\)。在這裡建立專案骨架會掃描整個磁碟機。"
@@ -14686,6 +14702,10 @@ msgstr "這會從你的 Mac 以及你在下面選的專案中移除 OpenKnowledg
msgid "This report is already on its way. Its result will appear in your bug report history."
msgstr "這份回報已經在傳送途中,結果會顯示在錯誤回報記錄裡。"
+#: src/components/SyncStatusBadge.tsx
+msgid "This repository has no commits yet — reopen the project to create the first commit, then Push will work"
+msgstr "這個儲存庫還沒有任何提交——重新開啟專案即可建立第一個提交,之後就能推送了"
+
#: src/components/acp/ThreadView.tsx
msgid "This request is no longer active."
msgstr "這個要求已經失效。"
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 31345780b..0b2a5a9c9 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1888,6 +1888,7 @@ export {
type SkillsShSkillLinks,
skillsShSkillLinks,
} from './skills-catalog/source-fields.ts';
+export { SYNC_PAUSED_REASONS, type SyncPausedReason } from './sync-paused-reason.ts';
export {
composeTemplateFile,
instantiateDoc,
diff --git a/packages/core/src/sync-paused-reason.test.ts b/packages/core/src/sync-paused-reason.test.ts
new file mode 100644
index 000000000..c318a1c31
--- /dev/null
+++ b/packages/core/src/sync-paused-reason.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, test } from 'vitest';
+import { SyncStatusSchema } from './schemas/api/sync-seed.ts';
+import { SYNC_PAUSED_REASONS } from './sync-paused-reason.ts';
+
+const baseStatus = {
+ state: 'idle',
+ lastSyncUtc: null,
+ lastFetchUtc: null,
+ lastPushedSha: null,
+ ahead: 0,
+ behind: 0,
+ consecutiveFailures: 0,
+ consecutivePushFailures: 0,
+ conflictCount: 0,
+ hasRemote: true,
+ syncEnabled: true,
+ identityUnresolved: false,
+};
+
+describe('SYNC_PAUSED_REASONS', () => {
+ test('is a de-duplicated list of kebab-case tokens', () => {
+ expect(SYNC_PAUSED_REASONS.length).toBe(new Set(SYNC_PAUSED_REASONS).size);
+ for (const reason of SYNC_PAUSED_REASONS) {
+ expect(reason, reason).toMatch(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/);
+ }
+ });
+
+ test('every member is accepted by the wire schema it describes', () => {
+ for (const reason of SYNC_PAUSED_REASONS) {
+ expect(
+ SyncStatusSchema.safeParse({ ...baseStatus, pausedReason: reason }).success,
+ reason,
+ ).toBe(true);
+ }
+ });
+
+ test('the wire field stays open, so a newer server can name a reason this build lacks', () => {
+ const parsed = SyncStatusSchema.safeParse({
+ ...baseStatus,
+ pausedReason: 'a-reason-from-the-future',
+ });
+
+ expect(parsed.success).toBe(true);
+ expect(parsed.data?.pausedReason).toBe('a-reason-from-the-future');
+ });
+});
diff --git a/packages/core/src/sync-paused-reason.ts b/packages/core/src/sync-paused-reason.ts
new file mode 100644
index 000000000..f487decad
--- /dev/null
+++ b/packages/core/src/sync-paused-reason.ts
@@ -0,0 +1,15 @@
+export const SYNC_PAUSED_REASONS = [
+ 'auth-error',
+ 'detached-head',
+ 'dirty-tree',
+ 'diverged-local-commits',
+ 'external-changes-pending',
+ 'git-index-locked',
+ 'git-operation-in-progress',
+ 'no-commits-yet',
+ 'no-push-permission',
+ 'non-content-merge-failure',
+ 'protected-branch',
+] as const;
+
+export type SyncPausedReason = (typeof SYNC_PAUSED_REASONS)[number];
diff --git a/packages/server/src/git-dirty.test.ts b/packages/server/src/git-dirty.test.ts
index 0738f3612..32eef92d8 100644
--- a/packages/server/src/git-dirty.test.ts
+++ b/packages/server/src/git-dirty.test.ts
@@ -100,6 +100,24 @@ describe('dirtyFilesOverlapWith', () => {
expect(result.files).toEqual(['new-on-feature.md']);
});
+ test('a file inside a wholly untracked directory registers as an overlap', async () => {
+ write('a.md', 'a-on-main\n');
+ commitAll('init');
+ run('git checkout -q -b feature');
+ run('mkdir -p notes');
+ write('notes/plan.md', 'feature-created\n');
+ commitAll('feature adds a file in a new directory');
+ run('git checkout -q main');
+
+ run('mkdir -p notes');
+ write('notes/plan.md', 'untracked-local\n');
+
+ const result = await dirtyFilesOverlapWith(projectDir, 'feature');
+
+ expect(result.conflicts).toBe(true);
+ expect(result.files).toEqual(['notes/plan.md']);
+ });
+
test('multiple overlapping dirty + untracked files produce sorted deduped list', async () => {
write('a.md', 'a-on-main\n');
write('b.md', 'b-on-main\n');
diff --git a/packages/server/src/git-dirty.ts b/packages/server/src/git-dirty.ts
index 4a5178918..bc6bd5286 100644
--- a/packages/server/src/git-dirty.ts
+++ b/packages/server/src/git-dirty.ts
@@ -1,5 +1,5 @@
import { createGitInstance } from './git-handle.ts';
-import { listNames, listPorcelainPaths } from './git-paths.ts';
+import { listNames, listPorcelainPaths, PORCELAIN_STATUS_ARGS } from './git-paths.ts';
export interface DirtyOverlapResult {
conflicts: boolean;
@@ -13,7 +13,7 @@ export async function dirtyFilesOverlapWith(
const { git } = createGitInstance(cwd, { credentialConfig: [] });
const [dirtyResult, changedResult] = await Promise.allSettled([
- listPorcelainPaths(git),
+ listPorcelainPaths(git, PORCELAIN_STATUS_ARGS),
listNames(git, ['diff', '--name-only', `HEAD..${targetRef}`]),
]);
diff --git a/packages/server/src/git-handle.ts b/packages/server/src/git-handle.ts
index 4287670f8..56cd32e64 100644
--- a/packages/server/src/git-handle.ts
+++ b/packages/server/src/git-handle.ts
@@ -26,6 +26,7 @@ interface GitHandleOptions {
gitIndexFile?: string;
ghToken?: RelayGhToken;
timeoutMs?: number;
+ abortSignal?: AbortSignal;
}
export interface GitHandle {
@@ -69,6 +70,7 @@ export function buildGitEnv(ghToken?: RelayGhToken): Record<string, string> {
LC_ALL: 'C',
GIT_TERMINAL_PROMPT: '0',
GIT_MERGE_AUTOEDIT: 'no',
+ GIT_OPTIONAL_LOCKS: '0',
};
const path = process.env.PATH ?? process.env.Path;
env.PATH = augmentGitSpawnPath(path, {
@@ -101,7 +103,7 @@ export function applyGitEnv(
}
export function createGitInstance(projectDir: string, options: GitHandleOptions): GitHandle {
- const { credentialConfig, gitIndexFile, ghToken, timeoutMs } = options;
+ const { credentialConfig, gitIndexFile, ghToken, timeoutMs, abortSignal } = options;
const env: Record<string, string | undefined> = buildGitEnv(ghToken);
if (gitIndexFile) {
@@ -120,6 +122,7 @@ export function createGitInstance(projectDir: string, options: GitHandleOptions)
config: gitConfig,
unsafe: { allowUnsafeCredentialHelper: true },
...(timeoutMs === undefined ? {} : { timeout: { block: timeoutMs } }),
+ ...(abortSignal === undefined ? {} : { abort: abortSignal }),
};
const git = simpleGit(gitOptions as Partial<SimpleGitOptions>).env(env as Record<string, string>);
diff --git a/packages/server/src/git-paths.test.ts b/packages/server/src/git-paths.test.ts
index e47019511..97453a0ae 100644
--- a/packages/server/src/git-paths.test.ts
+++ b/packages/server/src/git-paths.test.ts
@@ -1,5 +1,5 @@
import { execSync } from 'node:child_process';
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import simpleGit from 'simple-git';
@@ -7,8 +7,10 @@ import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
listNameStatus,
listNames,
+ listPorcelainEntries,
listPorcelainPaths,
listTreeLongEntries,
+ PORCELAIN_STATUS_ARGS,
parseNameStatusZ,
parsePorcelainEntries,
parsePorcelainPaths,
@@ -192,6 +194,16 @@ describe('path-listing wrappers (real git)', () => {
expect(paths).toEqual([NON_ASCII]);
});
+ test('the shared porcelain args list every file of an untracked directory', async () => {
+ mkdirSync(join(projectDir, 'nested'), { recursive: true });
+ writeFileSync(join(projectDir, 'nested', 'a.md'), 'a\n');
+ writeFileSync(join(projectDir, 'nested', 'b.md'), 'b\n');
+
+ const entries = await listPorcelainEntries(simpleGit(projectDir), PORCELAIN_STATUS_ARGS);
+
+ expect(entries.map((e) => e.path).sort()).toEqual(['nested/a.md', 'nested/b.md']);
+ });
+
test('listTreeLongEntries returns the real UTF-8 path and blob size', async () => {
writeFileSync(join(projectDir, NON_ASCII), 'x\n');
run('git add -A');
diff --git a/packages/server/src/git-paths.ts b/packages/server/src/git-paths.ts
index 2961bcdda..90d787fb5 100644
--- a/packages/server/src/git-paths.ts
+++ b/packages/server/src/git-paths.ts
@@ -1,5 +1,7 @@
import type { SimpleGit } from 'simple-git';
+export const PORCELAIN_STATUS_ARGS = ['status', '--porcelain', '-uall'];
+
export function splitNulSeparatedPaths(out: string): string[] {
return out.split('\0').filter((path) => path.length > 0);
}
@@ -108,14 +110,14 @@ export async function listNames(git: SimpleGit, args: string[]): Promise<string[
export async function listPorcelainPaths(
git: SimpleGit,
- args: string[] = ['status', '--porcelain'],
+ args: string[] = PORCELAIN_STATUS_ARGS,
): Promise<string[]> {
return parsePorcelainPaths(await rawZ(git, args));
}
export async function listPorcelainEntries(
git: SimpleGit,
- args: string[] = ['status', '--porcelain'],
+ args: string[] = PORCELAIN_STATUS_ARGS,
): Promise<PorcelainEntry[]> {
return parsePorcelainEntries(await rawZ(git, args));
}
diff --git a/packages/server/src/git-pathspec-name-invariance.test.ts b/packages/server/src/git-pathspec-name-invariance.test.ts
index be212a9b4..6a7d52580 100644
--- a/packages/server/src/git-pathspec-name-invariance.test.ts
+++ b/packages/server/src/git-pathspec-name-invariance.test.ts
@@ -61,6 +61,7 @@ beforeEach(async () => {
projectDir = join(tmpDir, 'project');
okDir = join(projectDir, '.ok', LOCAL_DIR);
mkdirSync(okDir, { recursive: true });
+ writeFileSync(join(projectDir, '.ok', '.gitignore'), `${LOCAL_DIR}/\n`, 'utf-8');
});
afterEach(async () => {
diff --git a/packages/server/src/git-worktree-status.test.ts b/packages/server/src/git-worktree-status.test.ts
index 8b591beb9..56179094d 100644
--- a/packages/server/src/git-worktree-status.test.ts
+++ b/packages/server/src/git-worktree-status.test.ts
@@ -1,17 +1,79 @@
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ utimesSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { delimiter, join } from 'node:path';
import type { GitWorktreeOpenTarget } from '@inkeep/open-knowledge-core';
import simpleGit from 'simple-git';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { PorcelainEntry } from './git-paths.ts';
import { parsePorcelainEntries } from './git-paths.ts';
import {
+ isExpectedGitAbsence,
partitionPorcelainEntries,
readIncomingEntries,
readWorktreeStatus,
WORKTREE_STATUS_LIST_CAP,
} from './git-worktree-status.ts';
+import { getLogger } from './logger.ts';
+
+const gitInstanceTimeouts = vi.hoisted(() => [] as (number | undefined)[]);
+const gitInstanceAbortSignals = vi.hoisted(() => [] as (AbortSignal | undefined)[]);
+const rawFailure = vi.hoisted(() => ({
+ matches: null as ((args: string[]) => boolean) | null,
+ error: new Error('simulated git crash'),
+}));
+
+vi.mock('./git-handle.ts', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('./git-handle.ts')>();
+ return {
+ ...actual,
+ createGitInstance: (
+ projectDir: string,
+ options: Parameters<typeof actual.createGitInstance>[1],
+ ) => {
+ gitInstanceTimeouts.push(options.timeoutMs);
+ gitInstanceAbortSignals.push(options.abortSignal);
+ const handle = actual.createGitInstance(projectDir, options);
+ const realRaw = handle.git.raw.bind(handle.git);
+ handle.git.raw = ((...args: unknown[]) => {
+ const first = args[0];
+ if (Array.isArray(first) && rawFailure.matches?.(first as string[])) {
+ return Promise.reject(rawFailure.error);
+ }
+ return (realRaw as (...a: unknown[]) => unknown)(...args);
+ }) as typeof handle.git.raw;
+ return handle;
+ },
+ };
+});
+
+const SYNC_ENGINE_GIT_BLOCK_TIMEOUT_MS = 120_000;
+
+function readSpawnedPids(pidFile: string): number[] {
+ if (!existsSync(pidFile)) return [];
+ return readFileSync(pidFile, 'utf8')
+ .split('\n')
+ .map((line) => Number.parseInt(line.trim(), 10))
+ .filter((pid) => Number.isInteger(pid) && pid > 0);
+}
+
+function isProcessAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
const allScoped = () => true;
@@ -103,6 +165,29 @@ describe('partitionPorcelainEntries', () => {
expect(out.truncated).toBe(true);
});
+ test('sync-scoped entries keep their slot when out-of-scope ones exhaust the cap', () => {
+ const many = Array.from({ length: WORKTREE_STATUS_LIST_CAP + 5 }, (_, i) => ({
+ x: '?',
+ y: '?',
+ path: `build/f${String(i).padStart(3, '0')}.md`,
+ }));
+ const out = partition([...many, { x: '?', y: '?', path: 'notes/mine.md' }], (p) =>
+ p.startsWith('notes/'),
+ );
+ expect(out.untracked).toHaveLength(WORKTREE_STATUS_LIST_CAP);
+ expect(out.untracked[0]?.path).toBe('notes/mine.md');
+ expect(out.untracked.map((e) => e.path)).toContain('notes/mine.md');
+ expect(out.truncated).toBe(true);
+ });
+
+ test('ordering within the sync-scoped group is the order git reported', () => {
+ const out = partition(
+ parsePorcelainEntries('?? build/z.md\0?? notes/b.md\0?? notes/a.md\0'),
+ (p) => p.startsWith('notes/'),
+ );
+ expect(out.untracked.map((e) => e.path)).toEqual(['notes/b.md', 'notes/a.md', 'build/z.md']);
+ });
+
test('a listing within the cap is not marked truncated', () => {
const out = partition(parsePorcelainEntries('M a.md\0'));
expect(out.truncated).toBe(false);
@@ -206,6 +291,31 @@ describe('readIncomingEntries', () => {
});
});
+describe('isExpectedGitAbsence', () => {
+ test('admits the three states git reports as absence rather than failure', () => {
+ expect(
+ isExpectedGitAbsence(
+ new Error(
+ "fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.",
+ ),
+ ),
+ ).toBe(true);
+ expect(isExpectedGitAbsence(new Error("fatal: no upstream configured for branch 'main'"))).toBe(
+ true,
+ );
+ expect(isExpectedGitAbsence(new Error('fatal: HEAD does not point to a branch'))).toBe(true);
+ expect(isExpectedGitAbsence(new Error("fatal: no such branch: 'main'"))).toBe(true);
+ });
+
+ test('a real read failure is not absence', () => {
+ expect(isExpectedGitAbsence(new Error('fatal: not a git repository'))).toBe(false);
+ expect(isExpectedGitAbsence(new Error('fatal: Unable to read current working directory'))).toBe(
+ false,
+ );
+ expect(isExpectedGitAbsence(undefined)).toBe(false);
+ });
+});
+
describe('readWorktreeStatus open-target stamping', () => {
let dir: string;
@@ -295,3 +405,353 @@ describe('readWorktreeStatus — an unreadable tree is representable', () => {
expect(status.untracked.map((e) => e.path)).toContain('a.md');
});
});
+
+describe('readWorktreeStatus — the panel listing is trustworthy', () => {
+ let dir: string;
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'ok-worktree-read-'));
+ });
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ async function seededRepo(): Promise<string> {
+ const project = join(dir, 'project');
+ mkdirSync(project, { recursive: true });
+ const g = simpleGit(project);
+ await g.init(['--initial-branch=main']);
+ await g.raw('config', 'user.name', 'Test');
+ await g.raw('config', 'user.email', '[email protected]');
+ writeFileSync(join(project, 'seed.md'), 'v1\n');
+ await g.add('.');
+ await g.commit('seed');
+ return project;
+ }
+
+ test('a brand-new folder is listed as its files, not as one collapsed directory', async () => {
+ const project = await seededRepo();
+ mkdirSync(join(project, 'newdir'), { recursive: true });
+ writeFileSync(join(project, 'newdir/a.md'), 'a\n');
+ writeFileSync(join(project, 'newdir/b.md'), 'b\n');
+
+ const status = await readWorktreeStatus(project, () => true);
+
+ expect(status.untracked.map((e) => e.path).sort()).toEqual(['newdir/a.md', 'newdir/b.md']);
+ });
+
+ test('reading the listing leaves the git index the sync engine writes untouched', async () => {
+ const project = await seededRepo();
+ const stale = new Date(Date.now() - 60_000);
+ utimesSync(join(project, 'seed.md'), stale, stale);
+ const before = statSync(join(project, '.git', 'index'), { bigint: true });
+
+ const status = await readWorktreeStatus(project, () => true);
+
+ const after = statSync(join(project, '.git', 'index'), { bigint: true });
+ expect(status.readable).toBe(true);
+ expect(after.ino).toBe(before.ino);
+ expect(after.mtimeNs).toBe(before.mtimeNs);
+ });
+
+ test('a real tree full of out-of-scope untracked files still lists the sync-scoped one', async () => {
+ const project = await seededRepo();
+ mkdirSync(join(project, 'build'), { recursive: true });
+ for (let i = 0; i < WORKTREE_STATUS_LIST_CAP + 20; i++) {
+ writeFileSync(join(project, 'build', `f${String(i).padStart(3, '0')}.md`), 'x\n');
+ }
+ mkdirSync(join(project, 'notes'), { recursive: true });
+ writeFileSync(join(project, 'notes', 'zzz-mine.md'), 'mine\n');
+
+ const status = await readWorktreeStatus(project, (p) => p.startsWith('notes/'));
+
+ expect(status.untracked).toHaveLength(WORKTREE_STATUS_LIST_CAP);
+ expect(status.untracked.map((e) => e.path)).toContain('notes/zzz-mine.md');
+ expect(status.truncated).toBe(true);
+ });
+
+ test('reading a branch with an upstream also leaves the git index untouched', async () => {
+ const project = await seededRepo();
+ const bare = join(dir, 'bare.git');
+ mkdirSync(bare, { recursive: true });
+ await simpleGit(bare).init(true);
+ await simpleGit(bare).raw('symbolic-ref', 'HEAD', 'refs/heads/main');
+ const g = simpleGit(project);
+ await g.addRemote('origin', bare);
+ await g.push(['--set-upstream', 'origin', 'main']);
+
+ const stale = new Date(Date.now() - 60_000);
+ utimesSync(join(project, 'seed.md'), stale, stale);
+ const before = statSync(join(project, '.git', 'index'), { bigint: true });
+
+ const status = await readWorktreeStatus(project, () => true);
+
+ const after = statSync(join(project, '.git', 'index'), { bigint: true });
+ expect(status.upstream).toBe('origin/main');
+ expect(after.ino).toBe(before.ino);
+ expect(after.mtimeNs).toBe(before.mtimeNs);
+ });
+
+ test.skipIf(process.platform === 'win32')(
+ 'a git that never answers is cut off by the read timeout and reports an unreadable tree',
+ async () => {
+ const project = await seededRepo();
+ const shimDir = join(dir, 'shim');
+ mkdirSync(shimDir, { recursive: true });
+ writeFileSync(join(shimDir, 'git'), '#!/bin/sh\nexec sleep 5\n');
+ chmodSync(join(shimDir, 'git'), 0o755);
+ const realPath = process.env.PATH;
+ process.env.PATH = `${shimDir}${delimiter}${realPath ?? ''}`;
+
+ try {
+ const status = await readWorktreeStatus(project, () => true, undefined, {
+ timeoutMs: 250,
+ });
+
+ expect(status.readable).toBe(false);
+ expect(status.staged).toEqual([]);
+ } finally {
+ process.env.PATH = realPath;
+ }
+ },
+ );
+
+ test('the default read timeout stays far below the sync engine block budget', async () => {
+ const project = await seededRepo();
+ gitInstanceTimeouts.length = 0;
+
+ await readWorktreeStatus(project, () => true);
+
+ expect(gitInstanceTimeouts.length).toBeGreaterThan(0);
+ for (const timeoutMs of gitInstanceTimeouts) {
+ expect(typeof timeoutMs).toBe('number');
+ expect(timeoutMs ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(
+ SYNC_ENGINE_GIT_BLOCK_TIMEOUT_MS / 4,
+ );
+ }
+ });
+
+ test('a silently defaulted branch leg is reported at warn, not swallowed', async () => {
+ const project = await seededRepo();
+ const logger = getLogger('git-worktree-status');
+ const warned: { data: Record<string, unknown>; msg: string }[] = [];
+ const spy = vi.spyOn(logger, 'warn').mockImplementation(((data: unknown, msg?: string) => {
+ warned.push({ data: (data ?? {}) as Record<string, unknown>, msg: msg ?? '' });
+ }) as never);
+ rawFailure.matches = (args) => args[0] === 'rev-parse' && args.at(-1) === 'HEAD';
+
+ try {
+ const status = await readWorktreeStatus(project, () => true);
+
+ expect(status.readable).toBe(true);
+ expect(status.branch).toBeNull();
+ const line = warned.find((entry) => entry.data.event === 'worktree-branch-read-failed');
+ expect(line?.msg.startsWith('[sync] ')).toBe(true);
+ expect(typeof line?.data.elapsedMs).toBe('number');
+ expect(line?.data).toHaveProperty('err');
+ } finally {
+ rawFailure.matches = null;
+ spy.mockRestore();
+ }
+ });
+
+ test('a silently defaulted upstream leg is reported at warn', async () => {
+ const project = await seededRepo();
+ const logger = getLogger('git-worktree-status');
+ const warned: Record<string, unknown>[] = [];
+ const spy = vi.spyOn(logger, 'warn').mockImplementation(((data: unknown) => {
+ warned.push((data ?? {}) as Record<string, unknown>);
+ }) as never);
+ rawFailure.matches = (args) => args[0] === 'rev-parse' && args.at(-1) === '@{upstream}';
+
+ try {
+ const status = await readWorktreeStatus(project, () => true);
+
+ expect(status.readable).toBe(true);
+ expect(status.upstream).toBeNull();
+ expect(warned.map((d) => d.event)).toContain('worktree-upstream-read-failed');
+ } finally {
+ rawFailure.matches = null;
+ spy.mockRestore();
+ }
+ });
+
+ test('a silently defaulted incoming leg is reported at warn', async () => {
+ const project = await seededRepo();
+ const logger = getLogger('git-worktree-status');
+ const warned: Record<string, unknown>[] = [];
+ const spy = vi.spyOn(logger, 'warn').mockImplementation(((data: unknown) => {
+ warned.push((data ?? {}) as Record<string, unknown>);
+ }) as never);
+ rawFailure.matches = (args) => args[0] === 'diff';
+
+ try {
+ const status = await readWorktreeStatus(project, () => true);
+
+ expect(status.readable).toBe(true);
+ expect(status.incoming).toEqual([]);
+ expect(warned.map((d) => d.event)).toContain('worktree-incoming-read-failed');
+ } finally {
+ rawFailure.matches = null;
+ spy.mockRestore();
+ }
+ });
+
+ test('a repo with no upstream defaults quietly — absence is not a failure', async () => {
+ const project = await seededRepo();
+ const logger = getLogger('git-worktree-status');
+ const warned: Record<string, unknown>[] = [];
+ const spy = vi.spyOn(logger, 'warn').mockImplementation(((data: unknown) => {
+ warned.push((data ?? {}) as Record<string, unknown>);
+ }) as never);
+
+ try {
+ const status = await readWorktreeStatus(project, () => true);
+
+ expect(status.upstream).toBeNull();
+ expect(status.incoming).toEqual([]);
+ expect(warned).toEqual([]);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ test('a repo with no commits yet defaults quietly and still reads its listing', async () => {
+ const project = join(dir, 'unborn');
+ mkdirSync(project, { recursive: true });
+ const g = simpleGit(project);
+ await g.init(['--initial-branch=main']);
+ writeFileSync(join(project, 'a.md'), 'x\n');
+ const logger = getLogger('git-worktree-status');
+ const warned: Record<string, unknown>[] = [];
+ const spy = vi.spyOn(logger, 'warn').mockImplementation(((data: unknown) => {
+ warned.push((data ?? {}) as Record<string, unknown>);
+ }) as never);
+
+ try {
+ const status = await readWorktreeStatus(project, () => true);
+
+ expect(status.readable).toBe(true);
+ expect(status.branch).toBeNull();
+ expect(status.untracked.map((e) => e.path)).toContain('a.md');
+ expect(warned).toEqual([]);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ test.skipIf(process.platform === 'win32')(
+ 'aborting a read that is already spawned kills the git process and stays out of the support grep',
+ async () => {
+ const project = await seededRepo();
+ const shimDir = join(dir, 'abort-shim');
+ mkdirSync(shimDir, { recursive: true });
+ const pidFile = join(shimDir, 'pids');
+ writeFileSync(join(shimDir, 'git'), `#!/bin/sh\necho $$ >> "${pidFile}"\nexec sleep 10\n`);
+ chmodSync(join(shimDir, 'git'), 0o755);
+ const realPath = process.env.PATH;
+ process.env.PATH = `${shimDir}${delimiter}${realPath ?? ''}`;
+
+ const logger = getLogger('git-worktree-status');
+ const reported: string[] = [];
+ const errorSpy = vi.spyOn(logger, 'error').mockImplementation(((data: unknown) => {
+ reported.push(String((data as Record<string, unknown>)?.event ?? ''));
+ }) as never);
+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(((data: unknown) => {
+ reported.push(String((data as Record<string, unknown>)?.event ?? ''));
+ }) as never);
+ gitInstanceAbortSignals.length = 0;
+ const controller = new AbortController();
+ let spawnedPids: number[] = [];
+
+ try {
+ const pending = readWorktreeStatus(project, () => true, undefined, {
+ timeoutMs: 30_000,
+ abortSignal: controller.signal,
+ }).then(
+ (value) => ({ ok: true as const, value }),
+ (err: unknown) => ({ ok: false as const, err }),
+ );
+
+ await vi.waitFor(() => {
+ spawnedPids = readSpawnedPids(pidFile);
+ expect(spawnedPids.length).toBeGreaterThan(0);
+ });
+ expect(spawnedPids.every(isProcessAlive)).toBe(true);
+ expect(controller.signal.aborted).toBe(false);
+
+ controller.abort();
+ const settled = await Promise.race([
+ pending,
+ new Promise<'still-running'>((resolve) =>
+ setTimeout(() => resolve('still-running'), 4000),
+ ),
+ ]);
+
+ expect(settled).not.toBe('still-running');
+ expect(settled).toMatchObject({ ok: true, value: { readable: false } });
+ expect(gitInstanceAbortSignals.some((s) => s?.aborted === true)).toBe(true);
+ expect(reported).toEqual([]);
+ await vi.waitFor(() => {
+ expect(readSpawnedPids(pidFile).filter(isProcessAlive)).toEqual([]);
+ });
+ } finally {
+ for (const pid of readSpawnedPids(pidFile)) {
+ if (isProcessAlive(pid)) process.kill(pid, 'SIGKILL');
+ }
+ process.env.PATH = realPath;
+ errorSpy.mockRestore();
+ warnSpy.mockRestore();
+ }
+ },
+ 20_000,
+ );
+
+ test('a signal already aborted when the read starts never spawns git and stays quiet', async () => {
+ const project = await seededRepo();
+ const logger = getLogger('git-worktree-status');
+ const reported: string[] = [];
+ const errorSpy = vi.spyOn(logger, 'error').mockImplementation(((data: unknown) => {
+ reported.push(String((data as Record<string, unknown>)?.event ?? ''));
+ }) as never);
+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(((data: unknown) => {
+ reported.push(String((data as Record<string, unknown>)?.event ?? ''));
+ }) as never);
+ gitInstanceAbortSignals.length = 0;
+
+ try {
+ const status = await readWorktreeStatus(project, () => true, undefined, {
+ abortSignal: AbortSignal.abort(),
+ });
+
+ expect(status.readable).toBe(false);
+ expect(gitInstanceAbortSignals.some((s) => s?.aborted === true)).toBe(true);
+ expect(reported).toEqual([]);
+ } finally {
+ errorSpy.mockRestore();
+ warnSpy.mockRestore();
+ }
+ });
+
+ test('an unreadable tree is reported to support with its duration and branch', async () => {
+ const project = await seededRepo();
+ const logger = getLogger('git-worktree-status');
+ const reported: { data: Record<string, unknown>; msg: string }[] = [];
+ const spy = vi.spyOn(logger, 'error').mockImplementation(((data: unknown, msg?: string) => {
+ reported.push({ data: (data ?? {}) as Record<string, unknown>, msg: msg ?? '' });
+ }) as never);
+
+ try {
+ rmSync(join(project, '.git'), { recursive: true, force: true });
+ const status = await readWorktreeStatus(project, () => true);
+
+ expect(status.readable).toBe(false);
+ const line = reported.find((entry) => entry.msg.includes('worktree status read failed'));
+ expect(line?.msg.startsWith('[sync] ')).toBe(true);
+ expect(typeof line?.data.elapsedMs).toBe('number');
+ expect(line?.data).toHaveProperty('branch');
+ expect(line?.data).toHaveProperty('err');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+});
diff --git a/packages/server/src/git-worktree-status.ts b/packages/server/src/git-worktree-status.ts
index 9415785e7..e9304083e 100644
--- a/packages/server/src/git-worktree-status.ts
+++ b/packages/server/src/git-worktree-status.ts
@@ -6,13 +6,20 @@ import type {
import { GIT_STATUS_CODES } from '@inkeep/open-knowledge-core';
import type { SimpleGit } from 'simple-git';
import { createGitInstance } from './git-handle.ts';
-import { listNameStatus, listPorcelainEntries, type PorcelainEntry } from './git-paths.ts';
+import {
+ listNameStatus,
+ listPorcelainEntries,
+ PORCELAIN_STATUS_ARGS,
+ type PorcelainEntry,
+} from './git-paths.ts';
import { getLogger } from './logger.ts';
const log = getLogger('git-worktree-status');
export const WORKTREE_STATUS_LIST_CAP = 100;
+const WORKTREE_STATUS_TIMEOUT_MS = 10_000;
+
export interface WorktreeStatus {
readable: boolean;
branch: string | null;
@@ -67,19 +74,46 @@ export function partitionPorcelainEntries(
notStaged.length > WORKTREE_STATUS_LIST_CAP ||
untracked.length > WORKTREE_STATUS_LIST_CAP;
+ const syncScopedFirst = (bucket: GitWorktreeEntry[]): GitWorktreeEntry[] =>
+ [...bucket.filter((e) => e.syncScoped), ...bucket.filter((e) => !e.syncScoped)].slice(
+ 0,
+ WORKTREE_STATUS_LIST_CAP,
+ );
+
return {
- staged: staged.slice(0, WORKTREE_STATUS_LIST_CAP),
- notStaged: notStaged.slice(0, WORKTREE_STATUS_LIST_CAP),
- untracked: untracked.slice(0, WORKTREE_STATUS_LIST_CAP),
+ staged: syncScopedFirst(staged),
+ notStaged: syncScopedFirst(notStaged),
+ untracked: syncScopedFirst(untracked),
truncated,
};
}
-export async function readIncomingEntries(git: SimpleGit): Promise<GitWorktreeEntry[]> {
+const EXPECTED_GIT_ABSENCE_MESSAGES = [
+ 'unknown revision or path not in the working tree',
+ 'no upstream configured for branch',
+ 'does not point to a branch',
+ 'no such branch',
+] as const;
+
+export function isExpectedGitAbsence(err: unknown): boolean {
+ const message = err instanceof Error ? err.message : String(err ?? '');
+ return EXPECTED_GIT_ABSENCE_MESSAGES.some((known) => message.includes(known));
+}
+
+export async function readIncomingEntries(
+ git: SimpleGit,
+ abortSignal?: AbortSignal,
+): Promise<GitWorktreeEntry[]> {
let rows: Awaited<ReturnType<typeof listNameStatus>>;
try {
rows = await listNameStatus(git, ['diff', '--name-status', 'HEAD...@{upstream}']);
- } catch {
+ } catch (err) {
+ if (!abortSignal?.aborted && !isExpectedGitAbsence(err)) {
+ log.warn(
+ { event: 'worktree-incoming-read-failed', err },
+ '[sync] incoming-change read failed — panel shows nothing incoming',
+ );
+ }
return [];
}
return rows.map((row) => ({
@@ -90,6 +124,11 @@ export async function readIncomingEntries(git: SimpleGit): Promise<GitWorktreeEn
}));
}
+export interface ReadWorktreeStatusOptions {
+ timeoutMs?: number;
+ abortSignal?: AbortSignal;
+}
+
/**
* It is threaded in rather than recomputed here so the answer comes from the sync engine's own
* admission predicate — the same one the staging walk consults (precedent #55).
@@ -98,6 +137,7 @@ export async function readWorktreeStatus(
projectDir: string,
isSyncScoped: (projectRelPath: string) => boolean,
toOpenTarget?: (projectRelPath: string) => GitWorktreeOpenTarget | undefined,
+ options: ReadWorktreeStatusOptions = {},
): Promise<WorktreeStatus> {
const empty: WorktreeStatus = {
readable: true,
@@ -111,23 +151,64 @@ export async function readWorktreeStatus(
truncated: false,
};
- const { git } = createGitInstance(projectDir, { credentialConfig: [] });
+ const { git } = createGitInstance(projectDir, {
+ credentialConfig: [],
+ timeoutMs: options.timeoutMs ?? WORKTREE_STATUS_TIMEOUT_MS,
+ ...(options.abortSignal === undefined ? {} : { abortSignal: options.abortSignal }),
+ });
+ const startedAt = Date.now();
const [entriesResult, branchResult, upstreamResult, incomingResult] = await Promise.allSettled([
- listPorcelainEntries(git),
+ listPorcelainEntries(git, PORCELAIN_STATUS_ARGS),
git.raw(['rev-parse', '--symbolic-full-name', '--abbrev-ref', 'HEAD']),
git.raw(['rev-parse', '--symbolic-full-name', '--abbrev-ref', '@{upstream}']),
- readIncomingEntries(git),
+ readIncomingEntries(git, options.abortSignal),
]);
- if (entriesResult.status === 'rejected') {
- log.warn({ err: entriesResult.reason }, '[git-status] porcelain read failed');
- return { ...empty, readable: false };
- }
-
const headRef = branchResult.status === 'fulfilled' ? branchResult.value.trim() : '';
const detached = headRef === 'HEAD';
const branch = detached || headRef === '' ? null : headRef;
+ const cancelled = options.abortSignal?.aborted === true;
+ const repoUnreadable = entriesResult.status === 'rejected';
+
+ const reportDefaultedLeg = (
+ result: PromiseSettledResult<unknown>,
+ event: string,
+ msg: string,
+ ): void => {
+ if (result.status !== 'rejected') return;
+ if (cancelled || repoUnreadable || isExpectedGitAbsence(result.reason)) return;
+ log.warn(
+ { event, err: result.reason, elapsedMs: Date.now() - startedAt, branch },
+ `[sync] ${msg}`,
+ );
+ };
+
+ reportDefaultedLeg(
+ branchResult,
+ 'worktree-branch-read-failed',
+ 'branch read failed — panel shows no branch',
+ );
+ reportDefaultedLeg(
+ upstreamResult,
+ 'worktree-upstream-read-failed',
+ 'upstream read failed — panel shows no upstream',
+ );
+
+ if (entriesResult.status === 'rejected') {
+ if (!cancelled) {
+ log.error(
+ {
+ event: 'worktree-read-failed',
+ err: entriesResult.reason,
+ elapsedMs: Date.now() - startedAt,
+ branch,
+ },
+ '[sync] worktree status read failed — panel listing marked unreadable',
+ );
+ }
+ return { ...empty, readable: false };
+ }
const upstream =
upstreamResult.status === 'fulfilled' ? upstreamResult.value.trim() || null : null;
diff --git a/packages/server/src/http/git-routes.test.ts b/packages/server/src/http/git-routes.test.ts
index ac19865db..a5062e95b 100644
--- a/packages/server/src/http/git-routes.test.ts
+++ b/packages/server/src/http/git-routes.test.ts
@@ -1,7 +1,45 @@
-import { describe, expect, test } from 'vitest';
+import { createServer } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { describe, expect, test, vi } from 'vitest';
import type { FileIndexEntry } from '../file-watcher.ts';
+import { getLogger } from '../logger.ts';
import { createGitRoutes } from './git-routes.ts';
+const worktreeReadCalls = vi.hoisted(() => [] as (AbortSignal | undefined)[]);
+
+vi.mock('../git-worktree-status.ts', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../git-worktree-status.ts')>();
+ return {
+ ...actual,
+ readWorktreeStatus: (
+ _projectDir: string,
+ _isSyncScoped: unknown,
+ _toOpenTarget: unknown,
+ options: { abortSignal?: AbortSignal } = {},
+ ) => {
+ worktreeReadCalls.push(options.abortSignal);
+ return new Promise((resolve) => {
+ options.abortSignal?.addEventListener(
+ 'abort',
+ () =>
+ resolve({
+ readable: false,
+ branch: null,
+ detached: false,
+ upstream: null,
+ staged: [],
+ notStaged: [],
+ untracked: [],
+ incoming: [],
+ truncated: false,
+ }),
+ { once: true },
+ );
+ });
+ },
+ };
+});
+
function buildGroup() {
return createGitRoutes({
projectDir: undefined,
@@ -30,3 +68,70 @@ describe('createGitRoutes table', () => {
}
});
});
+
+describe('worktree-status cancels its git work when the client gives up', () => {
+ test('a client abort aborts the signal the read was given', async () => {
+ worktreeReadCalls.length = 0;
+ const dispatch = buildGroup().table.resolve('/api/git/worktree-status')?.dispatch;
+ expect(dispatch).toBeDefined();
+
+ const server = createServer((req, res) => {
+ void dispatch?.(req, res).catch(() => undefined);
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address() as AddressInfo;
+
+ const controller = new AbortController();
+ const pending = fetch(`http://127.0.0.1:${port}/api/git/worktree-status`, {
+ signal: controller.signal,
+ }).catch(() => undefined);
+
+ await vi.waitFor(() => expect(worktreeReadCalls).toHaveLength(1));
+ const signal = worktreeReadCalls[0];
+ expect(signal?.aborted).toBe(false);
+
+ controller.abort();
+ await pending;
+ await vi.waitFor(() => expect(signal?.aborted).toBe(true));
+
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ test('a client abort writes nothing to the support grep once the read settles', async () => {
+ worktreeReadCalls.length = 0;
+ const log = getLogger('http');
+ const reported: Record<string, unknown>[] = [];
+ const errorSpy = vi.spyOn(log, 'error').mockImplementation(((data: unknown) => {
+ reported.push((data ?? {}) as Record<string, unknown>);
+ }) as never);
+ const dispatch = buildGroup().table.resolve('/api/git/worktree-status')?.dispatch;
+ const settled: unknown[] = [];
+
+ const server = createServer((req, res) => {
+ void dispatch?.(req, res).then(
+ () => settled.push('ok'),
+ (err) => settled.push(err),
+ );
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address() as AddressInfo;
+
+ try {
+ const controller = new AbortController();
+ const pending = fetch(`http://127.0.0.1:${port}/api/git/worktree-status`, {
+ signal: controller.signal,
+ }).catch(() => undefined);
+
+ await vi.waitFor(() => expect(worktreeReadCalls).toHaveLength(1));
+ controller.abort();
+ await pending;
+ await vi.waitFor(() => expect(settled).toHaveLength(1));
+
+ expect(settled[0]).toBe('ok');
+ expect(reported).toEqual([]);
+ } finally {
+ errorSpy.mockRestore();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+ });
+});
diff --git a/packages/server/src/http/git-routes.ts b/packages/server/src/http/git-routes.ts
index 321b95876..011554217 100644
--- a/packages/server/src/http/git-routes.ts
+++ b/packages/server/src/http/git-routes.ts
@@ -82,16 +82,29 @@ export function createGitRoutes(deps: GitRouteDeps): ApiRouteGroup {
});
return;
}
+ const clientGone = new AbortController();
+ res.on('close', () => {
+ if (!res.writableEnded) clientGone.abort();
+ });
try {
const engine = getSyncEngine?.();
const isSyncScoped = engine
? (relPath: string) => engine.isSyncScopedPath(relPath)
: () => false;
- const status = await readWorktreeStatus(projectDir ?? contentDir, isSyncScoped, toOpenTarget);
+ const status = await readWorktreeStatus(
+ projectDir ?? contentDir,
+ isSyncScoped,
+ toOpenTarget,
+ {
+ abortSignal: clientGone.signal,
+ },
+ );
+ if (res.writableEnded || res.destroyed) return;
successResponse(res, 200, GitWorktreeStatusSuccessSchema, status, {
handler: 'git-worktree-status',
});
} catch (e) {
+ if (res.writableEnded || res.destroyed) return;
errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Internal server error.', {
handler: 'git-worktree-status',
cause: e,
diff --git a/packages/server/src/share/freshness.ts b/packages/server/src/share/freshness.ts
index 5e2d927eb..74b9f9941 100644
--- a/packages/server/src/share/freshness.ts
+++ b/packages/server/src/share/freshness.ts
@@ -1,6 +1,7 @@
import { pathspecArgs, type ShareFreshness } from '@inkeep/open-knowledge-core';
import { truncateError } from '../error-format.ts';
import { createGitInstance } from '../git-handle.ts';
+import { PORCELAIN_STATUS_ARGS } from '../git-paths.ts';
import { getLogger } from '../logger.ts';
const FRESHNESS_PROBE_TIMEOUT_MS = 5_000;
@@ -28,7 +29,7 @@ export async function computeShareFreshness(
.then(() => true)
.catch(() => false),
git.raw(['diff', '--name-only', ref, ...scope]),
- git.raw(['status', '--porcelain', '--untracked-files=all', ...scope]),
+ git.raw([...PORCELAIN_STATUS_ARGS, ...scope]),
]);
if (!present) {
diff --git a/packages/server/src/sync-engine.index-heal.test.ts b/packages/server/src/sync-engine.index-heal.test.ts
new file mode 100644
index 000000000..e7d8e1b84
--- /dev/null
+++ b/packages/server/src/sync-engine.index-heal.test.ts
@@ -0,0 +1,1050 @@
+import {
+ appendFileSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { LOCAL_DIR, type SyncMode } from '@inkeep/open-knowledge-core';
+import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { getLogger } from './logger.ts';
+import { SyncEngine } from './sync-engine.ts';
+
+const stubContentFilter = {
+ isExcluded: (_path: string) => false,
+ isDirExcluded: (_path: string) => false,
+};
+
+interface CapturedLog {
+ data: Record<string, unknown>;
+ msg: string;
+ level: 'info' | 'warn' | 'error';
+}
+
+function captureSyncLogs(): { entries: CapturedLog[]; restore: () => void } {
+ const entries: CapturedLog[] = [];
+ const logger = getLogger('sync-engine');
+ const record =
+ (level: CapturedLog['level']) =>
+ (data: unknown, msg?: string): void => {
+ entries.push({ data: (data ?? {}) as Record<string, unknown>, msg: msg ?? '', level });
+ };
+ const infoSpy = vi.spyOn(logger, 'info').mockImplementation(record('info') as never);
+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(record('warn') as never);
+ const errorSpy = vi.spyOn(logger, 'error').mockImplementation(record('error') as never);
+ return {
+ entries,
+ restore: () => {
+ infoSpy.mockRestore();
+ warnSpy.mockRestore();
+ errorSpy.mockRestore();
+ },
+ };
+}
+
+let tmpDir = '';
+let projectDir = '';
+let okDir = '';
+
+beforeEach(() => {
+ tmpDir = mkdtempSync(join(tmpdir(), 'sync-engine-index-heal-'));
+ projectDir = join(tmpDir, 'project');
+ okDir = join(projectDir, '.ok', LOCAL_DIR);
+ mkdirSync(projectDir, { recursive: true });
+ mkdirSync(okDir, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(tmpDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+});
+
+function ignoreOkDir(): void {
+ appendFileSync(join(projectDir, '.git', 'info', 'exclude'), '\n.ok/\n', 'utf-8');
+}
+
+function lockPath(): string {
+ return join(projectDir, '.git', 'index.lock');
+}
+
+function statePath(): string {
+ return join(okDir, 'sync-state.json');
+}
+
+async function projectWithBareOrigin() {
+ const bare = join(tmpDir, 'bare.git');
+ mkdirSync(bare, { recursive: true });
+ await simpleGit(bare).init(true);
+ await simpleGit(bare).raw('symbolic-ref', 'HEAD', 'refs/heads/main');
+
+ const git = simpleGit(projectDir);
+ await git.init(['--initial-branch=main']);
+ ignoreOkDir();
+ await git.raw('config', 'user.name', 'Test');
+ await git.raw('config', 'user.email', '[email protected]');
+ writeFileSync(join(projectDir, 'doc.md'), 'v1\n', 'utf-8');
+ await git.add('.');
+ await git.commit('seed');
+ await git.addRemote('origin', bare);
+ await git.push(['--set-upstream', 'origin', 'main']);
+ return { git, bare };
+}
+
+function makeEngine(
+ opts: { mode?: SyncMode; _beforeRealIndexResetRetry?: () => void | Promise<void> } = {},
+) {
+ return new SyncEngine({
+ projectDir,
+ contentDir: projectDir,
+ contentFilter: stubContentFilter,
+ mode: opts.mode ?? 'off',
+ pullIntervalSeconds: 99999,
+ pushIntervalSeconds: 99999,
+ _beforeRealIndexResetRetry: opts._beforeRealIndexResetRetry,
+ });
+}
+
+async function advanceOriginFromSisterClone(bare: string): Promise<void> {
+ const sister = join(tmpDir, 'sister');
+ await simpleGit().clone(bare, sister);
+ const sg = simpleGit(sister);
+ await sg.raw('config', 'user.name', 'Sister');
+ await sg.raw('config', 'user.email', '[email protected]');
+ writeFileSync(join(sister, 'doc.md'), 'upstream\n', 'utf-8');
+ await sg.add('doc.md');
+ await sg.commit('sister edit');
+ await sg.push();
+}
+
+async function originHeadMessage(bare: string): Promise<string> {
+ return (await simpleGit(bare).raw(['log', '-1', '--format=%s', 'main'])).trim();
+}
+
+async function healPaths(engine: SyncEngine, paths: string[]): Promise<void> {
+ const internal = engine as unknown as {
+ healStaleRealIndex: (paths: string[], committed: ReadonlySet<string>) => Promise<void>;
+ };
+ await internal.healStaleRealIndex(paths, new Set<string>());
+}
+
+describe('SyncEngine real-index reset after a landed push', () => {
+ test('a reset blocked by a held index lock is logged once with the paths and branch', async () => {
+ const { git, bare } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ await git.add('doc.md');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeFileSync(lockPath(), '', 'utf-8');
+ await engine.pushOnce();
+
+ expect(await originHeadMessage(bare)).toContain('doc.md');
+ expect(engine.getStatus().pushError).toBeUndefined();
+
+ const errors = logs.entries.filter(
+ (e) => e.level === 'error' && e.data.event === 'stale-index-reset',
+ );
+ expect(errors).toHaveLength(1);
+ expect(errors[0]?.data).toMatchObject({
+ outcome: 'failed',
+ branch: 'main',
+ pathCount: 1,
+ paths: ['doc.md'],
+ });
+ expect(errors[0]?.msg).toContain('[sync] stale-index reset failed');
+ expect(logs.entries.filter((e) => e.data.event === 'stale-index-reset')).toHaveLength(1);
+ } finally {
+ rmSync(lockPath(), { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a lock released between attempts lets the retry clear the index without a second error', async () => {
+ const { git, bare } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ await git.add('doc.md');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine({
+ _beforeRealIndexResetRetry: () => {
+ rmSync(lockPath(), { force: true });
+ },
+ });
+ try {
+ await engine.start();
+ writeFileSync(lockPath(), '', 'utf-8');
+ await engine.pushOnce();
+
+ expect(await originHeadMessage(bare)).toContain('doc.md');
+ expect(engine.getStatus().pushError).toBeUndefined();
+ expect(existsSync(lockPath())).toBe(false);
+
+ const porcelain = await simpleGit(projectDir).raw(['status', '--porcelain']);
+ expect(porcelain.trim()).toBe('');
+
+ expect(
+ logs.entries.filter((e) => e.level === 'error' && e.data.event === 'stale-index-reset'),
+ ).toHaveLength(0);
+ const recovered = logs.entries.filter(
+ (e) => e.level === 'warn' && e.data.event === 'stale-index-reset',
+ );
+ expect(recovered).toHaveLength(1);
+ expect(recovered[0]?.data).toMatchObject({
+ outcome: 'recovered-on-retry',
+ paths: ['doc.md'],
+ });
+ expect(recovered[0]?.msg).toContain('the panel listing is current');
+ } finally {
+ rmSync(lockPath(), { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('an unobstructed push clears the real index and logs no reset error', async () => {
+ const { git, bare } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ await git.add('doc.md');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await engine.pushOnce();
+
+ expect(await originHeadMessage(bare)).toContain('doc.md');
+ const porcelain = await simpleGit(projectDir).raw(['status', '--porcelain']);
+ expect(porcelain.trim()).toBe('');
+ expect(logs.entries.filter((e) => e.data.event === 'stale-index-reset')).toHaveLength(0);
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+});
+
+describe('SyncEngine self-heal across every push-cycle exit', () => {
+ test('a path left stale by a blocked reset is cleared by the next push cycle', async () => {
+ const { bare } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeFileSync(lockPath(), '', 'utf-8');
+ await engine.pushOnce();
+ rmSync(lockPath(), { force: true });
+
+ expect(await originHeadMessage(bare)).toContain('doc.md');
+ expect((await simpleGit(projectDir).raw(['status', '--porcelain'])).trim()).not.toBe('');
+
+ await engine.pushOnce();
+
+ expect((await simpleGit(projectDir).raw(['status', '--porcelain'])).trim()).toBe('');
+
+ const heals = logs.entries.filter(
+ (e) => e.level === 'warn' && e.data.event === 'self-heal-applied',
+ );
+ expect(heals).toHaveLength(1);
+ expect(heals[0]?.data).toMatchObject({ branch: 'main', pathCount: 1, paths: ['doc.md'] });
+ } finally {
+ rmSync(lockPath(), { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+ test('a staged edit whose file was restored to HEAD content is cleared by the push cycle', async () => {
+ const { git } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ await git.add('doc.md');
+ writeFileSync(join(projectDir, 'doc.md'), 'v1\n', 'utf-8');
+ expect((await git.raw(['status', '--porcelain'])).trim()).toBe('MM doc.md');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await engine.pushOnce();
+
+ expect((await simpleGit(projectDir).raw(['status', '--porcelain'])).trim()).toBe('');
+ const heals = logs.entries.filter((e) => e.data.event === 'self-heal-applied');
+ expect(heals).toHaveLength(1);
+ expect(heals[0]?.data).toMatchObject({ paths: ['doc.md'] });
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a Git operation that begins mid-cycle stops the self-heal from resetting promised paths', async () => {
+ const { git } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ await git.add('doc.md');
+ writeFileSync(join(projectDir, 'doc.md'), 'v1\n', 'utf-8');
+ const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeFileSync(markerPath, (await git.revparse('HEAD')).trim(), 'utf-8');
+ await healPaths(engine, ['doc.md']);
+
+ expect((await git.raw(['status', '--porcelain'])).trim()).toBe('MM doc.md');
+ expect(logs.entries.filter((e) => e.data.event === 'self-heal-applied')).toHaveLength(0);
+ const skipped = logs.entries.filter(
+ (e) => e.level === 'warn' && e.data.event === 'self-heal-skipped-git-operation',
+ );
+ expect(skipped).toHaveLength(1);
+ expect(skipped[0]?.data).toMatchObject({ branch: 'main', pathCount: 1, paths: ['doc.md'] });
+
+ rmSync(markerPath, { force: true });
+ await healPaths(engine, ['doc.md']);
+
+ expect((await git.raw(['status', '--porcelain'])).trim()).toBe('');
+ expect(logs.entries.filter((e) => e.data.event === 'self-heal-applied')).toHaveLength(1);
+ } finally {
+ rmSync(markerPath, { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a push cycle refused for a Git operation never reaches the heal step', async () => {
+ const { git } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ await git.add('doc.md');
+ writeFileSync(join(projectDir, 'doc.md'), 'v1\n', 'utf-8');
+ const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeFileSync(markerPath, (await git.revparse('HEAD')).trim(), 'utf-8');
+ await engine.pushOnce();
+
+ expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');
+ expect((await git.raw(['status', '--porcelain'])).trim()).toBe('MM doc.md');
+ expect(
+ logs.entries.filter(
+ (e) =>
+ e.data.event === 'self-heal-applied' ||
+ e.data.event === 'self-heal-skipped-git-operation',
+ ),
+ ).toHaveLength(0);
+
+ rmSync(markerPath, { force: true });
+ await engine.pushOnce();
+
+ expect((await git.raw(['status', '--porcelain'])).trim()).toBe('');
+ expect(logs.entries.filter((e) => e.data.event === 'self-heal-applied')).toHaveLength(1);
+ } finally {
+ rmSync(markerPath, { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a re-edited path and a pending deletion both stay listed, with no error line', async () => {
+ const { git } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'other.md'), 'kept\n', 'utf-8');
+ writeFileSync(join(projectDir, 'gone.md'), 'kept\n', 'utf-8');
+ await git.add('.');
+ await git.commit('more files');
+ writeFileSync(join(projectDir, 'other.md'), 'edited again\n', 'utf-8');
+ rmSync(join(projectDir, 'gone.md'), { force: true });
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await healPaths(engine, ['other.md', 'gone.md']);
+
+ const porcelain = (await git.raw(['status', '--porcelain'])).trimEnd().split('\n').sort();
+ expect(porcelain).toEqual([' D gone.md', ' M other.md']);
+
+ expect(logs.entries.filter((e) => e.data.event === 'self-heal-applied')).toHaveLength(0);
+ expect(
+ logs.entries.filter((e) => String(e.data.event ?? '').startsWith('self-heal')),
+ ).toHaveLength(0);
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a path git reports as unmerged is never promised to the heal step', async () => {
+ const { git } = await projectWithBareOrigin();
+ await git.raw(['checkout', '-b', 'sister']);
+ writeFileSync(join(projectDir, 'doc.md'), 'sister\n', 'utf-8');
+ await git.add('doc.md');
+ await git.commit('sister edit');
+ await git.raw(['checkout', 'main']);
+ writeFileSync(join(projectDir, 'doc.md'), 'mine\n', 'utf-8');
+ await git.add('doc.md');
+ await git.commit('my edit');
+
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await git.raw(['merge', 'sister']).catch(() => undefined);
+ expect((await git.raw(['status', '--porcelain'])).trim()).toContain('UU doc.md');
+
+ const internal = engine as unknown as { snapshotPromisedPaths: () => Promise<string[]> };
+ expect(await internal.snapshotPromisedPaths()).toEqual([]);
+ } finally {
+ await git.raw(['merge', '--abort']).catch(() => undefined);
+ await engine.destroy();
+ }
+ });
+
+ test('an add/add unmerged path is never promised to the heal step', async () => {
+ const { git } = await projectWithBareOrigin();
+ await git.raw(['checkout', '-b', 'sister']);
+ writeFileSync(join(projectDir, 'both.md'), 'sister\n', 'utf-8');
+ await git.add('both.md');
+ await git.commit('sister adds both.md');
+ await git.raw(['checkout', 'main']);
+ writeFileSync(join(projectDir, 'both.md'), 'mine\n', 'utf-8');
+ await git.add('both.md');
+ await git.commit('main adds both.md');
+
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await git.raw(['merge', 'sister']).catch(() => undefined);
+ expect((await git.raw(['status', '--porcelain'])).trim()).toContain('AA both.md');
+
+ const internal = engine as unknown as { snapshotPromisedPaths: () => Promise<string[]> };
+ expect(await internal.snapshotPromisedPaths()).toEqual([]);
+ } finally {
+ await git.raw(['merge', '--abort']).catch(() => undefined);
+ await engine.destroy();
+ }
+ });
+
+ test('a both-deleted unmerged path is never promised to the heal step', async () => {
+ const { git } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'orig.md'), 'body\n', 'utf-8');
+ await git.add('orig.md');
+ await git.commit('seed orig.md');
+
+ await git.raw(['checkout', '-b', 'sister']);
+ await git.raw(['mv', 'orig.md', 'sister-name.md']);
+ await git.commit('sister renames orig.md');
+ await git.raw(['checkout', 'main']);
+ await git.raw(['mv', 'orig.md', 'main-name.md']);
+ await git.commit('main renames orig.md');
+
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await git.raw(['merge', 'sister']).catch(() => undefined);
+ const porcelain = (await git.raw(['status', '--porcelain'])).trimEnd().split('\n').sort();
+ expect(porcelain).toEqual(['AU main-name.md', 'DD orig.md', 'UA sister-name.md']);
+
+ const internal = engine as unknown as { snapshotPromisedPaths: () => Promise<string[]> };
+ expect(await internal.snapshotPromisedPaths()).toEqual([]);
+ } finally {
+ await git.raw(['merge', '--abort']).catch(() => undefined);
+ await engine.destroy();
+ }
+ });
+
+ test('more stale paths than the cap heal one capped batch per cycle, logging 20 paths', async () => {
+ const { git } = await projectWithBareOrigin();
+ const names = Array.from({ length: 105 }, (_, i) => `f${String(i).padStart(3, '0')}.md`);
+ for (const name of names) writeFileSync(join(projectDir, name), 'v1\n', 'utf-8');
+ await git.add('.');
+ await git.commit('seed the capped fixture');
+ await git.push();
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+
+ for (const name of names) writeFileSync(join(projectDir, name), 'v2\n', 'utf-8');
+ writeFileSync(lockPath(), '', 'utf-8');
+ await engine.pushOnce();
+ rmSync(lockPath(), { force: true });
+
+ const stale = (await git.raw(['status', '--porcelain'])).trimEnd().split('\n');
+ expect(stale).toHaveLength(names.length);
+
+ logs.entries.length = 0;
+ await engine.pushOnce();
+
+ const heals = logs.entries.filter(
+ (e) => e.level === 'warn' && e.data.event === 'self-heal-applied',
+ );
+ expect(heals).toHaveLength(1);
+ expect(heals[0]?.data.pathCount).toBe(100);
+ expect(heals[0]?.data.paths).toHaveLength(20);
+ expect(heals[0]?.data.paths).toEqual(names.slice(0, 20));
+
+ const remainder = (await git.raw(['status', '--porcelain'])).trimEnd().split('\n');
+ expect(remainder).toHaveLength(5);
+
+ await engine.pushOnce();
+ expect((await git.raw(['status', '--porcelain'])).trim()).toBe('');
+ } finally {
+ rmSync(lockPath(), { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a cycle that commits one path also heals a different path left stale', async () => {
+ const { git, bare } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'a.md'), 'a1\n', 'utf-8');
+ writeFileSync(join(projectDir, 'b.md'), 'b1\n', 'utf-8');
+ await git.add('.');
+ await git.commit('seed a and b');
+ await git.push();
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+
+ writeFileSync(join(projectDir, 'a.md'), 'a2\n', 'utf-8');
+ writeFileSync(lockPath(), '', 'utf-8');
+ await engine.pushOnce();
+ rmSync(lockPath(), { force: true });
+
+ writeFileSync(join(projectDir, 'b.md'), 'b2\n', 'utf-8');
+ const before = (await git.raw(['status', '--porcelain'])).trimEnd().split('\n').sort();
+ expect(before).toEqual([' M b.md', 'MM a.md']);
+
+ await engine.pushOnce();
+
+ expect((await git.raw(['status', '--porcelain'])).trim()).toBe('');
+ expect(await originHeadMessage(bare)).toContain('b.md');
+
+ const heals = logs.entries.filter((e) => e.data.event === 'self-heal-applied');
+ expect(heals).toHaveLength(1);
+ expect(heals[0]?.data).toMatchObject({ paths: ['a.md'] });
+ } finally {
+ rmSync(lockPath(), { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a symlink stale only in the index heals, while re-pointed symlinks stay listed', async () => {
+ const { git } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'target.md'), 'target body\n', 'utf-8');
+ writeFileSync(join(projectDir, 'decoy.md'), 'target.md', 'utf-8');
+ writeFileSync(join(projectDir, 'shared.md'), 'shared\n', 'utf-8');
+ writeFileSync(join(projectDir, 'was-file.md'), 'shared\n', 'utf-8');
+ symlinkSync('target.md', join(projectDir, 'link.md'));
+ symlinkSync('target.md', join(projectDir, 'stale-link.md'));
+ symlinkSync('missing.md', join(projectDir, 'dangling.md'));
+ await git.add('.');
+ await git.commit('symlink fixture');
+
+ rmSync(join(projectDir, 'link.md'), { force: true });
+ symlinkSync('decoy.md', join(projectDir, 'link.md'));
+ rmSync(join(projectDir, 'was-file.md'), { force: true });
+ symlinkSync('shared.md', join(projectDir, 'was-file.md'));
+
+ rmSync(join(projectDir, 'stale-link.md'), { force: true });
+ symlinkSync('decoy.md', join(projectDir, 'stale-link.md'));
+ await git.add('stale-link.md');
+ rmSync(join(projectDir, 'stale-link.md'), { force: true });
+ symlinkSync('target.md', join(projectDir, 'stale-link.md'));
+ expect((await git.raw(['status', '--porcelain', '--', 'stale-link.md'])).trim()).toBe(
+ 'MM stale-link.md',
+ );
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+
+ await healPaths(engine, ['link.md', 'dangling.md', 'was-file.md', 'stale-link.md']);
+
+ const after = (await git.raw(['status', '--porcelain'])).trimEnd().split('\n').sort();
+ expect(after).toEqual([' M link.md', ' T was-file.md']);
+
+ const heals = logs.entries.filter(
+ (e) => e.level === 'warn' && e.data.event === 'self-heal-applied',
+ );
+ expect(heals).toHaveLength(1);
+ expect(heals[0]?.data).toMatchObject({ paths: ['stale-link.md'] });
+ expect(logs.entries.filter((e) => e.data.event === 'self-heal-skipped')).toHaveLength(0);
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a push that only forwards existing commits still heals a stale real-index entry', async () => {
+ const { git, bare } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ await git.add('doc.md');
+ await git.commit('local ahead of origin');
+
+ writeFileSync(join(projectDir, 'doc.md'), 'v3\n', 'utf-8');
+ await git.add('doc.md');
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ expect((await git.raw(['status', '--porcelain'])).trim()).toBe('MM doc.md');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await engine.pushOnce();
+
+ expect(await originHeadMessage(bare)).toContain('local ahead of origin');
+ expect((await git.raw(['status', '--porcelain'])).trim()).toBe('');
+
+ const heals = logs.entries.filter(
+ (e) => e.level === 'warn' && e.data.event === 'self-heal-applied',
+ );
+ expect(heals).toHaveLength(1);
+ expect(heals[0]?.data).toMatchObject({ paths: ['doc.md'] });
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a push cycle over a clean tree does no heal work', async () => {
+ await projectWithBareOrigin();
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await engine.pushOnce();
+
+ expect(
+ logs.entries.filter((e) => String(e.data.event ?? '').startsWith('self-heal')),
+ ).toHaveLength(0);
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+});
+
+describe('SyncEngine index-lock paused reason', () => {
+ test('a lock held for a whole push cycle names the condition and clears on the next clean cycle', async () => {
+ const { bare } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeFileSync(lockPath(), '', 'utf-8');
+ await engine.pushOnce();
+
+ expect(await originHeadMessage(bare)).toContain('doc.md');
+ expect(engine.getStatus().pausedReason).toBe('git-index-locked');
+
+ const locked = logs.entries.filter(
+ (e) => e.level === 'error' && e.data.event === 'index-locked',
+ );
+ expect(locked).toHaveLength(1);
+ expect(locked[0]?.data).toMatchObject({
+ op: 'push',
+ branch: 'main',
+ errorClass: 'local',
+ errorSubclass: 'index-lock',
+ });
+ expect(locked[0]?.msg).toContain('[sync] index locked');
+
+ rmSync(lockPath(), { force: true });
+ await engine.pushOnce();
+
+ expect(engine.getStatus().pausedReason).toBeUndefined();
+ expect((await simpleGit(projectDir).raw(['status', '--porcelain'])).trim()).toBe('');
+ } finally {
+ rmSync(lockPath(), { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a lock held across a pull cycle names the condition from the pull side', async () => {
+ const { bare } = await projectWithBareOrigin();
+ await advanceOriginFromSisterClone(bare);
+ writeFileSync(join(projectDir, 'doc.md'), 'local overlay\n', 'utf-8');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeFileSync(lockPath(), '', 'utf-8');
+
+ expect(await engine.pullOnce()).toBe('error');
+ expect(engine.getStatus().pausedReason).toBe('git-index-locked');
+
+ const locked = logs.entries.filter(
+ (e) => e.level === 'error' && e.data.event === 'index-locked',
+ );
+ expect(locked).toHaveLength(1);
+ expect(locked[0]?.data).toMatchObject({
+ op: 'pull',
+ branch: 'main',
+ errorClass: 'local',
+ errorSubclass: 'index-lock',
+ });
+ } finally {
+ rmSync(lockPath(), { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a reset blocked during a pull cycle is attributed to the pull, not to a push', async () => {
+ const { bare } = await projectWithBareOrigin();
+ await advanceOriginFromSisterClone(bare);
+ writeFileSync(join(projectDir, 'doc.md'), 'local overlay\n', 'utf-8');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeFileSync(lockPath(), '', 'utf-8');
+ await engine.pullOnce('sync');
+
+ const resets = logs.entries.filter((e) => e.data.event === 'stale-index-reset');
+ expect(resets).toHaveLength(1);
+ expect(resets[0]?.data).toMatchObject({
+ outcome: 'failed',
+ op: 'pull',
+ branch: 'main',
+ errorClass: 'local',
+ errorSubclass: 'index-lock',
+ });
+ expect(resets[0]?.msg).not.toContain('landed push');
+
+ const locked = logs.entries.filter(
+ (e) => e.level === 'error' && e.data.event === 'index-locked',
+ );
+ expect(locked).toHaveLength(1);
+ expect(locked[0]?.data).toMatchObject({ op: 'pull' });
+ expect(locked[0]?.msg).toContain('[sync] index locked');
+ } finally {
+ rmSync(lockPath(), { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a reset blocked while committing an MCP launcher entry is attributed to neither cycle', async () => {
+ const { git } = await projectWithBareOrigin();
+ const entry = (marker: string) => ({
+ command: '/bin/sh',
+ args: ['-l', '-c', `${marker}\nexit 127`],
+ });
+ const config = (marker: string) =>
+ `${JSON.stringify({
+ theme: 'keep',
+ mcpServers: { other: { command: 'keep-me' }, 'open-knowledge': entry(marker) },
+ })}\n`;
+ writeFileSync(join(projectDir, '.mcp.json'), config('# ok-mcp-v2'), 'utf-8');
+ await git.add('.mcp.json');
+ await git.commit('mcp base');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ const internal = engine as unknown as {
+ persistReconciledMcpEntries: (
+ entries: Array<{ path: string; raw: string; winnerEntry: Record<string, unknown> }>,
+ ) => Promise<void>;
+ };
+ try {
+ await engine.start();
+ writeFileSync(lockPath(), '', 'utf-8');
+ await internal.persistReconciledMcpEntries([
+ {
+ path: '.mcp.json',
+ raw: config('# ok-mcp-v99'),
+ winnerEntry: entry('# ok-mcp-v99'),
+ },
+ ]);
+
+ const resets = logs.entries.filter((e) => e.data.event === 'stale-index-reset');
+ expect(resets).toHaveLength(1);
+ expect(resets[0]?.data).toMatchObject({
+ outcome: 'failed',
+ op: 'mcp-reconcile',
+ branch: 'main',
+ errorClass: 'local',
+ errorSubclass: 'index-lock',
+ });
+ } finally {
+ rmSync(lockPath(), { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a ref lock hit while an index-lock pause is resting still names itself in the log', async () => {
+ const { git } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ const refLock = join(projectDir, '.git', 'refs', 'heads', 'main.lock');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeFileSync(lockPath(), '', 'utf-8');
+ await engine.pushOnce();
+ expect(engine.getStatus().pausedReason).toBe('git-index-locked');
+
+ rmSync(lockPath(), { force: true });
+ writeFileSync(join(projectDir, 'doc.md'), 'v3\n', 'utf-8');
+ writeFileSync(refLock, '', 'utf-8');
+ await engine.pushOnce();
+
+ expect((await git.raw(['status', '--porcelain'])).trim()).not.toBe('');
+ expect(logs.entries.filter((e) => e.data.event === 'index-locked')).toHaveLength(1);
+ const held = logs.entries.filter(
+ (e) => e.level === 'error' && e.data.event === 'git-lock-held',
+ );
+ expect(held).toHaveLength(1);
+ expect(held[0]?.data).toMatchObject({ op: 'push', branch: 'main' });
+ } finally {
+ rmSync(refLock, { force: true });
+ rmSync(lockPath(), { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a reset blocked inside the push non-fast-forward retry is attributed to the push', async () => {
+ const { bare } = await projectWithBareOrigin();
+ await advanceOriginFromSisterClone(bare);
+ writeFileSync(join(projectDir, 'doc.md'), 'mine\n', 'utf-8');
+
+ const logs = captureSyncLogs();
+ let resetAttempts = 0;
+ const editDuringTheCycle = (): void => {
+ resetAttempts++;
+ if (resetAttempts !== 1) return;
+ writeFileSync(join(projectDir, 'doc.md'), 'typed while the push was in flight\n', 'utf-8');
+ };
+ const engine = makeEngine({ _beforeRealIndexResetRetry: editDuringTheCycle });
+ try {
+ await engine.start();
+ writeFileSync(lockPath(), '', 'utf-8');
+ await engine.pushOnce();
+
+ const resets = logs.entries.filter((e) => e.data.event === 'stale-index-reset');
+ expect(resets.length).toBeGreaterThanOrEqual(2);
+ expect(resets.map((e) => e.data.op)).not.toContain('pull');
+ expect(resets[resets.length - 1]?.data).toMatchObject({
+ outcome: 'failed',
+ op: 'push',
+ branch: 'main',
+ errorClass: 'local',
+ errorSubclass: 'index-lock',
+ });
+ } finally {
+ rmSync(lockPath(), { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a lock under full auto-sync pauses the panel without disabling the engine', async () => {
+ await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+
+ const engine = makeEngine({ mode: 'full' });
+ try {
+ await engine.start();
+ expect(engine.getStatus().state).not.toBe('disabled');
+
+ writeFileSync(lockPath(), '', 'utf-8');
+ await engine.pushOnce();
+
+ const status = engine.getStatus();
+ expect(status.pausedReason).toBe('git-index-locked');
+ expect(status.state).not.toBe('disabled');
+ } finally {
+ rmSync(lockPath(), { force: true });
+ await engine.destroy();
+ }
+ });
+
+ test('a held ref lock is not reported to the user as a held index lock', async () => {
+ const { git } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ const refLock = join(projectDir, '.git', 'refs', 'heads', 'main.lock');
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeFileSync(refLock, '', 'utf-8');
+ await engine.pushOnce();
+
+ expect(existsSync(lockPath())).toBe(false);
+ expect(engine.getStatus().pausedReason).not.toBe('git-index-locked');
+ expect((await git.raw(['status', '--porcelain'])).trim()).not.toBe('');
+
+ expect(logs.entries.filter((e) => e.data.event === 'index-locked')).toHaveLength(0);
+ const held = logs.entries.filter(
+ (e) => e.level === 'error' && e.data.event === 'git-lock-held',
+ );
+ expect(held).toHaveLength(1);
+ expect(held[0]?.data).toMatchObject({ op: 'push', branch: 'main' });
+ expect(held[0]?.msg).not.toContain('another program is holding .git/index.lock');
+ } finally {
+ rmSync(refLock, { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a pull invoked during an in-flight push is refused and leaves the lock pause intact', async () => {
+ const { git } = await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'a.md'), 'a1\n', 'utf-8');
+ await git.add('a.md');
+ await git.commit('seed a');
+ await git.push();
+
+ writeFileSync(join(projectDir, 'a.md'), 'a2\n', 'utf-8');
+ await git.add('a.md');
+ writeFileSync(join(projectDir, 'a.md'), 'a1\n', 'utf-8');
+ writeFileSync(join(projectDir, 'b.md'), 'b1\n', 'utf-8');
+
+ const logs = captureSyncLogs();
+ let resetAttempts = 0;
+ let pausedReasonDuringPull: string | undefined | 'never-ran' = 'never-ran';
+ let engine: SyncEngine | undefined;
+ const doPullCycle = vi.fn();
+ const runInterleavedPull = async (): Promise<void> => {
+ resetAttempts++;
+ if (resetAttempts !== 2 || engine === undefined) return;
+ const internals = engine as unknown as {
+ runPullCycle: () => Promise<void>;
+ doPullCycle: () => Promise<void>;
+ pullTimer: NodeJS.Timeout | null;
+ };
+ internals.doPullCycle = doPullCycle;
+ await internals.runPullCycle();
+ pausedReasonDuringPull = engine.getStatus().pausedReason;
+ };
+ engine = makeEngine({ mode: 'full', _beforeRealIndexResetRetry: runInterleavedPull });
+ try {
+ await engine.start();
+ writeFileSync(lockPath(), '', 'utf-8');
+ await engine.pushOnce();
+
+ expect(resetAttempts).toBeGreaterThanOrEqual(2);
+ expect(doPullCycle).not.toHaveBeenCalled();
+ expect(pausedReasonDuringPull).toBe('git-index-locked');
+ expect(engine.getStatus().pausedReason).toBe('git-index-locked');
+
+ const locked = logs.entries.filter(
+ (e) => e.level === 'error' && e.data.event === 'index-locked',
+ );
+ expect(locked).toHaveLength(1);
+ expect(locked[0]?.data).toMatchObject({ op: 'push' });
+ } finally {
+ rmSync(lockPath(), { force: true });
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a lock watch opened by the other leg neither captures nor restores the resting pause', () => {
+ const engine = makeEngine();
+ const internals = engine as unknown as {
+ cycleInFlight: 'push' | 'pull' | null;
+ pausedReason: string | undefined;
+ restingIndexLockPause: string | undefined;
+ beginIndexLockWatch: (op: 'push' | 'pull') => void;
+ settleIndexLockPause: (op: 'push' | 'pull') => void;
+ };
+ internals.pausedReason = 'git-index-locked';
+ internals.restingIndexLockPause = 'dirty-tree';
+ internals.cycleInFlight = 'push';
+
+ internals.beginIndexLockWatch('pull');
+ expect(internals.restingIndexLockPause).toBe('dirty-tree');
+
+ internals.settleIndexLockPause('pull');
+ expect(internals.pausedReason).toBe('git-index-locked');
+
+ internals.cycleInFlight = null;
+ internals.settleIndexLockPause('push');
+ expect(internals.pausedReason).toBe('dirty-tree');
+ });
+
+ test('a push failure that is not a held lock leaves the paused reason alone', async () => {
+ const { git } = await projectWithBareOrigin();
+
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await git.remote(['set-url', 'origin', join(tmpDir, 'not-a-repo.git')]);
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ await engine.pushOnce();
+
+ expect(engine.getStatus().pushError).toBeDefined();
+ expect(engine.getStatus().pausedReason).not.toBe('git-index-locked');
+ } finally {
+ await engine.destroy();
+ }
+ });
+
+ test('the lock pause is neither written to the state file nor restored from it', async () => {
+ await projectWithBareOrigin();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeFileSync(lockPath(), '', 'utf-8');
+ await engine.pushOnce();
+ rmSync(lockPath(), { force: true });
+
+ expect(engine.getStatus().pausedReason).toBe('git-index-locked');
+ const internal = engine as unknown as { saveStateNow: () => void };
+ internal.saveStateNow();
+ expect(JSON.parse(readFileSync(statePath(), 'utf-8')).pausedReason).toBeUndefined();
+ } finally {
+ rmSync(lockPath(), { force: true });
+ await engine.destroy();
+ }
+
+ writeFileSync(
+ statePath(),
+ JSON.stringify({
+ version: 1,
+ lastSyncUtc: null,
+ lastFetchUtc: null,
+ lastPushedSha: null,
+ pausedReason: 'git-index-locked',
+ }),
+ 'utf-8',
+ );
+
+ const restarted = makeEngine();
+ try {
+ await restarted.start();
+ expect(restarted.getStatus().pausedReason).toBeUndefined();
+ } finally {
+ await restarted.destroy();
+ }
+ });
+});
diff --git a/packages/server/src/sync-engine.stamp-persistence.test.ts b/packages/server/src/sync-engine.stamp-persistence.test.ts
new file mode 100644
index 000000000..ac9de0109
--- /dev/null
+++ b/packages/server/src/sync-engine.stamp-persistence.test.ts
@@ -0,0 +1,152 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { LOCAL_DIR, type SyncMode } from '@inkeep/open-knowledge-core';
+import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { getLogger } from './logger.ts';
+import { SyncEngine } from './sync-engine.ts';
+
+const stubContentFilter = {
+ isExcluded: (_path: string) => false,
+ isDirExcluded: (_path: string) => false,
+};
+
+interface CapturedLog {
+ data: Record<string, unknown>;
+ msg: string;
+}
+
+function captureSyncWarnings(): { entries: CapturedLog[]; restore: () => void } {
+ const entries: CapturedLog[] = [];
+ const logger = getLogger('sync-engine');
+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(((
+ data: unknown,
+ msg?: string,
+ ): void => {
+ entries.push({ data: (data ?? {}) as Record<string, unknown>, msg: msg ?? '' });
+ }) as never);
+ return { entries, restore: () => warnSpy.mockRestore() };
+}
+
+let tmpDir = '';
+let projectDir = '';
+let okDir = '';
+
+beforeEach(() => {
+ tmpDir = mkdtempSync(join(tmpdir(), 'sync-engine-stamps-'));
+ projectDir = join(tmpDir, 'project');
+ okDir = join(projectDir, '.ok', LOCAL_DIR);
+ mkdirSync(projectDir, { recursive: true });
+ mkdirSync(okDir, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(tmpDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+});
+
+function statePath(): string {
+ return join(okDir, 'sync-state.json');
+}
+
+async function projectWithBareOrigin() {
+ const bare = join(tmpDir, 'bare.git');
+ mkdirSync(bare, { recursive: true });
+ await simpleGit(bare).init(true);
+ await simpleGit(bare).raw('symbolic-ref', 'HEAD', 'refs/heads/main');
+
+ const git = simpleGit(projectDir);
+ await git.init(['--initial-branch=main']);
+ await git.raw('config', 'user.name', 'Test');
+ await git.raw('config', 'user.email', '[email protected]');
+ writeFileSync(join(projectDir, 'doc.md'), 'v1\n', 'utf-8');
+ await git.add('.');
+ await git.commit('seed');
+ await git.addRemote('origin', bare);
+ await git.push(['--set-upstream', 'origin', 'main']);
+ return { git, bare };
+}
+
+function makeEngine(opts: { mode?: SyncMode } = {}) {
+ return new SyncEngine({
+ projectDir,
+ contentDir: projectDir,
+ contentFilter: stubContentFilter,
+ mode: opts.mode ?? 'off',
+ pullIntervalSeconds: 99999,
+ pushIntervalSeconds: 99999,
+ });
+}
+
+describe('SyncEngine sync stamp persistence', () => {
+ test('push and pull stamps survive a restart that happens inside the save debounce', async () => {
+ await projectWithBareOrigin();
+
+ const engineA = makeEngine();
+ let engineB: SyncEngine | null = null;
+ try {
+ await engineA.start();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ await engineA.pushOnce();
+ await engineA.pullOnce();
+
+ const before = engineA.getStatus();
+ expect(before.lastPushOkUtc).toBeTruthy();
+ expect(before.lastPullOkUtc).toBeTruthy();
+
+ engineB = makeEngine();
+ await engineB.start();
+
+ const after = engineB.getStatus();
+ expect(after.lastPushOkUtc).toBe(before.lastPushOkUtc);
+ expect(after.lastPullOkUtc).toBe(before.lastPullOkUtc);
+ } finally {
+ if (engineB) await engineB.destroy();
+ await engineA.destroy();
+ }
+ });
+
+ test('the persisted file keeps version 1 and its existing fields', async () => {
+ await projectWithBareOrigin();
+
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ await engine.pushOnce();
+
+ const persisted = JSON.parse(readFileSync(statePath(), 'utf-8')) as Record<string, unknown>;
+ expect(persisted.version).toBe(1);
+ expect(persisted.lastPushOkUtc).toBe(engine.getStatus().lastPushOkUtc);
+ expect(persisted).toHaveProperty('lastFetchUtc');
+ expect(persisted).toHaveProperty('lastPushedSha');
+ expect(persisted).toHaveProperty('consecutiveFailures');
+ expect(persisted).toHaveProperty('inflightConflicts');
+ } finally {
+ await engine.destroy();
+ }
+ });
+
+ test('a stamp write that cannot reach disk warns and leaves the push cycle intact', async () => {
+ const { bare } = await projectWithBareOrigin();
+ mkdirSync(statePath(), { recursive: true });
+
+ const logs = captureSyncWarnings();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeFileSync(join(projectDir, 'doc.md'), 'v2\n', 'utf-8');
+ await engine.pushOnce();
+
+ expect(engine.getStatus().pushError).toBeUndefined();
+ expect(engine.getStatus().lastPushOkUtc).toBeTruthy();
+ expect((await simpleGit(bare).raw(['log', '-1', '--format=%s', 'main'])).trim()).toContain(
+ 'doc.md',
+ );
+ expect(logs.entries.some((e) => e.msg === '[sync] failed to persist sync state')).toBe(true);
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+});
diff --git a/packages/server/src/sync-engine.state-persist.test.ts b/packages/server/src/sync-engine.state-persist.test.ts
new file mode 100644
index 000000000..b8621a26d
--- /dev/null
+++ b/packages/server/src/sync-engine.state-persist.test.ts
@@ -0,0 +1,117 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
+import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { SyncEngine } from './sync-engine.ts';
+
+const writeCalls = vi.hoisted(() => [] as string[]);
+const renameCalls = vi.hoisted(() => [] as [string, string][]);
+
+vi.mock('./fs-traced.ts', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('./fs-traced.ts')>();
+ return {
+ ...actual,
+ tracedWriteFileSync: (
+ path: string,
+ data: Parameters<typeof actual.tracedWriteFileSync>[1],
+ options?: Parameters<typeof actual.tracedWriteFileSync>[2],
+ ) => {
+ writeCalls.push(path);
+ actual.tracedWriteFileSync(path, data, options);
+ },
+ tracedRenameSync: (from: string, to: string) => {
+ renameCalls.push([from, to]);
+ actual.tracedRenameSync(from, to);
+ },
+ };
+});
+
+const stubContentFilter = {
+ isExcluded: (_path: string) => false,
+ isDirExcluded: (_path: string) => false,
+};
+
+let tmpDir = '';
+let projectDir = '';
+let okDir = '';
+
+beforeEach(async () => {
+ writeCalls.length = 0;
+ renameCalls.length = 0;
+ tmpDir = mkdtempSync(join(tmpdir(), 'sync-engine-state-persist-'));
+ projectDir = join(tmpDir, 'project');
+ okDir = join(projectDir, '.ok', LOCAL_DIR);
+ mkdirSync(projectDir, { recursive: true });
+ mkdirSync(okDir, { recursive: true });
+ const git = simpleGit(projectDir);
+ await git.init(['--initial-branch=main']);
+ await git.raw('config', 'user.name', 'Test');
+ await git.raw('config', 'user.email', '[email protected]');
+});
+
+afterEach(() => {
+ rmSync(tmpDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+});
+
+function statePath(): string {
+ return join(okDir, 'sync-state.json');
+}
+
+function makeEngine() {
+ return new SyncEngine({
+ projectDir,
+ contentDir: projectDir,
+ contentFilter: stubContentFilter,
+ mode: 'off',
+ pullIntervalSeconds: 99999,
+ pushIntervalSeconds: 99999,
+ });
+}
+
+interface StateInternals {
+ saveStateNow: () => void;
+ scheduleSaveState: () => void;
+}
+
+describe('SyncEngine sync-state persistence', () => {
+ test('the state file is replaced by a rename, never truncated in place', async () => {
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ writeCalls.length = 0;
+ renameCalls.length = 0;
+
+ (engine as unknown as StateInternals).saveStateNow();
+
+ expect(writeCalls).toHaveLength(1);
+ expect(writeCalls[0]).not.toBe(statePath());
+ expect(renameCalls).toEqual([[writeCalls[0], statePath()]]);
+ expect(existsSync(writeCalls[0] as string)).toBe(false);
+ expect(JSON.parse(readFileSync(statePath(), 'utf-8')).version).toBe(1);
+ } finally {
+ await engine.destroy();
+ }
+ });
+
+ test('an immediate save cancels the armed debounce instead of writing twice', async () => {
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ const internal = engine as unknown as StateInternals;
+ vi.useFakeTimers();
+ internal.scheduleSaveState();
+ writeCalls.length = 0;
+
+ internal.saveStateNow();
+ expect(writeCalls).toHaveLength(1);
+
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(writeCalls).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ await engine.destroy();
+ }
+ });
+});
diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.ts
index b81771bbf..622c81926 100644
--- a/packages/server/src/sync-engine.test.ts
+++ b/packages/server/src/sync-engine.test.ts
@@ -1,5 +1,6 @@
import { execFile, execFileSync } from 'node:child_process';
import {
+ appendFileSync,
chmodSync,
existsSync,
mkdirSync,
@@ -455,6 +456,67 @@ describe('SyncEngine state persistence round-trip', () => {
}
});
+ test('names an unrecognized persisted pause reason before dropping it', async () => {
+ writeFileSync(
+ statePath(),
+ JSON.stringify({
+ version: 1,
+ lastSyncUtc: null,
+ lastFetchUtc: null,
+ lastPushedSha: null,
+ consecutiveFailures: 0,
+ pausedReason: 'reason-from-a-newer-build',
+ inflightConflicts: [],
+ }),
+ 'utf-8',
+ );
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine({ syncEnabled: false });
+ try {
+ await engine.start();
+ expect(engine.getStatus().pausedReason).toBeUndefined();
+
+ const dropped = logs.entries.filter(
+ (e) => e.level === 'warn' && e.data.event === 'paused-reason-unrecognized',
+ );
+ expect(dropped).toHaveLength(1);
+ expect(dropped[0]?.data).toMatchObject({ pausedReason: 'reason-from-a-newer-build' });
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a recognized persisted pause reason is restored without a diagnostic', async () => {
+ writeFileSync(
+ statePath(),
+ JSON.stringify({
+ version: 1,
+ lastSyncUtc: null,
+ lastFetchUtc: null,
+ lastPushedSha: null,
+ consecutiveFailures: 0,
+ pausedReason: 'detached-head',
+ inflightConflicts: [],
+ }),
+ 'utf-8',
+ );
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine({ syncEnabled: false });
+ try {
+ await engine.start();
+ expect(engine.getStatus().pausedReason).toBe('detached-head');
+ expect(
+ logs.entries.filter((e) => e.data.event === 'paused-reason-unrecognized'),
+ ).toHaveLength(0);
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
test('ignores state files with unknown version', async () => {
const persisted = { version: 99, consecutiveFailures: 9999, inflightConflicts: [] };
writeFileSync(statePath(), JSON.stringify(persisted), 'utf-8');
@@ -666,6 +728,7 @@ describe('SyncEngine tracked MCP overlap preparation', () => {
rmSync(projectDir, { recursive: true, force: true });
await simpleGit(tmpDir).clone(bareDir, projectDir);
mkdirSync(okDir, { recursive: true });
+ appendFileSync(join(projectDir, '.git', 'info', 'exclude'), '\n.ok/\n', 'utf-8');
writeFileSync(join(sisterDir, '.mcp.json'), `${v2}\n`, 'utf-8');
await sister.add('.mcp.json');
@@ -3213,12 +3276,12 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()
const engine = makeShareableEngine('off');
const internal = engine as unknown as {
- commitDirtyContentFilesToHead: (handle: unknown) => Promise<void>;
+ commitDirtyContentFilesToHead: (handle: unknown, op: 'push' | 'pull') => Promise<void>;
};
const commitDirty = internal.commitDirtyContentFilesToHead.bind(engine);
- internal.commitDirtyContentFilesToHead = async (handle) => {
+ internal.commitDirtyContentFilesToHead = async (handle, op) => {
chmodSync(join(projectDir, '.ok', 'schemas'), 0o311);
- await commitDirty(handle);
+ await commitDirty(handle, op);
};
try {
@@ -3258,12 +3321,12 @@ describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', ()
writeFileSync(join(projectDir, 'local.md'), '# Local\n');
const engine = makeShareableEngine();
const internal = engine as unknown as {
- commitDirtyContentFilesToHead: (handle: unknown) => Promise<void>;
+ commitDirtyContentFilesToHead: (handle: unknown, op: 'push' | 'pull') => Promise<void>;
};
const commitDirty = internal.commitDirtyContentFilesToHead.bind(engine);
- internal.commitDirtyContentFilesToHead = async (handle) => {
+ internal.commitDirtyContentFilesToHead = async (handle, op) => {
chmodSync(join(projectDir, '.ok', 'schemas'), 0o311);
- await commitDirty(handle);
+ await commitDirty(handle, op);
};
try {
@@ -6970,7 +7033,8 @@ describe('SyncEngine exclusive merge ownership', () => {
pullError?: string;
pushError?: string;
gitHandle(): GitHandle;
- commitDirtyContentFilesToHead(handle: GitHandle): Promise<string | null>;
+ saveStateNow(): void;
+ commitDirtyContentFilesToHead(handle: GitHandle, op: 'push' | 'pull'): Promise<string | null>;
doPushCycle(retriesLeft?: number): Promise<void>;
doPullCycle(invocation: 'explicit' | 'sync'): Promise<'up-to-date'>;
runPullCycle(): Promise<void>;
@@ -7022,13 +7086,13 @@ describe('SyncEngine exclusive merge ownership', () => {
const releaseRetry = Promise.withResolvers<void>();
const commitDirty = internals.commitDirtyContentFilesToHead.bind(engine);
let first = true;
- internals.commitDirtyContentFilesToHead = async (handle) => {
+ internals.commitDirtyContentFilesToHead = async (handle, op) => {
if (first) {
first = false;
enteredRetry.resolve();
await releaseRetry.promise;
}
- return commitDirty(handle);
+ return commitDirty(handle, op);
};
const push = engine.pushOnce();
try {
@@ -7138,7 +7202,7 @@ describe('SyncEngine exclusive merge ownership', () => {
await internals.doPushCycle();
} else {
await expect(
- internals.commitDirtyContentFilesToHead(internals.gitHandle()),
+ internals.commitDirtyContentFilesToHead(internals.gitHandle(), 'pull'),
).rejects.toThrow('Git operation');
}
expect(await git.revparse('HEAD')).toBe(head);
@@ -7163,7 +7227,7 @@ describe('SyncEngine exclusive merge ownership', () => {
try {
await internals.doPushCycle();
await expect(
- internals.commitDirtyContentFilesToHead(internals.gitHandle()),
+ internals.commitDirtyContentFilesToHead(internals.gitHandle(), 'pull'),
).rejects.toThrow('Git operation');
expect(await git.revparse('HEAD')).toBe(head);
expect(await git.raw(['ls-files', '--stage'])).toBe(stages);
@@ -7311,6 +7375,51 @@ describe('SyncEngine exclusive merge ownership', () => {
},
);
+ test('the operation pause is neither written to the state file nor restored from it', async () => {
+ const { engine, internals, git } = await setup('off');
+ const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');
+ const statePath = join(okDir, 'sync-state.json');
+ writeFileSync(markerPath, await git.revparse('HEAD'));
+ try {
+ await engine.pushOnce();
+ expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');
+
+ internals.saveStateNow();
+ const persisted = JSON.parse(readFileSync(statePath, 'utf-8')) as { pausedReason?: string };
+ expect(persisted.pausedReason).toBeUndefined();
+ } finally {
+ await engine.destroy();
+ }
+
+ rmSync(markerPath);
+ writeFileSync(
+ statePath,
+ JSON.stringify({
+ version: 1,
+ lastSyncUtc: null,
+ lastFetchUtc: null,
+ lastPushedSha: null,
+ consecutiveFailures: 0,
+ pausedReason: 'git-operation-in-progress',
+ inflightConflicts: [],
+ }),
+ 'utf-8',
+ );
+
+ const restarted = new SyncEngine({
+ projectDir,
+ contentDir: projectDir,
+ contentFilter: stubContentFilter,
+ mode: 'off',
+ });
+ try {
+ await restarted.start();
+ expect(restarted.getStatus().pausedReason).toBeUndefined();
+ } finally {
+ await restarted.destroy();
+ }
+ });
+
test('a successful safety probe preserves an unrelated pause reason', async () => {
const { engine, internals } = await setup();
internals.pausedReason = 'diverged-local-commits';
diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.ts
index 9c89059d1..b2c8492dd 100644
--- a/packages/server/src/sync-engine.ts
+++ b/packages/server/src/sync-engine.ts
@@ -15,8 +15,10 @@ import {
OK_DIR,
type PullOutcome,
pathspecArgs,
+ SYNC_PAUSED_REASONS,
type SyncMode,
type SyncModeChangeSource,
+ type SyncPausedReason,
tryLineLevelCombine,
} from '@inkeep/open-knowledge-core';
import { inspectGitRepository } from '@inkeep/open-knowledge-core/git-repository';
@@ -33,7 +35,7 @@ import {
classifyGitError,
type UserFacingErrorCode,
} from './error-classification.ts';
-import { tracedUnlinkSync, tracedWriteFileSync } from './fs-traced.ts';
+import { tracedRenameSync, tracedUnlinkSync, tracedWriteFileSync } from './fs-traced.ts';
import { createGhTokenSource, type GhTokenSource } from './gh-token-source.ts';
import {
applyGitEnv,
@@ -43,7 +45,13 @@ import {
withParentLock,
} from './git-handle.ts';
import { resolveGitIdentity } from './git-identity.ts';
-import { listNames } from './git-paths.ts';
+import {
+ listNameStatus,
+ listNames,
+ listPorcelainEntries,
+ PORCELAIN_STATUS_ARGS,
+ type PorcelainEntry,
+} from './git-paths.ts';
import {
type CheckPushPermissionOptions,
type DetectGhAccountsFn,
@@ -204,7 +212,7 @@ interface SyncStatus {
pushErrorCode?: UserFacingErrorCode;
pullError?: string;
pullErrorCode?: UserFacingErrorCode;
- pausedReason?: string;
+ pausedReason?: SyncPausedReason;
pushPermission?: PushPermissionStatus;
}
@@ -237,11 +245,43 @@ type SyncStagingScope = typeof CONTENT_SYNC_STAGING_SCOPE | typeof PROJECT_SYNC_
type PullInvocation = 'explicit' | 'sync';
const BLOCKING_PATHS_CAP = 50;
+const LOGGED_PATHS_CAP = 20;
+const PROMISED_PATHS_CAP = 100;
+const INDEX_LOCK_PATH_IN_STDERR = /(^|[/\\])index\.lock\b/i;
+const INDEX_RESET_RETRY_DELAY_SECONDS = 0.05;
+
+type SyncCycleOp = 'push' | 'pull';
+type IndexResetOp = SyncCycleOp | 'mcp-reconcile';
+
+const SYNC_PAUSED_REASON_VALUES = new Set<string>(SYNC_PAUSED_REASONS);
-const ONE_SHOT_PAUSES: ReadonlySet<string | undefined> = new Set([
+function isSyncPausedReason(value: string): value is SyncPausedReason {
+ return SYNC_PAUSED_REASON_VALUES.has(value);
+}
+
+const ONE_SHOT_PAUSES: ReadonlySet<SyncPausedReason | undefined> = new Set<SyncPausedReason>([
'diverged-local-commits',
'external-changes-pending',
+ 'git-index-locked',
+ 'git-operation-in-progress',
+ 'no-commits-yet',
+]);
+
+const NON_PERSISTED_PAUSE_LIST = [
+ 'no-push-permission',
+ 'auth-error',
+ 'git-index-locked',
'git-operation-in-progress',
+ 'no-commits-yet',
+] as const satisfies readonly SyncPausedReason[];
+
+const NON_PERSISTED_PAUSES: ReadonlySet<SyncPausedReason | undefined> = new Set<SyncPausedReason>(
+ NON_PERSISTED_PAUSE_LIST,
+);
+
+const NON_RESTORED_PAUSES: ReadonlySet<SyncPausedReason | undefined> = new Set<SyncPausedReason>([
+ ...NON_PERSISTED_PAUSE_LIST,
+ 'external-changes-pending',
]);
const COMMIT_BLOCKING_MESSAGE = 'Commit local changes before syncing';
@@ -289,6 +329,7 @@ interface SyncEngineOptions {
detectGh?: DetectGhFn;
detectGhAccounts?: DetectGhAccountsFn;
_readCredentialUrlMatch?: CredentialUrlMatchReader;
+ _beforeRealIndexResetRetry?: () => void | Promise<void>;
tokenStore?: ProbeTokenStore | null;
checkPushPermissionFn?: (opts: CheckPushPermissionOptions) => Promise<PushPermission>;
}
@@ -299,6 +340,12 @@ function jitteredMs(seconds: number): number {
return Math.round(base + jitter);
}
+function sleepMs(ms: number): Promise<void> {
+ return new Promise((resolve) => {
+ setTimeout(resolve, ms);
+ });
+}
+
function isUnbornHead(projectDir: string): boolean {
const inspected = inspectGitRepository(projectDir);
if (inspected.kind !== 'repository') return false;
@@ -356,6 +403,7 @@ export class SyncEngine {
private checkpointBeforeOverlayRestore:
| ((context: { branch: string; paths: number }) => void | Promise<void>)
| undefined;
+ private beforeRealIndexResetRetry: (() => void | Promise<void>) | undefined;
private mcpTomlEditor: NativeTomlMcpEditor | undefined;
private detectGh: DetectGhFn | undefined;
@@ -398,7 +446,10 @@ export class SyncEngine {
private pushErrorCode: UserFacingErrorCode | undefined;
private pullError: string | undefined;
private pullErrorCode: UserFacingErrorCode | undefined;
- private pausedReason: string | undefined;
+ private pausedReason: SyncPausedReason | undefined;
+ private indexLockHitThisCycle = false;
+ private lastLockNoticeKind: 'index-locked' | 'git-lock-held' | undefined;
+ private restingIndexLockPause: SyncPausedReason | undefined;
private blockingPaths: string[] = [];
private currentBranch = 'main';
@@ -431,6 +482,7 @@ export class SyncEngine {
this.onAutoDisable = options.onAutoDisable;
this.checkpointBeforeStrandedConversion = options.checkpointBeforeStrandedConversion;
this.checkpointBeforeOverlayRestore = options.checkpointBeforeOverlayRestore;
+ this.beforeRealIndexResetRetry = options._beforeRealIndexResetRetry;
this.mcpTomlEditor = options.mcpTomlEditor;
this.detectGh = options.detectGh;
this.detectGhAccounts = options.detectGhAccounts;
@@ -868,7 +920,9 @@ export class SyncEngine {
if (
this.pausedReason === 'dirty-tree' ||
this.pausedReason === 'external-changes-pending' ||
- this.pausedReason === 'non-content-merge-failure'
+ this.pausedReason === 'non-content-merge-failure' ||
+ this.pausedReason === 'git-index-locked' ||
+ this.pausedReason === 'no-commits-yet'
) {
this.pausedReason = undefined;
this.clearPullError();
@@ -942,20 +996,24 @@ export class SyncEngine {
return;
}
- if (!this.hasRemote || isUnbornHead(this.projectDir)) {
- log.info(
- { hasRemote: this.hasRemote },
- '[sync] one-shot push refused — no remote, or no commits yet',
- );
+ if (!this.hasRemote) {
+ log.info({ hasRemote: false }, '[sync] one-shot push refused — no remote');
return;
}
+ if (isUnbornHead(this.projectDir)) {
+ this.noteUnbornHeadRefusal();
+ return;
+ }
+ this.clearUnbornHeadPause();
const restingState = this.state;
this.cycleInFlight = 'push';
+ this.beginIndexLockWatch('push');
try {
await this.doPushCycle(1);
} finally {
this.cycleInFlight = null;
+ this.settleIndexLockPause('push');
if (this.pushCycleLanded) this.markRun();
const settled = this.currentState();
if (settled !== 'conflict' && settled !== 'auth-error') {
@@ -1025,15 +1083,18 @@ export class SyncEngine {
);
return this.recordPullOutcome('refused');
}
+ this.clearUnbornHeadPause();
const restingMode = this.mode;
const restingState = this.state;
const restingPausedReason = this.pausedReason;
this.cycleInFlight = 'pull';
+ this.beginIndexLockWatch('pull');
try {
return this.recordPullOutcome(await this.doPullCycle(invocation));
} finally {
this.cycleInFlight = null;
+ this.settleIndexLockPause('pull');
if (restingMode === 'off') {
if (!ONE_SHOT_PAUSES.has(this.pausedReason)) {
if (!ONE_SHOT_PAUSES.has(restingPausedReason)) {
@@ -1052,6 +1113,7 @@ export class SyncEngine {
this.lastPullOutcome = outcome;
if (outcome === 'succeeded' || outcome === 'up-to-date' || outcome === 'conflict') {
this.lastPullOkUtc = new Date().toISOString();
+ this.saveStateNow();
}
this.cc1Broadcaster?.signal('sync-status');
return outcome;
@@ -1505,13 +1567,16 @@ export class SyncEngine {
this.schedulePull();
return;
}
+ this.clearUnbornHeadPause();
this.cycleInFlight = 'pull';
+ this.beginIndexLockWatch('pull');
try {
if (this.mode === 'follow') await this.refreshAuthTier();
this.recordPullOutcome(await this.doPullCycle(this.mode === 'full' ? 'sync' : 'explicit'));
} finally {
this.cycleInFlight = null;
+ this.settleIndexLockPause('pull');
this.schedulePull();
}
}
@@ -1580,7 +1645,7 @@ export class SyncEngine {
this.transitionTo('pulling');
this.setBatchInProgress?.(true);
try {
- await this.commitDirtyContentFilesToHead(handle);
+ await this.commitDirtyContentFilesToHead(handle, 'pull');
const mergePrep = await this.prepareForMerge(handle, branch);
if (!mergePrep.proceed) return 'refused';
let stashRestored = true;
@@ -2061,19 +2126,23 @@ export class SyncEngine {
return;
}
if (isUnbornHead(this.projectDir)) {
+ if (this.hasRemote) this.noteUnbornHeadRefusal();
this.schedulePush();
return;
}
+ this.clearUnbornHeadPause();
if (this.cycleInFlight !== null) {
if (this.cycleInFlight === 'pull' && this.pushTimer === null) this.schedulePush();
return;
}
this.cycleInFlight = 'push';
+ this.beginIndexLockWatch('push');
try {
await this.doPushCycle(1);
} finally {
this.cycleInFlight = null;
+ this.settleIndexLockPause('push');
if (this.pushCycleLanded) this.markRun();
this.schedulePush();
}
@@ -2086,80 +2155,157 @@ export class SyncEngine {
try {
const contentFiles = this.gatherContentFilesSync();
+ const promisedPaths = await this.snapshotPromisedPaths();
+ const committedPaths = new Set<string>();
await withParentLock(async () => {
await this.assertNoGitOperationInProgress();
this.transitionTo('pushing');
- const handle = this.gitHandle(tmpIndexPath);
-
- if (isUnbornHead(this.projectDir)) {
- log.info({}, '[sync] repo has no commits yet — skipping push cycle');
- this.transitionTo('idle');
- return;
- }
- let headSha: string;
try {
- headSha = (await handle.git.revparse('HEAD')).trim();
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- const raw = (e as { git?: unknown }).git?.toString() ?? msg;
- const combined = `${msg}\n${raw}`;
- if (
- /unknown revision or path not in the working tree/i.test(combined) ||
- /ambiguous argument 'HEAD'/i.test(combined) ||
- /does not have any commits yet/i.test(combined)
- ) {
+ const handle = this.gitHandle(tmpIndexPath);
+
+ if (isUnbornHead(this.projectDir)) {
log.info({}, '[sync] repo has no commits yet — skipping push cycle');
this.transitionTo('idle');
return;
}
- this.handleError(classifyGitError(e instanceof Error ? e : new Error(String(e))), 'push');
- return;
- }
+ let headSha: string;
+ try {
+ headSha = (await handle.git.revparse('HEAD')).trim();
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ const raw = (e as { git?: unknown }).git?.toString() ?? msg;
+ const combined = `${msg}\n${raw}`;
+ if (
+ /unknown revision or path not in the working tree/i.test(combined) ||
+ /ambiguous argument 'HEAD'/i.test(combined) ||
+ /does not have any commits yet/i.test(combined)
+ ) {
+ log.info({}, '[sync] repo has no commits yet — skipping push cycle');
+ this.transitionTo('idle');
+ return;
+ }
+ this.handleError(
+ classifyGitError(e instanceof Error ? e : new Error(String(e))),
+ 'push',
+ );
+ return;
+ }
- await handle.git.raw(['read-tree', headSha]);
+ await handle.git.raw(['read-tree', headSha]);
- const headContentSet = await this.listHeadContentPaths(handle, headSha);
+ const headContentSet = await this.listHeadContentPaths(handle, headSha);
- const staged = await this.stageContentFiles(handle, contentFiles);
+ const staged = await this.stageContentFiles(handle, contentFiles);
- const onDiskSet = new Set(staged.map((f) => f.projectRelPath));
- const deleted = [...headContentSet].filter((f) => !onDiskSet.has(f));
- await this.removePathsFromIndex(handle, deleted);
+ const onDiskSet = new Set(staged.map((f) => f.projectRelPath));
+ const deleted = [...headContentSet].filter((f) => !onDiskSet.has(f));
+ await this.removePathsFromIndex(handle, deleted);
- const newTreeSha = (await handle.git.raw(['write-tree'])).trim();
+ const newTreeSha = (await handle.git.raw(['write-tree'])).trim();
- let headTreeSha = '';
- try {
- headTreeSha = (await handle.git.raw(['rev-parse', `${headSha}^{tree}`])).trim();
- } catch {}
- if (headTreeSha && headTreeSha === newTreeSha) {
- let upstreamSha: string | null = null;
+ let headTreeSha = '';
try {
- upstreamSha = (
- await handle.git.raw(['rev-parse', `origin/${this.currentBranch}`])
- ).trim();
+ headTreeSha = (await handle.git.raw(['rev-parse', `${headSha}^{tree}`])).trim();
} catch {}
+ if (headTreeSha && headTreeSha === newTreeSha) {
+ let upstreamSha: string | null = null;
+ try {
+ upstreamSha = (
+ await handle.git.raw(['rev-parse', `origin/${this.currentBranch}`])
+ ).trim();
+ } catch {}
+
+ if (upstreamSha === headSha) {
+ log.info(
+ { contentFileCount: contentFiles.length, headSha },
+ '[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)',
+ );
+ this.lastPushedSha = headSha;
+ this.lastSyncUtc = new Date().toISOString();
+ this.pushCycleLanded = true;
+ this.consecutivePushFailures = 0;
+ this.consecutiveContentions = 0;
+ this.pushStreakIsConnectivity = false;
+ this.clearPushError();
+ this.transitionTo('idle');
+ return;
+ }
- if (upstreamSha === headSha) {
log.info(
- { contentFileCount: contentFiles.length, headSha },
- '[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)',
+ { headSha, upstreamSha },
+ '[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits',
+ );
+
+ let hasUpstream = false;
+ try {
+ await handle.git.raw(['rev-parse', '--abbrev-ref', `${this.currentBranch}@{u}`]);
+ hasUpstream = true;
+ } catch {}
+
+ if (hasUpstream) {
+ await handle.git.raw(['push', 'origin', this.currentBranch]);
+ } else {
+ await handle.git.raw(['push', '--set-upstream', 'origin', this.currentBranch]);
+ }
+
+ commitSha = headSha;
+ return;
+ }
+
+ let changedProjectRelPaths: string[] = [];
+ let changedContentRelPaths: string[] = [];
+ try {
+ const diffPaths = await listNames(handle.git, [
+ 'diff-tree',
+ '--name-only',
+ '-r',
+ headSha,
+ newTreeSha,
+ ]);
+ if (diffPaths.length > 0) {
+ const contentFileByProjRel = new Map(
+ contentFiles.map((f) => [f.projectRelPath, f.contentRelPath]),
+ );
+ for (const projRelPath of diffPaths) {
+ changedProjectRelPaths.push(projRelPath);
+ const contentRelPath =
+ contentFileByProjRel.get(projRelPath) ??
+ toPosix(relative(this.contentDir, join(this.projectDir, projRelPath)));
+ if (contentRelPath && !contentRelPath.startsWith('..')) {
+ changedContentRelPaths.push(contentRelPath);
+ }
+ }
+ }
+ } catch {
+ changedProjectRelPaths = contentFiles.map((f) => f.projectRelPath).concat(deleted);
+ changedContentRelPaths = contentFiles.map((f) => f.contentRelPath);
+ }
+ const message = this.buildCommitMessage(changedContentRelPaths);
+
+ await this.applyCommitIdentity(handle);
+
+ const newCommitSha = (
+ await handle.git.raw(['commit-tree', newTreeSha, '-p', headSha, '-m', message])
+ ).trim();
+
+ if (!newCommitSha || !SHA_HEX_40.test(newCommitSha)) {
+ log.warn(
+ { raw: newCommitSha },
+ '[sync] commit-tree returned invalid SHA — aborting push',
);
- this.lastPushedSha = headSha;
- this.lastSyncUtc = new Date().toISOString();
- this.pushCycleLanded = true;
- this.consecutivePushFailures = 0;
- this.consecutiveContentions = 0;
- this.pushStreakIsConnectivity = false;
- this.clearPushError();
this.transitionTo('idle');
return;
}
- log.info(
- { headSha, upstreamSha },
- '[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits',
- );
+ await handle.git.raw([
+ 'update-ref',
+ `refs/heads/${this.currentBranch}`,
+ newCommitSha,
+ headSha,
+ ]);
+
+ await this.resetRealIndexForPaths(changedProjectRelPaths, 'push');
+ for (const projRelPath of changedProjectRelPaths) committedPaths.add(projRelPath);
let hasUpstream = false;
try {
@@ -2173,77 +2319,10 @@ export class SyncEngine {
await handle.git.raw(['push', '--set-upstream', 'origin', this.currentBranch]);
}
- commitSha = headSha;
- return;
- }
-
- let changedProjectRelPaths: string[] = [];
- let changedContentRelPaths: string[] = [];
- try {
- const diffPaths = await listNames(handle.git, [
- 'diff-tree',
- '--name-only',
- '-r',
- headSha,
- newTreeSha,
- ]);
- if (diffPaths.length > 0) {
- const contentFileByProjRel = new Map(
- contentFiles.map((f) => [f.projectRelPath, f.contentRelPath]),
- );
- for (const projRelPath of diffPaths) {
- changedProjectRelPaths.push(projRelPath);
- const contentRelPath =
- contentFileByProjRel.get(projRelPath) ??
- toPosix(relative(this.contentDir, join(this.projectDir, projRelPath)));
- if (contentRelPath && !contentRelPath.startsWith('..')) {
- changedContentRelPaths.push(contentRelPath);
- }
- }
- }
- } catch {
- changedProjectRelPaths = contentFiles.map((f) => f.projectRelPath).concat(deleted);
- changedContentRelPaths = contentFiles.map((f) => f.contentRelPath);
- }
- const message = this.buildCommitMessage(changedContentRelPaths);
-
- await this.applyCommitIdentity(handle);
-
- const newCommitSha = (
- await handle.git.raw(['commit-tree', newTreeSha, '-p', headSha, '-m', message])
- ).trim();
-
- if (!newCommitSha || !SHA_HEX_40.test(newCommitSha)) {
- log.warn(
- { raw: newCommitSha },
- '[sync] commit-tree returned invalid SHA — aborting push',
- );
- this.transitionTo('idle');
- return;
- }
-
- await handle.git.raw([
- 'update-ref',
- `refs/heads/${this.currentBranch}`,
- newCommitSha,
- headSha,
- ]);
-
- await this.resetRealIndexForPaths(changedProjectRelPaths);
-
- let hasUpstream = false;
- try {
- await handle.git.raw(['rev-parse', '--abbrev-ref', `${this.currentBranch}@{u}`]);
- hasUpstream = true;
- } catch {}
-
- if (hasUpstream) {
- await handle.git.raw(['push', 'origin', this.currentBranch]);
- } else {
- await handle.git.raw(['push', '--set-upstream', 'origin', this.currentBranch]);
+ commitSha = newCommitSha;
+ } finally {
+ await this.healStaleRealIndex(promisedPaths, committedPaths);
}
-
- commitSha = newCommitSha;
});
if (commitSha) {
@@ -2283,7 +2362,7 @@ export class SyncEngine {
try {
await retryHandle.git.fetch('origin');
retryStage = 'push';
- await this.commitDirtyContentFilesToHead(retryHandle);
+ await this.commitDirtyContentFilesToHead(retryHandle, 'push');
const mergePrep = await this.prepareForMerge(retryHandle, this.currentBranch);
if (!mergePrep.proceed) {
this.setBatchInProgress?.(false);
@@ -2348,7 +2427,10 @@ export class SyncEngine {
this.scheduleSaveState();
}
- private async commitDirtyContentFilesToHead(handle: GitHandle): Promise<string | null> {
+ private async commitDirtyContentFilesToHead(
+ handle: GitHandle,
+ op: SyncCycleOp,
+ ): Promise<string | null> {
await this.assertNoGitOperationInProgress();
const status = await handle.git.status();
if (status.files.length === 0) return null;
@@ -2403,7 +2485,7 @@ export class SyncEngine {
headSha,
]);
- await this.resetRealIndexForPaths(changedProjectRelPaths, handle);
+ await this.resetRealIndexForPaths(changedProjectRelPaths, op, handle);
return newCommitSha;
} finally {
@@ -2636,7 +2718,10 @@ export class SyncEngine {
this.transitionTo('idle');
}
}
- log.warn({ err: error, op }, '[sync] cycle refused because a Git operation holds the tree');
+ log.error(
+ { event: 'git-operation-refusal', err: error, op, branch: this.currentBranch },
+ '[sync] cycle refused because a Git operation holds the tree — finish or abort it to resume sync',
+ );
this.cc1Broadcaster?.signal('sync-status');
this.scheduleSaveState();
}
@@ -2654,7 +2739,7 @@ export class SyncEngine {
): Promise<void> {
if (reconciled.length === 0) return;
if (this.hasGitOperationInProgress()) {
- throw new Error('refusing MCP entry commit while a Git operation is in progress');
+ throw new GitOperationInProgressError();
}
await withParentLock(async () => {
@@ -2770,7 +2855,10 @@ export class SyncEngine {
{ event: 'mcp-config-reconcile', outcome: 'overlay-replay-failed', err },
'[sync] MCP overlay replay failed; resetting the affected index entries',
);
- await this.resetRealIndexForPaths(replayEntries.map((entry) => entry.path));
+ await this.resetRealIndexForPaths(
+ replayEntries.map((entry) => entry.path),
+ 'mcp-reconcile',
+ );
this.restoreReconciledMcpOverlays(reconciled);
}
log.info(
@@ -2948,22 +3036,164 @@ export class SyncEngine {
}
}
- private async resetRealIndexForPaths(paths: string[], handle?: GitHandle): Promise<void> {
+ private async snapshotPromisedPaths(): Promise<string[]> {
+ let entries: PorcelainEntry[];
+ let unmerged: ReadonlySet<string>;
+ try {
+ const { git } = this.gitHandle();
+ entries = await listPorcelainEntries(git, PORCELAIN_STATUS_ARGS);
+ unmerged = new Set(await listNames(git, ['diff', '--name-only', '--diff-filter=U']));
+ } catch (e) {
+ log.warn(
+ { event: 'snapshot-read-failed', err: e, branch: this.currentBranch },
+ '[sync] could not read the real index before the push cycle — skipping stale-index self-heal',
+ );
+ return [];
+ }
+
+ const paths: string[] = [];
+ for (const entry of entries) {
+ if (unmerged.has(entry.path)) continue;
+ if (!this.isSyncScopedPath(entry.path)) continue;
+ paths.push(entry.path);
+ if (paths.length === PROMISED_PATHS_CAP) break;
+ }
+ return paths;
+ }
+
+ private async healStaleRealIndex(
+ promisedPaths: string[],
+ committedPaths: ReadonlySet<string>,
+ ): Promise<void> {
+ const promised = new Set(promisedPaths.filter((p) => !committedPaths.has(p)));
+ if (promised.size === 0) return;
+
+ if (this.hasGitOperationInProgress()) {
+ log.warn(
+ {
+ event: 'self-heal-skipped-git-operation',
+ branch: this.currentBranch,
+ pathCount: promised.size,
+ paths: [...promised].slice(0, LOGGED_PATHS_CAP),
+ },
+ '[sync] self-heal skipped — a Git operation now holds the tree, so the promised paths stay listed until it ends',
+ );
+ return;
+ }
+
+ const handle = this.gitHandle();
+ let stagedAgainstHead: string[];
+ let changedInWorktree: string[];
+ try {
+ const rows = await listNameStatus(handle.git, [
+ 'diff-index',
+ '--cached',
+ '--name-status',
+ 'HEAD',
+ ]);
+ stagedAgainstHead = rows.flatMap((row) =>
+ row.status[0] === 'R' || row.status[0] === 'C' ? [row.from, row.to] : [row.to],
+ );
+ changedInWorktree = await listNames(handle.git, ['diff', '--name-only', 'HEAD']);
+ } catch (e) {
+ log.error(
+ {
+ event: 'self-heal-skipped',
+ branch: this.currentBranch,
+ pathCount: promised.size,
+ paths: [...promised].slice(0, LOGGED_PATHS_CAP),
+ err: e,
+ },
+ '[sync] self-heal could not compare the real index against HEAD — the promised paths stay listed in the real index',
+ );
+ return;
+ }
+
+ const worktreeDiffers = new Set(changedInWorktree);
+ const healable = [
+ ...new Set(stagedAgainstHead.filter((p) => promised.has(p) && !worktreeDiffers.has(p))),
+ ];
+ if (healable.length === 0) return;
+
+ await this.resetRealIndexForPaths(healable, 'push', handle);
+ log.warn(
+ {
+ event: 'self-heal-applied',
+ branch: this.currentBranch,
+ pathCount: healable.length,
+ paths: healable.slice(0, LOGGED_PATHS_CAP),
+ },
+ '[sync] self-heal cleared stale real-index entries left behind by an earlier push cycle',
+ );
+ }
+
+ private async resetRealIndexForPaths(
+ paths: string[],
+ op: IndexResetOp,
+ handle?: GitHandle,
+ ): Promise<void> {
if (paths.length === 0) return;
const realIndexHandle = handle ?? this.gitHandle();
const unique = [...new Set(paths)];
const BATCH = 100;
for (let i = 0; i < unique.length; i += BATCH) {
const batch = unique.slice(i, i + BATCH);
+ await this.resetRealIndexBatch(realIndexHandle, batch, op);
+ }
+ }
+
+ private async resetRealIndexBatch(
+ handle: GitHandle,
+ batch: string[],
+ op: IndexResetOp,
+ ): Promise<void> {
+ let firstError: unknown;
+ try {
+ await handle.git.raw(['reset', 'HEAD', ...pathspecArgs(batch)]);
+ return;
+ } catch (e) {
+ firstError = e;
+ }
+
+ let classified = classifyGitError(firstError);
+ let finalError = firstError;
+ let recovered = false;
+
+ if (classified.class === 'local' && classified.subclass === 'index-lock') {
+ await this.beforeRealIndexResetRetry?.();
+ await sleepMs(jitteredMs(INDEX_RESET_RETRY_DELAY_SECONDS));
try {
- await realIndexHandle.git.raw(['reset', 'HEAD', ...pathspecArgs(batch)]);
- } catch (resetErr: unknown) {
- log.warn(
- { resetErr, files: batch.length },
- '[sync] real-index reset failed; paths may remain staged',
- );
+ await handle.git.raw(['reset', 'HEAD', ...pathspecArgs(batch)]);
+ recovered = true;
+ } catch (e) {
+ finalError = e;
+ classified = classifyGitError(e);
}
}
+
+ const fields = {
+ event: 'stale-index-reset',
+ outcome: recovered ? 'recovered-on-retry' : 'failed',
+ op,
+ branch: this.currentBranch,
+ pathCount: batch.length,
+ paths: batch.slice(0, LOGGED_PATHS_CAP),
+ errorClass: classified.class,
+ errorSubclass: classified.subclass,
+ err: finalError,
+ };
+ if (recovered) {
+ log.warn(
+ fields,
+ '[sync] stale-index reset needed a second attempt — it succeeded, so the panel listing is current',
+ );
+ } else {
+ log.error(fields, '[sync] stale-index reset failed — the panel listing may stay stale');
+ }
+
+ if (!recovered && classified.class === 'local' && classified.subclass === 'index-lock') {
+ this.noteIndexLockEncountered(op, classified);
+ }
}
private buildCommitMessage(contentRelPaths: string[]): string {
@@ -3140,7 +3370,7 @@ export class SyncEngine {
this.pullErrorCode = undefined;
}
- private handleError(classified: ClassifiedError, op: 'push' | 'pull'): void {
+ private handleError(classified: ClassifiedError, op: SyncCycleOp): void {
if (classified.userFacingCode !== null) {
if (op === 'push') {
this.pushErrorCode = classified.userFacingCode;
@@ -3176,6 +3406,12 @@ export class SyncEngine {
this.transitionTo('disabled');
this.pausedReason = 'protected-branch';
void this.onAutoDisable?.('protected-branch');
+ } else if (classified.class === 'local' && classified.subclass === 'index-lock') {
+ this.bumpFailureCount(op);
+ if (this.state === 'pushing' || this.state === 'pulling' || this.state === 'fetching') {
+ this.transitionTo('idle');
+ }
+ this.noteIndexLockEncountered(op, classified);
} else if (classified.class === 'local' && classified.subclass === 'dirty-tree') {
if (this.state === 'conflict' || this.conflictCount > 0) {
this.transitionTo('conflict');
@@ -3194,12 +3430,85 @@ export class SyncEngine {
}
}
+ private otherLegInFlight(op: SyncCycleOp): boolean {
+ return this.cycleInFlight !== null && this.cycleInFlight !== op;
+ }
+
+ private beginIndexLockWatch(op: SyncCycleOp): void {
+ if (this.otherLegInFlight(op)) return;
+ const alreadyLocked = this.pausedReason === 'git-index-locked';
+ this.indexLockHitThisCycle = false;
+ if (!alreadyLocked) this.lastLockNoticeKind = undefined;
+ this.restingIndexLockPause = alreadyLocked ? undefined : this.pausedReason;
+ }
+
+ private holdsIndexLock(classified: ClassifiedError): boolean {
+ return INDEX_LOCK_PATH_IN_STDERR.test(`${classified.message}\n${classified.rawStderr ?? ''}`);
+ }
+
+ private noteIndexLockEncountered(op: IndexResetOp, classified: ClassifiedError): void {
+ const isIndexLock = this.holdsIndexLock(classified);
+ const noticeKind = isIndexLock ? 'index-locked' : 'git-lock-held';
+ if (this.lastLockNoticeKind !== noticeKind) {
+ this.lastLockNoticeKind = noticeKind;
+ const fields = {
+ event: noticeKind,
+ op,
+ branch: this.currentBranch,
+ errorClass: classified.class,
+ errorSubclass: classified.subclass,
+ };
+ if (isIndexLock) {
+ log.error(
+ fields,
+ '[sync] index locked — another program is holding .git/index.lock, so sync cannot update it',
+ );
+ } else {
+ log.error(
+ fields,
+ '[sync] a git lock file blocked the operation — the held lock is not .git/index.lock, so the listing is not paused on it',
+ );
+ }
+ }
+ if (!isIndexLock) return;
+ this.indexLockHitThisCycle = true;
+ if (this.pausedReason === 'git-index-locked') return;
+ this.pausedReason = 'git-index-locked';
+ this.cc1Broadcaster?.signal('sync-status');
+ }
+
+ private noteUnbornHeadRefusal(): void {
+ if (this.pausedReason !== 'no-commits-yet') {
+ log.error(
+ { event: 'unborn-head-refusal', branch: this.currentBranch },
+ '[sync] push refused — this repository has no commits yet, so there is nothing to send',
+ );
+ }
+ this.pausedReason = 'no-commits-yet';
+ this.cc1Broadcaster?.signal('sync-status');
+ }
+
+ private clearUnbornHeadPause(): void {
+ if (this.pausedReason !== 'no-commits-yet') return;
+ this.pausedReason = undefined;
+ this.cc1Broadcaster?.signal('sync-status');
+ }
+
+ private settleIndexLockPause(op: SyncCycleOp): void {
+ if (this.otherLegInFlight(op)) return;
+ if (this.indexLockHitThisCycle) return;
+ if (this.pausedReason !== 'git-index-locked') return;
+ this.pausedReason = this.restingIndexLockPause;
+ this.cc1Broadcaster?.signal('sync-status');
+ }
+
private currentState(): SyncState {
return this.state;
}
private markRun(): void {
this.lastPushOkUtc = new Date().toISOString();
+ this.saveStateNow();
this.cc1Broadcaster?.signal('sync-status');
}
@@ -3221,11 +3530,14 @@ export class SyncEngine {
}
private saveStateNow(): void {
+ if (this.stateSaveTimer !== null) {
+ clearTimeout(this.stateSaveTimer);
+ this.stateSaveTimer = null;
+ }
try {
- const persistedReason =
- this.pausedReason === 'no-push-permission' || this.pausedReason === 'auth-error'
- ? undefined
- : this.pausedReason;
+ const persistedReason = NON_PERSISTED_PAUSES.has(this.pausedReason)
+ ? undefined
+ : this.pausedReason;
const data: PersistedSyncState = {
version: 1,
lastSyncUtc: this.lastSyncUtc,
@@ -3240,7 +3552,9 @@ export class SyncEngine {
pausedSinceUtc: persistedReason ? new Date().toISOString() : undefined,
inflightConflicts: this.conflictStore.list().map((c) => c.file),
};
- writeFileSync(this.statePath, JSON.stringify(data, null, 2), 'utf-8');
+ const tmpStatePath = `${this.statePath}.tmp`;
+ tracedWriteFileSync(tmpStatePath, JSON.stringify(data, null, 2), 'utf-8');
+ tracedRenameSync(tmpStatePath, this.statePath);
} catch (e) {
log.warn({ err: e }, '[sync] failed to persist sync state');
}
@@ -3260,12 +3574,16 @@ export class SyncEngine {
this.consecutivePullFailures = data.consecutiveFailures ?? 0;
this.consecutivePushFailures = data.consecutivePushFailures ?? 0;
this.pushStreakIsConnectivity = data.pushStreakIsConnectivity ?? false;
- this.pausedReason =
- data.pausedReason === 'no-push-permission' ||
- data.pausedReason === 'auth-error' ||
- data.pausedReason === 'external-changes-pending'
- ? undefined
- : data.pausedReason;
+ const rawReason = typeof data.pausedReason === 'string' ? data.pausedReason : undefined;
+ const storedReason =
+ rawReason !== undefined && isSyncPausedReason(rawReason) ? rawReason : undefined;
+ if (rawReason !== undefined && storedReason === undefined && rawReason.length > 0) {
+ log.warn(
+ { event: 'paused-reason-unrecognized', pausedReason: rawReason },
+ '[sync] persisted pause reason is not one this build knows — dropping it and continuing without a pause',
+ );
+ }
+ this.pausedReason = NON_RESTORED_PAUSES.has(storedReason) ? undefined : storedReason;
const inflightFiles = data.inflightConflicts ?? [];
if (inflightFiles.length > 0) {
diff --git a/packages/server/src/sync-engine.unborn-head.test.ts b/packages/server/src/sync-engine.unborn-head.test.ts
new file mode 100644
index 000000000..2c7b890c9
--- /dev/null
+++ b/packages/server/src/sync-engine.unborn-head.test.ts
@@ -0,0 +1,249 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { LOCAL_DIR, type SyncMode } from '@inkeep/open-knowledge-core';
+import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { getLogger } from './logger.ts';
+import { SyncEngine } from './sync-engine.ts';
+
+const stubContentFilter = {
+ isExcluded: (_path: string) => false,
+ isDirExcluded: (_path: string) => false,
+};
+
+interface CapturedLog {
+ data: Record<string, unknown>;
+ msg: string;
+ level: 'info' | 'warn' | 'error';
+}
+
+function captureSyncLogs(): { entries: CapturedLog[]; restore: () => void } {
+ const entries: CapturedLog[] = [];
+ const logger = getLogger('sync-engine');
+ const record =
+ (level: CapturedLog['level']) =>
+ (data: unknown, msg?: string): void => {
+ entries.push({ data: (data ?? {}) as Record<string, unknown>, msg: msg ?? '', level });
+ };
+ const infoSpy = vi.spyOn(logger, 'info').mockImplementation(record('info') as never);
+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(record('warn') as never);
+ const errorSpy = vi.spyOn(logger, 'error').mockImplementation(record('error') as never);
+ return {
+ entries,
+ restore: () => {
+ infoSpy.mockRestore();
+ warnSpy.mockRestore();
+ errorSpy.mockRestore();
+ },
+ };
+}
+
+let tmpDir = '';
+let projectDir = '';
+let okDir = '';
+
+beforeEach(() => {
+ tmpDir = mkdtempSync(join(tmpdir(), 'sync-engine-unborn-head-'));
+ projectDir = join(tmpDir, 'project');
+ okDir = join(projectDir, '.ok', LOCAL_DIR);
+ mkdirSync(projectDir, { recursive: true });
+ mkdirSync(okDir, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(tmpDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+});
+
+function statePath(): string {
+ return join(okDir, 'sync-state.json');
+}
+
+async function emptyProject() {
+ const git = simpleGit(projectDir);
+ await git.init(['--initial-branch=main']);
+ await git.raw('config', 'user.name', 'Test');
+ await git.raw('config', 'user.email', '[email protected]');
+ return git;
+}
+
+async function emptyProjectWithBareOrigin() {
+ const bare = join(tmpDir, 'bare.git');
+ mkdirSync(bare, { recursive: true });
+ await simpleGit(bare).init(true);
+ await simpleGit(bare).raw('symbolic-ref', 'HEAD', 'refs/heads/main');
+
+ const git = await emptyProject();
+ await git.addRemote('origin', bare);
+ return { git, bare };
+}
+
+function makeEngine(opts: { mode?: SyncMode } = {}) {
+ return new SyncEngine({
+ projectDir,
+ contentDir: projectDir,
+ contentFilter: stubContentFilter,
+ mode: opts.mode ?? 'off',
+ pullIntervalSeconds: 99999,
+ pushIntervalSeconds: 99999,
+ });
+}
+
+describe('SyncEngine push refusal on an unborn HEAD', () => {
+ test('a push with a remote and no commits names the missing first commit', async () => {
+ await emptyProjectWithBareOrigin();
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await engine.pushOnce();
+
+ const status = engine.getStatus();
+ expect(status.pausedReason).toBe('no-commits-yet');
+ expect(status.state).toBe('disabled');
+
+ const refusals = logs.entries.filter(
+ (e) => e.level === 'error' && e.data.event === 'unborn-head-refusal',
+ );
+ expect(refusals).toHaveLength(1);
+ expect(refusals[0].data).toMatchObject({ branch: 'main' });
+ expect(refusals[0].msg).toContain('no commits yet');
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('the notice clears once a first commit exists', async () => {
+ const { git } = await emptyProjectWithBareOrigin();
+
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await engine.pushOnce();
+ expect(engine.getStatus().pausedReason).toBe('no-commits-yet');
+
+ writeFileSync(join(projectDir, 'doc.md'), 'v1\n', 'utf-8');
+ await git.add('doc.md');
+ await git.commit('first');
+ await engine.pushOnce();
+
+ expect(engine.getStatus().pausedReason).toBeUndefined();
+ expect(engine.getStatus().pushError).toBeUndefined();
+ } finally {
+ await engine.destroy();
+ }
+ });
+
+ test('a full auto-sync push with no commits names the condition instead of going silent', async () => {
+ await emptyProjectWithBareOrigin();
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine({ mode: 'full' });
+ try {
+ await engine.start();
+ expect(engine.getStatus().state).not.toBe('disabled');
+ await engine.pushOnce();
+
+ const status = engine.getStatus();
+ expect(status.pausedReason).toBe('no-commits-yet');
+ expect(status.state).not.toBe('disabled');
+
+ const refusals = logs.entries.filter(
+ (e) => e.level === 'error' && e.data.event === 'unborn-head-refusal',
+ );
+ expect(refusals).toHaveLength(1);
+ expect(refusals[0]?.data).toMatchObject({ branch: 'main' });
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a repeating full-mode push cycle logs the refusal once per condition, not per tick', async () => {
+ await emptyProjectWithBareOrigin();
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine({ mode: 'full' });
+ try {
+ await engine.start();
+ await engine.pushOnce();
+ await engine.pushOnce();
+ await engine.pushOnce();
+
+ expect(engine.getStatus().pausedReason).toBe('no-commits-yet');
+ expect(logs.entries.filter((e) => e.data.event === 'unborn-head-refusal')).toHaveLength(1);
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a full-mode project with no remote is not paused on the missing first commit', async () => {
+ await emptyProject();
+
+ const logs = captureSyncLogs();
+ const engine = makeEngine({ mode: 'full' });
+ try {
+ await engine.start();
+ await engine.pushOnce();
+
+ expect(engine.getStatus().pausedReason).toBeUndefined();
+ expect(logs.entries.filter((e) => e.data.event === 'unborn-head-refusal')).toHaveLength(0);
+ } finally {
+ logs.restore();
+ await engine.destroy();
+ }
+ });
+
+ test('a project with no remote is left alone', async () => {
+ await emptyProject();
+
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await engine.pushOnce();
+ expect(engine.getStatus().pausedReason).toBeUndefined();
+ } finally {
+ await engine.destroy();
+ }
+ });
+
+ test('the notice is neither written to the state file nor restored from it', async () => {
+ await emptyProjectWithBareOrigin();
+
+ const engine = makeEngine();
+ try {
+ await engine.start();
+ await engine.pushOnce();
+ expect(engine.getStatus().pausedReason).toBe('no-commits-yet');
+
+ const internal = engine as unknown as { saveStateNow: () => void };
+ internal.saveStateNow();
+ expect(JSON.parse(readFileSync(statePath(), 'utf-8')).pausedReason).toBeUndefined();
+ } finally {
+ await engine.destroy();
+ }
+
+ writeFileSync(
+ statePath(),
+ JSON.stringify({
+ version: 1,
+ lastSyncUtc: null,
+ lastFetchUtc: null,
+ lastPushedSha: null,
+ pausedReason: 'no-commits-yet',
+ }),
+ 'utf-8',
+ );
+
+ const restarted = makeEngine();
+ try {
+ await restarted.start();
+ expect(restarted.getStatus().pausedReason).toBeUndefined();
+ } finally {
+ await restarted.destroy();
+ }
+ });
+});