logancyang_obsidian-copilot/src/agentMode/session/AgentChatPersistenceManager.test.ts
Emt-lin 6d878e175c
feat(agent-projects): project-scoped Agent Mode — Agent Home PR2 (#2604)
* feat(agent-mode): project-scoped Agent Mode workspaces (PR2)

Turn Agent Mode "projects" into Claude Projects-style workspaces: entering a
project gives a scoped workspace with its own sessions, chat history, and
materialized context, while the global workspace becomes one special scope
(GLOBAL_SCOPE sentinel) sharing the same code path.

Session scope
- AgentSessionManager stores sessions by internal id but binds each to an
  immutable projectId; per-scope MRU, resolveSessionCwd, getSessionsForScope, and
  enterProject/exitProject all key off that projectId, and the active-session
  invariant (active.projectId === activeProjectId) keeps existing UI helpers
  untouched.
- Backend restarts / in-place replacement inherit the replaced session's
  projectId; project scope reuses the warm process instead of adopting the
  vault-root probe session.
- Re-entering a project opens as a fresh visit: conversational chats detach from
  the tab strip (kept live in the pool, listed in chat history) instead of
  dragging every prior tab back, while an unused empty landing is reused rather
  than stacked. The global workspace keeps its restore-the-last-tab behavior.

Context materialization (off-vault shared cache)
- projectContextMaterializer + contextCacheStore + manifestBuilder capture a
  project's URL/YouTube/PDF context once per session (single-flight per project)
  into a per-vault, off-vault store shared across projects
  (~/.obsidian-copilot/vaults/<vaultId>/context-cache/): a source referenced by N
  projects is converted once per vault, not N times. Paths derive from one source
  of truth (conversionsLocation.ts); getVaultId lives in utils/appPaths.
- Layout: shared remotes/ + files/ snapshots keyed by source identity (md5),
  per-project markers/<md5(projectId)>/ failure markers. A root-confined node:fs
  backend (createNodeContextCacheFs) writes atomically (temp+rename), throws on
  write/mkdir/read while list/remove/clear tolerate a missing target (the store
  treats a failed read as a cache miss), and never ascends past the cache root; it
  loads node:fs lazily behind the desktop boundary so Obsidian mobile never pulls
  it into the bundle.
- A per-artifact async-mutex lock makes two projects cold-converting the same
  source converge to a single fetch (the waiter re-reads meta inside the lock and
  cheap-skips). Shared snapshots are never reconciled per-project; a project's
  stale marker is cleared on a cheap-skip hit or when a usable stale snapshot
  survives a failed refresh.
- Cache semantics match the legacy CAG cache: a successful snapshot is kept
  indefinitely (fingerprint cheap-skip, no TTL); a failure with no usable
  snapshot writes a marker and is cheap-skipped on later automatic runs
  (re-surfacing the error) until the file changes or the user retries. A
  schemaVersion stamped into every snapshot/marker makes a future format change
  re-materialize instead of misreading stale content; MATERIALIZED_SOURCE_TYPES
  is the single source of truth for source kinds.
- The first prompt inlines a <project_context> block listing absolute snapshot
  paths (keyed by type:source so a same-URL web+youtube pair resolves correctly)
  so all three backends reach the shared store; opencode gets an
  external_directory allow for the cache root. Per-source status mirrors CAG's
  ProjectLoadTracker into the projectId-keyed agentProjectContextLoadAtom
  (remotes parallel, files sequential; each flips Ready/Failed as it settles) and
  the composer shows a context status icon and queues sends while materializing.
  The never-reject contract and contextSignature/warm reactivity are preserved;
  released CAG caches (.copilot/*) are untouched.

Instructions mirror
- project.md stays the single source of truth, with a marker-gated AGENTS.md
  mirror generated by ensureAgentsMirror: codex/opencode auto-discover it from
  the session cwd, claude gets the same composed instructions via
  getProjectProfile. A built-in project policy is layered into each project's
  instructions (a user-authored, unmarked AGENTS.md is left untouched).

Landing & project UI
- AgentLandingStack spine with project landing state, header, Welcome card,
  Project Chats tab variant, and project CRUD (anchored create popover, edit
  modal, overflow menu); shelf lists cap at 5 behind a View-all popover.
- One context editor (ProjectContextSourceEditor) is shared by the home shelf and
  the Edit Project modal; the Manage modal leads with a Links section whose single
  add affordance is the sidebar "+URL" popover (the old right-pane inline URL
  input is removed for consistency with Tags/Folders/Files). A three-state
  (processing / ready / failed) status popover offers inline per-source retry, its
  landing refresh deferred to popover-close and scope-guarded. The web/youtube
  classification is consolidated into one UrlKind type reused across every URL
  surface. Truncated previews mark the cut with a labelled divider and a "Copy
  full content" pill, and cap render so large snapshots don't freeze the modal.

History scope
- Agent chat history is scope-keyed: a project view lists only its own chats,
  while GLOBAL_SCOPE is the flat all-chats view. Native session history is scoped
  to projects and resumed transcripts hydrate from the session's scope cwd; legacy
  chats with no projectId resolve to GLOBAL_SCOPE. A failed resume/create during a
  cross-scope history load rolls back the active scope (rollbackHistoryLoadScope)
  so the active-session invariant can't be left split.

Todo / plan
- Unified backend todo lists across claude/codex/opencode feed the project info
  popover, with per-session todo-id tracking and symmetric plan clear.

Hardening & fixes
- contextCacheFs rejects `..`, absolute, and root-escaping paths; symlink escape
  is documented as out of the cache's threat model.
- A hard-disabled composer (orphaned project) blocks keyboard sends and queued
  flushes, not just pointer events, so a turn can't drain into a dead project.
- The per-message attachment envelope is renamed <copilot-context> ->
  <attached_context> to disambiguate from the project-wide <project_context>.

Tests
- 30+ suites covering session scope, the off-vault cache store/fs (including a
  real-filesystem dedup integration test), the materializer, AGENTS.md mirror,
  todo-plan pipeline, landing UI, the context-signature refresh state machine, and
  the opencode external_directory allow; plus a mobile load-boundary smoke guard
  over the cache consumers.

* fix(agent-mode): keep project edit modal open on save failure

ProjectInfoPopover's edit onSave swallowed updateProject errors into a
Notice, so onSave resolved and AddProjectModal closed — discarding the
user's edits on duplicate-name / folder-collision failures. Log and
rethrow instead so the modal keeps the form open and surfaces the error,
matching AgentProjectRowActions.handleEdit.

* fix(agent-mode): preserve project context after first-turn fan-out; clear off-vault markers on delete

A first-turn multi-agent fan-out set firstPromptSent while only the
ephemeral sub-sessions received the <project_context> block — the visible
backend is never prompted on that path. The next normal turn then injected
null, permanently stripping the project manifest from the main chat. Stop
the fan-out branch from consuming the first-turn flag so the next visible
turn delivers it. Adds a regression test.

Also clear the off-vault failure-marker bucket (markers/<md5(projectId)>)
in deleteProject so a project recreated under the same id can't inherit
stale negative-cache state. Desktop-gated + dynamically imported; the
helper roots a confined fs at the bucket and reuses recursive clear().

* fix(agent-mode): refresh empty project landing on System Prompt edit

An empty landing session bakes in its project instructions at creation
(Claude via systemPromptAppend, codex/opencode via the AGENTS.md mirror),
but the landing-refresh trigger keyed on the materialization signature,
which deliberately omits systemPrompt. A System-Prompt-only edit therefore
left the open landing untouched, so the first message ran with stale
instructions until a manual new chat.

Add getProjectLandingCaptureSignature (materialization signature + the
instruction body) and key the landing-refresh observer on it, leaving
getProjectContextSignature untouched so prompt edits never trigger
re-materialization. Adds tests.

* fix(agent-mode): preserve compose draft typed during landing refresh

The empty-landing context refresh replaces the session in place; its
draftEmpty guard ran before the async backend-startup window, so text the
user typed during that window landed in the old session's draft and was
pruned when the old session closed — breaking the guard's stated 'never
discard text the user has started typing' contract.

Add useAgentInputDrafts.migrateDraft and call it right after the swap to
carry any draft typed during startup onto the new session id. Writes
setDrafts directly to bypass the live-id guard; ordering is safe because
closeSession awaits cancel() before deleting the old session, so the
source draft is still present when migration runs. Adds tests.

* fix(agent-mode): don't reuse a project landing that captured stale instructions

The previous fix made the active landing refresh on a System-Prompt edit,
but enterProject's session-reuse path gated only on the materialization
dirty flag, which deliberately ignores systemPrompt. So editing a
non-active project's System Prompt then re-entering reused the old landing
and ran the next turn with stale captured instructions.

Track a per-session landing-capture signature (materialization signature +
instruction body) at creation and require a reuse candidate to match the
live project config. When spawning fresh, detach existing empty landings so
a stale blank one can't linger. Leaves the materialization dirty machinery
untouched (it must stay systemPrompt-insensitive). Adds a regression test.

* docs(agent-mode): note PR2 tag/extension routing and Tier-1 exclusion scope

Two DESIGN NOTEs at the project context materializer, recording decisions
already settled in PR2_DESIGN.md so future reviews don't re-flag them:
- tag/extension inclusions are forwarded as source labels and reached via the
  agent's native search; precise resolution (MCP tag_search) is a PR3 item.
- exclusions are Tier 1 (best-effort: don't materialize / don't feed); they do
  not hard-block the agent's native grep — that needs a Tier 2/3 sandbox,
  deferred past PR2.

* fix(agent-mode): let project sessions read opted-in off-vault context

The built-in project prompt's default-only-cwd rule buried its carve-out in
a negative clause, so agents read an off-vault materialized snapshot path
(~/.obsidian-copilot/.../context-cache/...) as a forbidden external file and
declined to read it — even though the project itself configured that source.

Restructure the built-in prompt by axis (write / read+exception / boundary)
and name the <project_context> block explicitly: sources listed there are
opt-in to read and search even outside cwd, and a -> <abs path> snapshot
pointer is read directly. Pin the cross-file <project_context> tag coupling
with a regression test that diffs the prompt against the manifest's real
output.

* refactor(agent-mode): unify agent context status into one shared view

Per-item conversion status (icon + label + lookup key) was duplicated across
three agent surfaces: the composer status popover, the Manage modal's Links
panel, and — newly needed — its File Context file list. Each had its own
status->icon mapping, and the file list had none at all (it was wired to the
CAG load atom, which the agent pipeline never populates, so agent files showed
no status while URLs did).

Introduce processingItemStatusView as the single source of truth
(processingSourceKey / buildProcessingItemLookup / getProcessingStatusLabel /
ProcessingStatusIcon) and route all three surfaces through it. The Manage modal
now builds one agent status lookup (gated to the agent variant) shared by both
the Links panel and the file list, so file rows finally show conversion status
keyed by file:<path>. The legacy CAG status stays separate (different cache,
different semantics). Adds useAgentProcessingItems({ enabled }) so CAG/mobile
callers skip the off-vault read entirely.

* feat(agent-mode): show conversion status + snapshot preview for project files

The context editor's File Context list showed no conversion status or preview
for agent project files, while the Links panel showed both for URLs — an
asymmetry, since file snapshots also live in the off-vault cache. Wire file
rows to the same agent status pipeline: a ready file now shows its status icon
and a 'view parsed content' arrow that opens the off-vault snapshot via
openAgentCachedItemPreview (the same opener URLs use). Markdown has no snapshot
so it shows neither; the CAG path is unchanged.

Collapse the per-prop enableLinks branching at the row into one
getFileRowStatusProps resolver (agent vs CAG dispatched once). Also corrects
stale comments flagged in review (STATUS_COLOR is CAG-badge-only; the agent
hook still subscribes to its atom but the value is unused when disabled).

* refactor(agent-mode): neutralize reviewer-dialogue comments; share source builder

Drop the "if a future review flags this, point them here" reviewer-meta
sentences from this branch's own comments (keeping all why/invariant
rationale), leaving the pre-existing base-convention instances untouched.

Extract buildAgentProcessingSources() so useAgentProcessingItems and
useAgentPersistentFailureCount construct the AgentProcessingSource[] shape
through one shared pure helper instead of two copies that could drift; each
hook still passes its own candidate set (draft vs saved), so behavior is
unchanged.

* fix(agent-mode): restore the <copilot-context> attachment envelope

The per-message attachment envelope was renamed <copilot-context> →
<attached_context> in an earlier feature commit (8b880361), bundled as an
incidental "disambiguate from <project_context>" tweak. That changed AI prompt
content emitted to EVERY agent chat (not just project-scoped ones) without an
explicit request, against the repo rule "Never modify AI prompt content unless
the user explicitly asks"; base v4-preview has used <copilot-context> since
Agent Mode was introduced. Revert the tag (the inner instruction text was
unchanged) so the established prompt contract is preserved. The two
claudeSessionTranscript tests already expected <copilot-context>, so this also
restores prod/test consistency.

* fix(agent-mode): supersede a stale in-flight context materialization on edit

The per-project single-flight let any non-force caller join the in-flight run
unconditionally. If a project's context was edited while an earlier
materialization was still running (slow URL/PDF conversion + a queued first
prompt), the next session joined the stale run and received the pre-edit
<project_context> / additionalDirectories — the queued send could flush with
the old source set, and the new links/files were only captured on a later chat.

Carry the run's context signature in the in-flight entry and join only when it
matches the caller's current record signature; a differing signature supersedes
via the existing take-over-slot path (which defers disk work until the prior run
settles, so no cache-file race). Regression test added to the single-flight
describe.

* fix(agent-mode): roll back project scope when auto-spawn fails

enterProject optimistically parks the prior scope, points activeProjectId
at the new project, detaches its tabs, and nulls activeSessionId before
awaiting the auto-spawn of the scope's first session. When that spawn
rejects (e.g. a missing backend binary), the callers only surface a
Notice, leaving the manager scoped to a project with no active chat until
the user manually recovers.

Wrap the project-scope auto-spawn in spawnEnteredScopeOrRollback, which
restores the previous scope's activeProjectId + active-session pointer and
re-notifies on failure, then rethrows so the caller still reports it. The
rollback is guarded on still being parked in the attempted scope so a
concurrent enterProject isn't clobbered — mirroring the existing
rollbackHistoryLoadScope precedent for the history-load path.

* fix(agent-mode): address review findings (URL trim perf, snapshot meta parse, docs)

Three PR-introduced fixes from the PR2 review plus a deferral note:

- urlTagUtils: rewrite trimUrlTrailingPunctuation from O(n²) (a full split
  scan per stripped char) to O(n) — pre-count brackets once, then walk the end
  pointer left. A pathological trailing-bracket paste no longer freezes the main
  thread. Semantics are unchanged (balanced brackets kept, unbalanced stripped,
  hidden punctuation re-trimmed). Adds a 100k perf tripwire test.

- contextCacheStore: anchor parseSnapshotMeta's close marker to a line boundary
  (\n--> ) instead of the first --> anywhere, which a source path containing -->
  would match inside the embedded JSON, truncating it and forcing a permanent
  cache miss. Adds a regression test.

- projects/state: correct doc comments — project.md is the SSOT, AGENTS.md is
  its generated mirror (was inverted).

- AgentSessionManager: DESIGN NOTE only — detached sessions on project re-entry
  are kept alive intentionally and not yet evicted; bounding the idle class is
  deferred (needs a per-session backend close primitive).
2026-06-28 00:33:22 -07:00

285 lines
11 KiB
TypeScript

/* eslint-disable obsidianmd/no-tfile-tfolder-cast -- test fixtures; not real TFiles */
import { AI_SENDER, USER_SENDER } from "@/constants";
import { AgentChatPersistenceManager } from "./AgentChatPersistenceManager";
import { GLOBAL_SCOPE } from "./scope";
import type { AgentChatMessage } from "./types";
import type { App, TFile } from "obsidian";
jest.mock("obsidian", () => ({
Notice: jest.fn(),
TFile: jest.fn(),
}));
jest.mock("@/logger");
jest.mock("@/settings/model", () => ({
getSettings: jest.fn().mockReturnValue({
defaultSaveFolder: "test-folder",
defaultConversationTag: "copilot-conversation",
defaultConversationNoteName: "{$date}_{$time}__{$topic}",
}),
}));
jest.mock("@/utils", () => ({
ensureFolderExists: jest.fn(async () => {}),
formatDateTime: jest.fn(() => ({
fileName: "20260101_120000",
display: "2026/01/01 12:00:00",
})),
getUtf8ByteLength: jest.fn((s: string) => new TextEncoder().encode(s).length),
truncateToByteLimit: jest.fn((s: string, n: number) => {
const bytes = new TextEncoder().encode(s);
if (bytes.length <= n) return s;
return new TextDecoder().decode(bytes.slice(0, n));
}),
}));
jest.mock("@/utils/vaultAdapterUtils", () => ({
isInVaultCache: jest.fn(() => false),
listMarkdownFiles: jest.fn().mockResolvedValue([]),
readFrontmatterViaAdapter: jest.fn().mockResolvedValue(null),
}));
interface FakeFile {
path: string;
basename: string;
contents?: string;
}
/**
* Build a minimal in-memory `app` mock that records files written via
* `vault.create` / `vault.adapter.write` so a round-trip save/load test can
* read what the previous step wrote without wiring real disk I/O.
*/
function makeApp() {
const files = new Map<string, FakeFile>();
return {
files,
vault: {
getAbstractFileByPath: jest.fn((path: string) => files.get(path) ?? null),
create: jest.fn(async (path: string, content: string) => {
const basename = path.split("/").pop()!.replace(/\.md$/, "");
const file = { path, basename, contents: content };
files.set(path, file);
return file;
}),
modify: jest.fn(async (file: FakeFile, content: string) => {
file.contents = content;
}),
read: jest.fn(async (file: FakeFile) => file.contents ?? ""),
delete: jest.fn(async (file: FakeFile) => {
files.delete(file.path);
}),
adapter: {
exists: jest.fn(async (path: string) => files.has(path)),
read: jest.fn(async (path: string) => files.get(path)?.contents ?? ""),
write: jest.fn(async (path: string, content: string) => {
const existing = files.get(path);
if (existing) {
existing.contents = content;
} else {
const basename = path.split("/").pop()!.replace(/\.md$/, "");
files.set(path, { path, basename, contents: content });
}
}),
remove: jest.fn(async (path: string) => {
files.delete(path);
}),
},
},
metadataCache: {
getFileCache: jest.fn(() => undefined),
},
fileManager: {
processFrontMatter: jest.fn(),
},
};
}
function makeMessage(sender: string, message: string, epoch = 1735732800000): AgentChatMessage {
return {
id: `msg-${epoch}`,
sender,
message,
isVisible: true,
timestamp: { epoch, display: "2026/01/01 12:00:00", fileName: "20260101_120000" },
};
}
describe("AgentChatPersistenceManager", () => {
let app: ReturnType<typeof makeApp>;
let manager: AgentChatPersistenceManager;
beforeEach(() => {
app = makeApp();
manager = new AgentChatPersistenceManager(app as unknown as App);
});
it("round-trips messages, backendId, and label", async () => {
const messages = [makeMessage(USER_SENDER, "hello world"), makeMessage(AI_SENDER, "hi back")];
const saved = await manager.saveSession(messages, "claude", { label: "My chat" });
expect(saved).not.toBeNull();
const file = app.files.get(saved!.path)!;
const loaded = await manager.loadFile(file as unknown as TFile);
expect(loaded.backendId).toBe("claude");
expect(loaded.label).toBe("My chat");
expect(loaded.messages).toHaveLength(2);
expect(loaded.messages[0].sender).toBe(USER_SENDER);
expect(loaded.messages[0].message).toBe("hello world");
expect(loaded.messages[1].sender).toBe(AI_SENDER);
expect(loaded.messages[1].message).toBe("hi back");
});
it("serializes a mid-stream fan-out turn so an interrupted autosave isn't blank", async () => {
// A long fan-out turn whose composite body has NOT been written to `message`
// yet (still streaming), saved mid-turn (reload/close/crash). The live fanout
// must be serialized so the streamed per-agent text survives, not a blank bubble.
const fanoutMsg: AgentChatMessage = {
id: "msg-2",
sender: AI_SENDER,
message: "",
isVisible: true,
timestamp: { epoch: 2, display: "2026/01/01 12:00:00", fileName: "20260101_120000" },
fanout: {
answers: {
opencode: { backendId: "opencode", status: "running", text: "partial opencode answer" },
},
summary: { status: "streaming", text: "" },
},
};
const saved = await manager.saveSession(
[makeMessage(USER_SENDER, "q"), fanoutMsg],
"claude",
{}
);
const file = app.files.get(saved!.path)!;
const loaded = await manager.loadFile(file as unknown as TFile);
expect(loaded.messages[1].message).toContain("partial opencode answer");
});
it("escapes and round-trips a label containing quotes and backslashes", async () => {
const tricky = 'has "quotes" and \\backslashes\\';
const messages = [makeMessage(USER_SENDER, "hi")];
const saved = await manager.saveSession(messages, "opencode", { label: tricky });
expect(saved).not.toBeNull();
const loaded = await manager.loadFile(app.files.get(saved!.path) as unknown as TFile);
expect(loaded.label).toBe(tricky);
});
it("strips control characters from labels so they can't break frontmatter", async () => {
const messages = [makeMessage(USER_SENDER, "hi")];
const saved = await manager.saveSession(messages, "opencode", {
label: "first\nsecond\rthird",
});
const raw = app.files.get(saved!.path)!.contents!;
// The label line must remain a single key:value entry.
const labelLines = raw.split("\n").filter((l) => l.startsWith("agentLabel:"));
expect(labelLines).toHaveLength(1);
const loaded = await manager.loadFile(app.files.get(saved!.path) as unknown as TFile);
expect(loaded.label).toBe("first second third");
});
it("throws on missing backendId instead of silently defaulting", async () => {
const path = "test-folder/agent__broken.md";
await app.vault.adapter.write(
path,
["---", "epoch: 1735732800000", "mode: agent", "---", "", "**user**: hi"].join("\n")
);
await expect(
manager.loadFile({ path, basename: "agent__broken" } as unknown as TFile)
).rejects.toThrow(/Missing backendId/);
});
it("assigns deterministic ids that depend only on message timestamp", async () => {
const messages = [
makeMessage(USER_SENDER, "first", 1700000000000),
makeMessage(AI_SENDER, "second", 1700000000001),
];
const saved = await manager.saveSession(messages, "claude");
const file = app.files.get(saved!.path)!;
const loadedA = await manager.loadFile(file as unknown as TFile);
const loadedB = await manager.loadFile(file as unknown as TFile);
// The key contract: same file + same content → same ids across reloads.
expect(loadedA.messages.map((m) => m.id)).toEqual(loadedB.messages.map((m) => m.id));
expect(loadedA.messages[0].id.startsWith("loaded-0-")).toBe(true);
});
it("returns null when given zero messages instead of writing an empty file", async () => {
const result = await manager.saveSession([], "opencode");
expect(result).toBeNull();
expect(app.files.size).toBe(0);
});
describe("projectId scope round-trip", () => {
it("round-trips a real projectId for a project-scoped chat", async () => {
const messages = [makeMessage(USER_SENDER, "hi")];
const saved = await manager.saveSession(messages, "claude", { projectId: "proj-123" });
expect(saved).not.toBeNull();
const raw = app.files.get(saved!.path)!.contents!;
expect(raw).toContain('projectId: "proj-123"');
const loaded = await manager.loadFile(app.files.get(saved!.path) as unknown as TFile);
expect(loaded.projectId).toBe("proj-123");
});
it("defaults an unscoped chat to GLOBAL_SCOPE and writes no projectId (hard contract)", async () => {
const messages = [makeMessage(USER_SENDER, "hi")];
const saved = await manager.saveSession(messages, "claude");
const raw = app.files.get(saved!.path)!.contents!;
expect(raw).not.toContain("projectId:");
const loaded = await manager.loadFile(app.files.get(saved!.path) as unknown as TFile);
expect(loaded.projectId).toBe(GLOBAL_SCOPE);
});
it("treats an explicit GLOBAL_SCOPE like an unscoped chat (no projectId frontmatter)", async () => {
const messages = [makeMessage(USER_SENDER, "hi")];
const saved = await manager.saveSession(messages, "claude", { projectId: GLOBAL_SCOPE });
const raw = app.files.get(saved!.path)!.contents!;
expect(raw).not.toContain("projectId:");
const loaded = await manager.loadFile(app.files.get(saved!.path) as unknown as TFile);
expect(loaded.projectId).toBe(GLOBAL_SCOPE);
});
it("treats a blank projectId option like an unscoped chat", async () => {
const messages = [makeMessage(USER_SENDER, "hi")];
const saved = await manager.saveSession(messages, "claude", { projectId: " " });
const raw = app.files.get(saved!.path)!.contents!;
expect(raw).not.toContain("projectId:");
const loaded = await manager.loadFile(app.files.get(saved!.path) as unknown as TFile);
expect(loaded.projectId).toBe(GLOBAL_SCOPE);
});
it("normalizes a padded projectId option before writing frontmatter", async () => {
const messages = [makeMessage(USER_SENDER, "hi")];
const saved = await manager.saveSession(messages, "claude", { projectId: " proj-123 " });
const raw = app.files.get(saved!.path)!.contents!;
expect(raw).toContain('projectId: "proj-123"');
expect(raw).not.toContain('projectId: " proj-123 "');
const loaded = await manager.loadFile(app.files.get(saved!.path) as unknown as TFile);
expect(loaded.projectId).toBe("proj-123");
});
it("maps a legacy agent__ chat with no projectId frontmatter to GLOBAL_SCOPE", async () => {
const path = "test-folder/agent__legacy.md";
await app.vault.adapter.write(
path,
[
"---",
"epoch: 1735732800000",
"mode: agent",
"backendId: claude",
"---",
"",
"**user**: hi",
].join("\n")
);
// Reason: the stored file carries `contents`, so loadFile's vault.read
// path returns the frontmatter (a bare {path} fixture would read empty).
const loaded = await manager.loadFile(app.files.get(path) as unknown as TFile);
expect(loaded.projectId).toBe(GLOBAL_SCOPE);
});
});
});