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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions IMPLEMENTATION_PLAN.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,45 @@
# IMPLEMENTATION PLAN — WebObsidian

CI follow-up 2026-10-30: the fork-main PR reproduced a hidden Electron selection-pixel timing race. The fixture now isolates its profile, disables background throttling, waits for the exact viewport and measured selection coverage, then waits up to four seconds for the selected compositor frame. All original theme, width, selected-pixel, unselected-background and margin assertions remain intact; no runtime/CSS changes are involved.

The next CI run passed the complete test suite and exposed a smoke-startup race: `/healthz` was ready before the asynchronous initial index scan, so missing-file resolution correctly returned `503` rather than `404`. The smoke fixture now waits on authenticated `/api/index/status` availability and initial-scan completion before its existing resolver assertions.

## Editor indentation and folding — 2026-10-30

- [x] Add four-column tab stops, literal Tab insertion and list/selection indentation with Shift-Tab outdent.
- [x] Add clickable folding for headings and nested indentation, including individual indented code statements; preserve code text literally and stop at the enclosing fence.
- [x] Indent/outdent a folded parent together with its hidden descendants; keep folding visual and support undo.
- [x] Add fenced-code indentation guides, standard folding shortcuts and command-palette fold/unfold actions.
- [x] Verify structural boundaries, readonly protection, mixed indentation and actual Editor keyboard/click behavior in Live Preview and Source.

Progress 2026-10-30: structural unit tests and the actual React Editor browser regression passed; web typecheck passed. Full tests/build recorded in the task result.

Follow-up 2026-10-30: the original ABAP screenshot requires folding inside fenced code, not only the enclosing block. Removed the code-interior exclusion, bounded nested folds by code syntax nodes, and added independent fold/unfold clicks for both ABAP calls in Live Preview and Source. Seven structural unit tests and the browser regression passed before full verification.

Original comparison 2026-10-30: inspected installed Obsidian 1.14.5 in an isolated synthetic vault. Measurements in `tests/fixtures/rendering/obsidian-folding.json` confirm inline controls at the first non-whitespace character (no left gutter), no generic paragraph or enclosing code-fence folds, and saved fold state after reopening. Four typed spaces remain four spaces; both tabs and spaces participate in indentation folding. Web now follows those rules and saves view state in browser storage scoped by vault and path, without storing note text. Browser regressions cover document recreation, vault isolation and a deep heading restored after asynchronous hydration of a 5,000-line note.

## Draft recovery usability — 2026-10-30

- [x] Replace the persistent draft counter with an actionable unsaved-text recovery list; hide empty lists and ordinary live autosaves.
- [x] Explain browser copies and provide Review text, Download copy and Remove browser copy actions with vault-safe removal confirmation.
- [x] Explain deleted originals and require an explicit separate copy to recover their text.
- [x] Extend real-browser coverage for recovery, removal, deleted originals, normal autosaves and mobile keyboard/zoom positioning.

Progress 2026-10-30: recovery/viewport browser regressions, web typecheck, full `npm test` (288 server + 417 web passed; 10 server skips) and production build passed. Independent code review reported no actionable findings.

## Remote MCP, indexing and editor recovery integration — 2026-10-30

- [x] Integrate authenticated remote MCP alongside local stdio and scoped keys.
- [x] Integrate cached indexing, reconciliation/hash audits and automatic search refresh.
- [x] Integrate module-based plugins, draft recovery, conflict resolution and adaptive toolbar layouts.
- [x] Preserve data-safety and authentication fixes with regression coverage.

The upstream contribution retains one consolidated commit and source attribution.
Runtime sources and configuration match the reviewed integrated source tree;
upstream repository routing is applied separately in documentation and desktop metadata.
The viewport regression waits for exact expected dimensions before its unchanged zoom
and toolbar assertions, avoiding reads of the previous asynchronous layout.

## Review fixes — 2026-10-30

- [x] R1: CLI default recovery password, including old installations.
Expand Down
14 changes: 14 additions & 0 deletions scripts/integration-smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,20 @@ try {
const request = (url, options = {}) => fetch(`${base}${url}`, {
...options, headers: { cookie, 'content-type': 'application/json', ...options.headers },
});
// /healthz means the process is listening. Resolver assertions require the
// asynchronous initial index scan to finish before a missing file is a 404.
let indexStatus;
const indexDeadline = Date.now() + 10_000;
do {
const response = await request('/api/index/status');
assert.equal(response.status, 200);
indexStatus = await response.json();
if (indexStatus.initialScanComplete && indexStatus.available) break;
if (server.exitCode !== null) throw new Error(`server exited during indexing: ${output}`);
await delay(25);
} while (Date.now() < indexDeadline);
assert.ok(indexStatus?.initialScanComplete && indexStatus.available,
`initial index did not become ready: ${JSON.stringify(indexStatus)}\n${output}`);
const settings = await (await request('/api/settings')).json();
assert.equal(settings.vault.trashRetentionDays, 0);
const locked = await (await request('/api/files/content?path=notes/locked.md')).json();
Expand Down
107 changes: 106 additions & 1 deletion server/src/services/git.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@ import path from 'node:path';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { simpleGit } from 'simple-git';
import { mutateFileText, withVaultMutation } from './vault.js';
import { checkVersion, contentVersion } from './noteversion.js';

const exec = promisify(execFile);
const T = 20_000; // generous per-test timeout — these shell out to real git

// Full git settings; vault.path is set per test to a fresh temp repo.
const { settings } = vi.hoisted(() => ({
settings: {
vault: { path: '', trash: '.trash' },
vault: { path: '', trash: '.trash', allowedRoots: [] as string[] },
git: {
enabled: true,
autoSync: false,
Expand Down Expand Up @@ -86,6 +88,109 @@ afterEach(async () => {
});

describe.skipIf(!gitOnPath)('git integration (real repo)', () => {
it('a queued push keeps its vault and remote settings together across a vault switch', async () => {
await git.init();
await fs.writeFile(path.join(work, 'Note.md'), 'vault A');
await git.commitAll();
const next = await fs.mkdtemp(path.join(os.tmpdir(), 'wo-next-vault-'));
const nextRemote = await fs.mkdtemp(path.join(os.tmpdir(), 'wo-next-remote-'));
let entered!: () => void, release!: () => void;
const started = new Promise<void>(r => { entered = r; });
const gate = new Promise<void>(r => { release = r; });
const mutation = withVaultMutation(async () => { entered(); await gate; });
let pushing: Promise<unknown> | undefined;
try {
await exec('git', ['init', '--bare', '-b', 'main', nextRemote]);
await started;
pushing = git.push();
// Let the push join the occupied vault queue before changing settings.
await new Promise(r => setTimeout(r, 100));
settings.vault.path = next;
settings.git.remote = nextRemote;
release(); await mutation; await pushing;
expect((await exec('git', ['-C', work, 'remote', 'get-url', 'origin'])).stdout.trim()).toBe(bare);
expect((await exec('git', ['--git-dir', bare, 'show', 'main:Note.md'])).stdout).toBe('vault A');
expect((await exec('git', ['--git-dir', nextRemote, 'for-each-ref'])).stdout).toBe('');
} finally {
release(); await mutation; await pushing?.catch(() => {});
await fs.rm(next, { recursive: true, force: true });
await fs.rm(nextRemote, { recursive: true, force: true });
}
}, T);
async function remoteNoteUpdate() {
await git.init();
await fs.writeFile(path.join(work, 'Note.md'), 'base');
expect((await git.sync()).ok).toBe(true);
const peer = await fs.mkdtemp(path.join(os.tmpdir(), 'wo-peer-'));
try {
await exec('git', ['clone', bare, peer]);
await fs.writeFile(path.join(peer, 'Note.md'), 'remote');
await exec('git', ['-C', peer, 'add', '.']);
await exec('git', ['-C', peer, 'commit', '-m', 'remote edit']);
await exec('git', ['-C', peer, 'push']);
} finally { await fs.rm(peer, { recursive: true, force: true }); }
}

function saveLocal() {
return mutateFileText('Note.md', current => {
if (!checkVersion(current, contentVersion('base')).ok) {
throw Object.assign(new Error('version_conflict'), { status: 409 });
}
return { content: 'local', result: undefined };
});
}

it.each(['pull', 'sync'] as const)('%s waits for an accepted save and cannot overwrite it mid-write', async operation => {
await remoteNoteUpdate();
let entered!: () => void, release!: () => void;
const started = new Promise<void>(r => { entered = r; });
const gate = new Promise<void>(r => { release = r; });
const open = fs.open.bind(fs);
const spy = vi.spyOn(fs, 'open').mockImplementation(async (...args: Parameters<typeof fs.open>) => {
if (String(args[0]).includes('Note.md.tmp-')) { entered(); await gate; }
return open(...args);
});
const saving = saveLocal();
let pulling: Promise<string> | undefined;
try {
await started;
pulling = (operation === 'pull' ? git.pull().then(() => 'pulled')
: git.sync().then(result => result.ok ? 'pulled' : 'rejected')).catch(() => 'rejected');
const result = await Promise.race([pulling, new Promise<string>(r => setTimeout(() => r('waiting'), 1000))]);
expect(result).toBe('waiting');
release(); await saving;
expect(await pulling).toBe('rejected'); // Git protects the now-dirty local note.
expect(await fs.readFile(path.join(work, 'Note.md'), 'utf8')).toBe('local');
expect((await exec('git', ['-C', work, 'show', 'HEAD:Note.md'])).stdout).toBe(operation === 'sync' ? 'local' : 'base');
expect((await git.status()).conflicted).toEqual([]);
} finally { release(); await saving; await pulling; spy.mockRestore(); }
}, T);

it.each(['pull', 'sync'] as const)('a save queued behind %s checks the pulled version and reports a conflict', async operation => {
settings.git.lfsPatterns = ['*.png'];
await remoteNoteUpdate();
let entered!: () => void, release!: () => void;
const started = new Promise<void>(r => { entered = r; });
const gate = new Promise<void>(r => { release = r; });
const read = fs.readFile.bind(fs);
const spy = vi.spyOn(fs, 'readFile').mockImplementation((async (...args: Parameters<typeof fs.readFile>) => {
if (String(args[0]) === path.join(work, '.gitattributes')) { entered(); await gate; }
return read(...args);
}) as typeof fs.readFile);
const pulling = (operation === 'pull' ? git.pull().then(() => 'pulled')
: git.sync().then(result => result.ok ? 'pulled' : 'rejected')).catch(() => 'rejected');
let saving: Promise<unknown> | undefined;
try {
await started;
saving = saveLocal().then(() => 'saved', error => error.status);
const result = await Promise.race([saving, new Promise<string>(r => setTimeout(() => r('waiting'), 100))]);
expect(result).toBe('waiting');
release();
expect(await pulling).toBe('pulled');
expect(await saving).toBe(409);
expect(await fs.readFile(path.join(work, 'Note.md'), 'utf8')).toBe('remote');
} finally { release(); await pulling; await saving; spy.mockRestore(); }
}, T);
it('uses the temporary global Git configuration for simple-git child processes', async () => {
const origin = await simpleGit({ baseDir: work }).raw(['config', '--global', '--show-origin', '--get', 'user.name']);
expect(origin.replace(/\\/g, '/').includes(cfgHome.replace(/\\/g, '/'))).toBe(true);
Expand Down
42 changes: 26 additions & 16 deletions server/src/services/git.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { AsyncLocalStorage } from 'node:async_hooks';
import { simpleGit, type SimpleGit, type StatusResult } from 'simple-git';
import { getSettings } from './settings.js';
import { getVaultRoot } from './vault.js';
import { getSettings as loadSettings } from './settings.js';
import { getVaultRoot, withVaultMutation } from './vault.js';
import { redactUrlCreds } from '../lib/redact.js';

/** GitHub-native sync with Git LFS support (PRD FR-4). */
const operationSettings = new AsyncLocalStorage<Awaited<ReturnType<typeof loadSettings>>>();
async function getSettings() {
return operationSettings.getStore() ?? loadSettings();
}

export interface GitStatus {
enabled: boolean;
Expand Down Expand Up @@ -38,10 +43,10 @@ async function git(): Promise<SimpleGit> {
// `commit` collide on `.git/index.lock` ("Another git process seems to be
// running") — and a command killed mid-write leaves that lock behind, which then
// wedges EVERY later op (the "completely dead" state). Funnelling all mutating
// ops through one async queue removes the race; clearing a stale lock at the head
// ops through the vault mutation queue removes the race with both Git commands
// and version-checked saves; clearing a stale lock at the head
// of each op heals a leftover from a crash or an external Obsidian-git process.
// ---------------------------------------------------------------------------
let gitQueue: Promise<unknown> = Promise.resolve();

/** A lock a live git process holds is gone within a second for a notes vault; one
* older than this is orphaned. Generous enough that even an external LFS commit
Expand All @@ -67,21 +72,26 @@ async function clearStaleLocks(): Promise<void> {

/** Run `fn` with exclusive access to the vault repo, after self-healing any stale
* lock. Ops queue (never overlap); a rejecting op doesn't poison the queue. */
function withGitLock<T>(fn: () => Promise<T>): Promise<T> {
const result = gitQueue.then(async () => {
await clearStaleLocks();
return fn();
async function withGitLock<T>(fn: () => Promise<T>): Promise<T> {
// Hold the same canonical-root lock as compare-and-set + atomic file writes
// for the ENTIRE operation (including all of sync's commit/pull/push steps).
// Capture the vault before waiting, as ordinary file mutations do.
const settings = structuredClone(await loadSettings());
return withVaultMutation(async () => {
// A settings switch between the two captures must never pair one vault
// with another vault's remote. Once admitted, use this snapshot throughout.
if (path.resolve(settings.vault.path) !== await getVaultRoot()) {
throw Object.assign(new Error('Vault changed; retry the Git operation'), { status: 409 });
}
return operationSettings.run(settings, async () => {
await clearStaleLocks();
return fn();
});
});
gitQueue = result.then(
() => undefined,
() => undefined,
);
return result;
}

// Public, serialized git operations. Each delegates to its private *Impl below;
// callers that already hold the lock (e.g. syncImpl) call the *Impl directly to
// avoid re-entering the queue and dead-locking.
// callers that already hold the lock (e.g. syncImpl) call the *Impl directly.
export const status = (): Promise<GitStatus> => withGitLock(statusImpl);
export const pull = (): Promise<string> => withGitLock(pullImpl);
export const push = (): Promise<string> => withGitLock(pushImpl);
Expand Down Expand Up @@ -457,7 +467,7 @@ async function recoverMerge(g: SimpleGit): Promise<void> {

/** Convenience: stage+commit+pull+push in one go. Reports conflicts. Runs entirely
* inside the git queue (via the exported `sync` wrapper), so it calls the unlocked
* *Impl helpers directly — re-entering withGitLock here would dead-lock. */
* *Impl helpers directly so the transaction retains its settings snapshot. */
async function syncImpl(message?: string): Promise<{ ok: boolean; log: string[] }> {
const log: string[] = [];
const g = await git();
Expand Down
Loading
Loading