feat(knowledge): rebuild the project notes panel as Project knowledge (#2973)
The panel stored notes, todos and plans inside one shared JSON file that six unrelated domains also wrote to, synchronised itself through window CustomEvents, and could only read plans. It is now Project knowledge: server-owned storage with explicit routes, a store with rollback, a section sidebar, plans that open and edit in place, and search across all of it. Notes and plans the user pins travel with every message sent in that project. Pinning is project state, not an attachment to one message, so it holds until unpinned and the work status panel names what is riding along and can detach it. Agent memory is added alongside, in two scopes: what is true about the user, and what is true about this codebase. The split is not cosmetic — a wrong project fact costs one project and is noticed, while a wrong global fact quietly shapes every session everywhere and the user has no code to check it against. It stays separate from notes so an agent mistake cannot land in what the user wrote. Sessions receive an index of titles only; bodies are read on demand, because an index carrying full text grows until it crowds out the conversation. Deciding what a session must be told, and whether it has been told, now lives on the server. The client owned it before, which meant sessions started without a UI — scheduled tasks, sessions the agent dispatches — received nothing at all, and a tab's record of what it had sent outlived the conversation: after compaction the agent no longer held the block while the tab went on believing it did. What was delivered is recorded in the session's own metadata, and compaction restores it through the runtime that already restores pinned messages, in the same turn. Agent memory ships dark behind OPENCHAMBER_MEMORY_ENABLE: unset, there is no tool, no routes, no session index, no settings row and no panel tab. Absent rather than switched off, so nothing invites turning on a feature that has not been announced. Pinned notes and plans are unaffected and ship as normal.
This commit is contained in:
committed by
GitHub
parent
7611076436
commit
34e8a24b20
@@ -57,10 +57,13 @@ Examples:
|
||||
- `useProjectsStore.ts`
|
||||
- `useGlobalSessionsStore.ts`
|
||||
- `useSessionFoldersStore.ts`
|
||||
- `useProjectContextStore.ts`
|
||||
- `messageQueueStore.ts`
|
||||
|
||||
These stores coordinate persistent project/session metadata across multiple views.
|
||||
|
||||
`useProjectContextStore.ts` caches server-owned project notes, todos, and plan links, keyed by the path-derived project id. It replaced a pair of `window` CustomEvents that made every mounted notes panel re-read the whole project config. Writes are optimistic and roll back on failure; they are serialized per project, because the server's own store does a read-modify-write and two concurrent saves would otherwise race it. A load that resolves while a write is in flight keeps the local value for that field group only, so a slow snapshot cannot undo newer typing while still delivering the plan list it fetched. A failed load sets `error` and preserves the cached snapshot — an unreachable server must never render as "this project has no notes". Note and plan creation are deliberately not optimistic, since ids and timestamps are assigned by the server. Notes, todos, and plans are written through separate routes and tracked by separate in-flight flags, so a todo toggle cannot clobber a note edit in the same window. Pinned notes and plans are assembled into a synthetic context part by `lib/projectContextPinning.ts` at send time; that module tracks per-session what it already sent so an unchanged pinned set is not re-sent every turn.
|
||||
|
||||
`messageQueueStore.ts` keeps a queued message until its own send resolves, so between dispatch and resolution the entry is still visible to every reader. Dispatchers must therefore mark the send (`markSending`/`clearSending`) and read `getSendableQueue()` — or filter `sendingIds` themselves — instead of dispatching straight from `queuedMessages`; otherwise a composer submit merges a message the auto-send hook is already delivering and it is sent twice (the window is seconds over a relay). `clearQueue()` retains in-flight entries for the same reason. `sendingIds` is deliberately not persisted: a restart has no in-flight sends, and a stale flag would strand a queued message.
|
||||
|
||||
`useGlobalSessionsStore.ts` owns cold/global active and archived session coverage, including `sessionsByDirectory`. It is complementary to directory child stores: it is not the source of live busy/retry status or session messages.
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
|
||||
|
||||
import { AgentMemoryDisabledError, type AgentMemoryEntry } from '@/lib/agentMemoryApi';
|
||||
|
||||
function entry(overrides: Partial<AgentMemoryEntry> = {}): AgentMemoryEntry {
|
||||
return {
|
||||
id: 'mem-1',
|
||||
title: 'Uses bun',
|
||||
body: 'Tests run with bun test.',
|
||||
type: 'fact',
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
interface MemoryReadResult {
|
||||
global: AgentMemoryEntry[];
|
||||
project: AgentMemoryEntry[];
|
||||
globalFailed: boolean;
|
||||
projectFailed: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Swappable implementations rather than mock helpers: each test states the one
|
||||
* behaviour it needs.
|
||||
*/
|
||||
let readImpl: () => Promise<MemoryReadResult>;
|
||||
let deleteImpl: () => Promise<void>;
|
||||
let updateImpl: (memoryId: string, patch: Record<string, unknown>) => Promise<AgentMemoryEntry>;
|
||||
let lastPatch: Record<string, unknown> | null = null;
|
||||
|
||||
mock.module('@/lib/agentMemoryApi', () => ({
|
||||
AgentMemoryDisabledError,
|
||||
fetchAgentMemory: () => readImpl(),
|
||||
deleteAgentMemory: () => deleteImpl(),
|
||||
updateAgentMemory: (
|
||||
_scope: string,
|
||||
_projectPath: string | null,
|
||||
memoryId: string,
|
||||
patch: Record<string, unknown>,
|
||||
) => {
|
||||
lastPatch = patch;
|
||||
return updateImpl(memoryId, patch);
|
||||
},
|
||||
}));
|
||||
|
||||
const { useAgentMemoryStore } = await import('./useAgentMemoryStore');
|
||||
|
||||
beforeEach(() => {
|
||||
useAgentMemoryStore.getState().reset();
|
||||
readImpl = async () => ({
|
||||
global: [entry({ id: 'g1', title: 'About user' })],
|
||||
project: [entry({ id: 'p1', title: 'About project' })],
|
||||
globalFailed: false,
|
||||
projectFailed: false,
|
||||
});
|
||||
deleteImpl = async () => undefined;
|
||||
updateImpl = async (memoryId, patch) => ({ ...entry({ id: memoryId }), ...patch });
|
||||
lastPatch = null;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useAgentMemoryStore.getState().reset();
|
||||
});
|
||||
|
||||
describe('load', () => {
|
||||
test('holds both scopes', async () => {
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
|
||||
const state = useAgentMemoryStore.getState();
|
||||
expect(state.global.map((item) => item.id)).toEqual(['g1']);
|
||||
expect(state.project.map((item) => item.id)).toEqual(['p1']);
|
||||
expect(state.loaded).toBe(true);
|
||||
});
|
||||
|
||||
test('a failed load keeps what was already held', async () => {
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
readImpl = async () => { throw new Error('offline'); };
|
||||
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
|
||||
const state = useAgentMemoryStore.getState();
|
||||
// Blanking here would read as the agent having forgotten everything.
|
||||
expect(state.global).toHaveLength(1);
|
||||
expect(state.error).toBe('offline');
|
||||
});
|
||||
|
||||
test('a disabled feature clears the lists rather than reporting an error', async () => {
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
readImpl = async () => { throw new AgentMemoryDisabledError(); };
|
||||
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
|
||||
const state = useAgentMemoryStore.getState();
|
||||
expect(state.disabled).toBe(true);
|
||||
expect(state.global).toHaveLength(0);
|
||||
expect(state.error).toBeNull();
|
||||
});
|
||||
|
||||
test('a partly failed read is recorded as failed, not as empty', async () => {
|
||||
readImpl = async () => ({ global: [], project: [], globalFailed: true, projectFailed: false });
|
||||
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
|
||||
expect(useAgentMemoryStore.getState().globalFailed).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
test('removes the entry', async () => {
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
|
||||
const ok = await useAgentMemoryStore.getState().deleteEntry('project', 'p1');
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(useAgentMemoryStore.getState().project).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('restores the entry when the delete fails', async () => {
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
deleteImpl = async () => { throw new Error('offline'); };
|
||||
|
||||
const ok = await useAgentMemoryStore.getState().deleteEntry('project', 'p1');
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(useAgentMemoryStore.getState().project).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('user corrections', () => {
|
||||
test('sends only what changed and adopts the saved entry', async () => {
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
|
||||
const ok = await useAgentMemoryStore.getState().saveEntry('project', 'p1', { body: 'Reworded.' });
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(lastPatch).toEqual({ body: 'Reworded.' });
|
||||
expect(useAgentMemoryStore.getState().project[0].body).toBe('Reworded.');
|
||||
});
|
||||
|
||||
test('a failed save leaves the entry as it was', async () => {
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
updateImpl = async () => { throw new Error('offline'); };
|
||||
|
||||
const ok = await useAgentMemoryStore.getState().saveEntry('project', 'p1', { body: 'Reworded.' });
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(useAgentMemoryStore.getState().project[0].body).toBe('Tests run with bun test.');
|
||||
expect(useAgentMemoryStore.getState().error).toBe('offline');
|
||||
});
|
||||
|
||||
test('touches only the scope it was given', async () => {
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
|
||||
await useAgentMemoryStore.getState().saveEntry('project', 'p1', { title: 'Clearer' });
|
||||
|
||||
expect(useAgentMemoryStore.getState().global[0].title).toBe('About user');
|
||||
});
|
||||
});
|
||||
|
||||
describe('turning the feature off and on', () => {
|
||||
test('a successful load clears the disabled flag', async () => {
|
||||
readImpl = async () => { throw new AgentMemoryDisabledError(); };
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
expect(useAgentMemoryStore.getState().disabled).toBe(true);
|
||||
|
||||
readImpl = async () => ({
|
||||
global: [entry({ id: 'g1' })], project: [], globalFailed: false, projectFailed: false,
|
||||
});
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
|
||||
expect(useAgentMemoryStore.getState().disabled).toBe(false);
|
||||
});
|
||||
|
||||
test('refresh re-reads the store the last load used', async () => {
|
||||
readImpl = async () => { throw new AgentMemoryDisabledError(); };
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
|
||||
let requestedPath: string | null = 'unset';
|
||||
readImpl = async () => {
|
||||
requestedPath = useAgentMemoryStore.getState().projectPath;
|
||||
return { global: [], project: [], globalFailed: false, projectFailed: false };
|
||||
};
|
||||
await useAgentMemoryStore.getState().refresh();
|
||||
|
||||
// The disabled answer must not lose the path, or refresh reads the wrong store.
|
||||
expect(requestedPath).toBe('/tmp/project');
|
||||
});
|
||||
|
||||
test('a stale disabled answer cannot latch the feature off again', async () => {
|
||||
// Re-enabling fires a load before the setting has finished being written,
|
||||
// so the server truthfully answers "disabled" to a request that is already
|
||||
// out of date by the time it lands.
|
||||
const gate: { release?: () => void } = {};
|
||||
readImpl = () => new Promise((_resolve, reject) => {
|
||||
gate.release = () => reject(new AgentMemoryDisabledError());
|
||||
});
|
||||
const stale = useAgentMemoryStore.getState().load('/tmp/project');
|
||||
|
||||
readImpl = async () => ({
|
||||
global: [entry({ id: 'g1' })], project: [], globalFailed: false, projectFailed: false,
|
||||
});
|
||||
await useAgentMemoryStore.getState().load('/tmp/project');
|
||||
|
||||
gate.release?.();
|
||||
await stale;
|
||||
|
||||
expect(useAgentMemoryStore.getState().disabled).toBe(false);
|
||||
expect(useAgentMemoryStore.getState().global).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* Agent memory, as the panel and the send path see it.
|
||||
*
|
||||
* The server owns the store; this holds the last snapshot read from it and
|
||||
* serializes writes so two quick edits cannot land out of order.
|
||||
*
|
||||
* A failed load never blanks what is already held. An empty list would read as
|
||||
* "the agent has forgotten everything", which is the one wrong answer here: the
|
||||
* user would go looking for lost memory that is sitting safely on disk.
|
||||
*/
|
||||
|
||||
import { create } from 'zustand';
|
||||
|
||||
import {
|
||||
AgentMemoryDisabledError,
|
||||
deleteAgentMemory,
|
||||
fetchAgentMemory,
|
||||
updateAgentMemory,
|
||||
type AgentMemoryEntry,
|
||||
type AgentMemoryScope,
|
||||
} from '@/lib/agentMemoryApi';
|
||||
|
||||
interface AgentMemoryState {
|
||||
global: AgentMemoryEntry[];
|
||||
project: AgentMemoryEntry[];
|
||||
/** The project path the held `project` entries belong to. */
|
||||
projectPath: string | null;
|
||||
loading: boolean;
|
||||
loaded: boolean;
|
||||
/** True once the server has reported the feature switched off. */
|
||||
disabled: boolean;
|
||||
globalFailed: boolean;
|
||||
projectFailed: boolean;
|
||||
error: string | null;
|
||||
|
||||
load: (projectPath: string | null) => Promise<void>;
|
||||
/** Re-read the store the last load used. */
|
||||
refresh: () => Promise<void>;
|
||||
saveEntry: (
|
||||
scope: AgentMemoryScope,
|
||||
memoryId: string,
|
||||
patch: { title?: string; body?: string },
|
||||
) => Promise<boolean>;
|
||||
deleteEntry: (scope: AgentMemoryScope, memoryId: string) => Promise<boolean>;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
const EMPTY_STATE = {
|
||||
global: [] as AgentMemoryEntry[],
|
||||
project: [] as AgentMemoryEntry[],
|
||||
projectPath: null as string | null,
|
||||
loading: false,
|
||||
loaded: false,
|
||||
disabled: false,
|
||||
globalFailed: false,
|
||||
projectFailed: false,
|
||||
error: null as string | null,
|
||||
};
|
||||
|
||||
/**
|
||||
* Only the newest load may write to the store. Turning the feature back on
|
||||
* fires a load before the setting has finished being written, so an older
|
||||
* "disabled" answer can arrive after a newer successful one and latch the
|
||||
* feature off again.
|
||||
*/
|
||||
let loadSequence = 0;
|
||||
|
||||
/** Serializes writes so a slow first request cannot overwrite a later one. */
|
||||
let writeChain: Promise<unknown> = Promise.resolve();
|
||||
const enqueueWrite = <T>(work: () => Promise<T>): Promise<T> => {
|
||||
const next = writeChain.then(work, work);
|
||||
writeChain = next.catch(() => undefined);
|
||||
return next;
|
||||
};
|
||||
|
||||
const listFor = (state: AgentMemoryState, scope: AgentMemoryScope): AgentMemoryEntry[] => (
|
||||
scope === 'global' ? state.global : state.project
|
||||
);
|
||||
|
||||
const withList = (
|
||||
scope: AgentMemoryScope,
|
||||
entries: AgentMemoryEntry[],
|
||||
): Partial<AgentMemoryState> => (
|
||||
scope === 'global' ? { global: entries } : { project: entries }
|
||||
);
|
||||
|
||||
const errorMessage = (error: unknown, fallback: string): string => (
|
||||
error instanceof Error && error.message ? error.message : fallback
|
||||
);
|
||||
|
||||
export const useAgentMemoryStore = create<AgentMemoryState>((set, get) => ({
|
||||
...EMPTY_STATE,
|
||||
|
||||
load: async (projectPath) => {
|
||||
const requestId = ++loadSequence;
|
||||
set({ loading: true, projectPath });
|
||||
try {
|
||||
const snapshot = await fetchAgentMemory(projectPath);
|
||||
if (requestId !== loadSequence) return;
|
||||
set({
|
||||
global: snapshot.global,
|
||||
project: snapshot.project,
|
||||
projectPath,
|
||||
globalFailed: snapshot.globalFailed,
|
||||
projectFailed: snapshot.projectFailed,
|
||||
loading: false,
|
||||
loaded: true,
|
||||
disabled: false,
|
||||
error: null,
|
||||
});
|
||||
} catch (error) {
|
||||
if (requestId !== loadSequence) return;
|
||||
if (error instanceof AgentMemoryDisabledError) {
|
||||
// Switched off is not a failure. Clearing the lists is right here and
|
||||
// only here: with the feature off there is nothing for the user to act
|
||||
// on, and the tab that would show them is gone too. The path is kept so
|
||||
// a later refresh knows which store to re-read.
|
||||
set({ ...EMPTY_STATE, projectPath, disabled: true, loaded: true });
|
||||
return;
|
||||
}
|
||||
// Whatever was loaded before stays. Only the error is new.
|
||||
set({ loading: false, error: errorMessage(error, 'Failed to load agent memory') });
|
||||
}
|
||||
},
|
||||
|
||||
refresh: async () => {
|
||||
await get().load(get().projectPath);
|
||||
},
|
||||
|
||||
saveEntry: async (scope, memoryId, patch) => enqueueWrite(async () => {
|
||||
const previous = listFor(get(), scope);
|
||||
try {
|
||||
const saved = await updateAgentMemory(scope, get().projectPath, memoryId, patch);
|
||||
set(withList(scope, listFor(get(), scope).map((entry) => (entry.id === memoryId ? saved : entry))));
|
||||
return true;
|
||||
} catch (error) {
|
||||
set({ ...withList(scope, previous), error: errorMessage(error, 'Failed to save memory') });
|
||||
return false;
|
||||
}
|
||||
}),
|
||||
|
||||
deleteEntry: async (scope, memoryId) => enqueueWrite(async () => {
|
||||
const previous = listFor(get(), scope);
|
||||
set(withList(scope, previous.filter((entry) => entry.id !== memoryId)));
|
||||
|
||||
try {
|
||||
await deleteAgentMemory(scope, get().projectPath, memoryId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
set({ ...withList(scope, previous), error: errorMessage(error, 'Failed to delete memory') });
|
||||
return false;
|
||||
}
|
||||
}),
|
||||
|
||||
reset: () => {
|
||||
set({ ...EMPTY_STATE });
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
import { beforeEach, describe, expect, mock, test } from 'bun:test';
|
||||
|
||||
interface NotePayload {
|
||||
id: string;
|
||||
body: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
source: 'manual' | 'selection' | 'agent';
|
||||
pinned: boolean;
|
||||
}
|
||||
|
||||
interface ContextPayload {
|
||||
notes: NotePayload[];
|
||||
todos: { id: string; text: string; completed: boolean; createdAt: number }[];
|
||||
plans: { id: string; file: string; title: string; createdAt: number; pinned: boolean }[];
|
||||
}
|
||||
|
||||
const emptyPayload = (): ContextPayload => ({ notes: [], todos: [], plans: [] });
|
||||
|
||||
const note = (overrides: Partial<NotePayload> = {}): NotePayload => ({
|
||||
id: 'n1',
|
||||
body: 'body',
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
source: 'manual',
|
||||
pinned: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const planLink = (overrides: Partial<ContextPayload['plans'][number]> = {}) => ({
|
||||
id: 'p1',
|
||||
file: 'a.md',
|
||||
title: 'A',
|
||||
createdAt: 1,
|
||||
pinned: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
// The UI tsconfig does not load bun's test globals, so these tests follow the
|
||||
// local precedent of swapping plain handlers instead of using mock helpers.
|
||||
const handlers = {
|
||||
fetch: async (): Promise<ContextPayload> => emptyPayload(),
|
||||
saveTodos: async (todos: ContextPayload['todos']): Promise<ContextPayload> => ({
|
||||
notes: [],
|
||||
todos,
|
||||
plans: [],
|
||||
}),
|
||||
createNote: async (): Promise<{ note: NotePayload; context: ContextPayload }> => ({
|
||||
note: note(),
|
||||
context: { notes: [note()], todos: [], plans: [] },
|
||||
}),
|
||||
updateNote: async (): Promise<NotePayload | null> => note(),
|
||||
deleteNote: async (): Promise<ContextPayload> => emptyPayload(),
|
||||
create: async (): Promise<{ plan: ContextPayload['plans'][number]; context: ContextPayload }> => ({
|
||||
plan: planLink(),
|
||||
context: { notes: [], todos: [], plans: [planLink()] },
|
||||
}),
|
||||
update: async (): Promise<{ plan: ContextPayload['plans'][number]; raw: string } | null> => ({
|
||||
plan: planLink(),
|
||||
raw: '# A',
|
||||
}),
|
||||
pinPlan: async (): Promise<ContextPayload['plans'][number] | null> => planLink({ pinned: true }),
|
||||
remove: async (): Promise<ContextPayload> => emptyPayload(),
|
||||
};
|
||||
|
||||
const calls = { fetch: 0, saveTodos: 0, createNote: 0, updateNote: 0, deleteNote: 0, create: 0, update: 0, pinPlan: 0, remove: 0 };
|
||||
|
||||
mock.module('@/lib/projectContextApi', () => ({
|
||||
fetchProjectContext: () => {
|
||||
calls.fetch += 1;
|
||||
return handlers.fetch();
|
||||
},
|
||||
saveProjectTodos: (_project: unknown, todos: ContextPayload['todos']) => {
|
||||
calls.saveTodos += 1;
|
||||
return handlers.saveTodos(todos);
|
||||
},
|
||||
createProjectNote: () => {
|
||||
calls.createNote += 1;
|
||||
return handlers.createNote();
|
||||
},
|
||||
updateProjectNote: () => {
|
||||
calls.updateNote += 1;
|
||||
return handlers.updateNote();
|
||||
},
|
||||
deleteProjectNote: () => {
|
||||
calls.deleteNote += 1;
|
||||
return handlers.deleteNote();
|
||||
},
|
||||
setProjectPlanPinned: () => {
|
||||
calls.pinPlan += 1;
|
||||
return handlers.pinPlan();
|
||||
},
|
||||
createProjectPlan: () => {
|
||||
calls.create += 1;
|
||||
return handlers.create();
|
||||
},
|
||||
updateProjectPlan: () => {
|
||||
calls.update += 1;
|
||||
return handlers.update();
|
||||
},
|
||||
deleteProjectPlan: () => {
|
||||
calls.remove += 1;
|
||||
return handlers.remove();
|
||||
},
|
||||
resolveProjectContextId: (project: { path?: string } | null | undefined) => (
|
||||
project?.path ? `path_${project.path}` : ''
|
||||
),
|
||||
}));
|
||||
|
||||
const { useProjectContextStore } = await import('./useProjectContextStore');
|
||||
|
||||
const PROJECT = { id: 'ignored', path: '/repo' };
|
||||
const store = () => useProjectContextStore.getState();
|
||||
const entry = () => store().getEntry(PROJECT);
|
||||
|
||||
const deferred = <T>() => {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((res) => { resolve = res; });
|
||||
return { promise, resolve };
|
||||
};
|
||||
|
||||
const failWith = (message: string) => async (): Promise<never> => {
|
||||
throw new Error(message);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
store().reset();
|
||||
calls.fetch = 0;
|
||||
calls.saveTodos = 0;
|
||||
calls.createNote = 0;
|
||||
calls.updateNote = 0;
|
||||
calls.deleteNote = 0;
|
||||
calls.create = 0;
|
||||
calls.update = 0;
|
||||
calls.pinPlan = 0;
|
||||
calls.remove = 0;
|
||||
|
||||
handlers.fetch = async () => emptyPayload();
|
||||
handlers.saveTodos = async (todos) => ({ notes: [], todos, plans: [] });
|
||||
handlers.createNote = async () => ({ note: note(), context: { notes: [note()], todos: [], plans: [] } });
|
||||
handlers.updateNote = async () => note();
|
||||
handlers.deleteNote = async () => emptyPayload();
|
||||
handlers.create = async () => ({ plan: planLink(), context: { notes: [], todos: [], plans: [planLink()] } });
|
||||
handlers.update = async () => ({ plan: planLink(), raw: '# A' });
|
||||
handlers.pinPlan = async () => planLink({ pinned: true });
|
||||
handlers.remove = async () => emptyPayload();
|
||||
});
|
||||
|
||||
describe('getEntry', () => {
|
||||
test('returns a stable empty entry for an unknown project', () => {
|
||||
expect(entry()).toEqual({ notes: [], todos: [], plans: [], loaded: false, loading: false, error: null });
|
||||
});
|
||||
|
||||
test('returns the empty entry for a project without a path', () => {
|
||||
expect(store().getEntry({ id: 'x', path: '' }).loaded).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('load', () => {
|
||||
test('populates from the server', async () => {
|
||||
handlers.fetch = async () => ({
|
||||
notes: [note({ body: 'server note' })],
|
||||
todos: [{ id: 't1', text: 'a', completed: false, createdAt: 1 }],
|
||||
plans: [planLink()],
|
||||
});
|
||||
|
||||
await store().load(PROJECT);
|
||||
|
||||
expect(entry().notes.map((entryNote) => entryNote.body)).toEqual(['server note']);
|
||||
expect(entry().todos).toHaveLength(1);
|
||||
expect(entry().plans).toHaveLength(1);
|
||||
expect(entry().loaded).toBe(true);
|
||||
expect(entry().error).toBeNull();
|
||||
});
|
||||
|
||||
test('does not refetch once loaded', async () => {
|
||||
await store().load(PROJECT);
|
||||
await store().load(PROJECT);
|
||||
expect(calls.fetch).toBe(1);
|
||||
});
|
||||
|
||||
test('refetches when forced', async () => {
|
||||
await store().load(PROJECT);
|
||||
await store().load(PROJECT, { force: true });
|
||||
expect(calls.fetch).toBe(2);
|
||||
});
|
||||
|
||||
test('a failed load preserves previously loaded data instead of clearing it', async () => {
|
||||
handlers.fetch = async () => ({ notes: [note({ body: 'kept' })], todos: [], plans: [] });
|
||||
await store().load(PROJECT);
|
||||
|
||||
handlers.fetch = failWith('offline');
|
||||
await store().load(PROJECT, { force: true });
|
||||
|
||||
expect(entry().notes.map((entryNote) => entryNote.body)).toEqual(['kept']);
|
||||
expect(entry().loaded).toBe(true);
|
||||
expect(entry().error).toBe('offline');
|
||||
});
|
||||
|
||||
test('a first-load failure reports the error and stays unloaded', async () => {
|
||||
handlers.fetch = failWith('boom');
|
||||
|
||||
await store().load(PROJECT);
|
||||
|
||||
expect(entry().loaded).toBe(false);
|
||||
expect(entry().notes).toEqual([]);
|
||||
expect(entry().error).toBe('boom');
|
||||
});
|
||||
|
||||
test('concurrent loads issue a single request', async () => {
|
||||
await Promise.all([store().load(PROJECT), store().load(PROJECT), store().load(PROJECT)]);
|
||||
expect(calls.fetch).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('saveTodos', () => {
|
||||
test('applies optimistically before the request resolves', async () => {
|
||||
const gate = deferred<ContextPayload>();
|
||||
handlers.saveTodos = () => gate.promise;
|
||||
|
||||
const pending = store().saveTodos(PROJECT, [{ id: 't1', text: 'typed', completed: false, createdAt: 1 }]);
|
||||
expect(entry().todos).toHaveLength(1);
|
||||
|
||||
gate.resolve({ notes: [], todos: [{ id: 't1', text: 'typed', completed: false, createdAt: 1 }], plans: [] });
|
||||
expect(await pending).toBe(true);
|
||||
expect(entry().todos).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('rolls back and reports the error on failure', async () => {
|
||||
await store().saveTodos(PROJECT, [{ id: 't1', text: 'original', completed: false, createdAt: 1 }]);
|
||||
handlers.saveTodos = failWith('disk full');
|
||||
|
||||
expect(await store().saveTodos(PROJECT, [])).toBe(false);
|
||||
expect(entry().todos.map((todo) => todo.text)).toEqual(['original']);
|
||||
expect(entry().error).toBe('disk full');
|
||||
});
|
||||
|
||||
test('serializes concurrent writes in call order', async () => {
|
||||
const order: string[] = [];
|
||||
handlers.saveTodos = async (todos) => {
|
||||
const label = todos[0]?.text ?? 'empty';
|
||||
order.push(`start:${label}`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
order.push(`end:${label}`);
|
||||
return { notes: [], todos, plans: [] };
|
||||
};
|
||||
|
||||
await Promise.all([
|
||||
store().saveTodos(PROJECT, [{ id: '1', text: 'first', completed: false, createdAt: 1 }]),
|
||||
store().saveTodos(PROJECT, [{ id: '2', text: 'second', completed: false, createdAt: 2 }]),
|
||||
]);
|
||||
|
||||
expect(order).toEqual(['start:first', 'end:first', 'start:second', 'end:second']);
|
||||
});
|
||||
|
||||
test('a load resolving during an in-flight write does not clobber it', async () => {
|
||||
const gate = deferred<ContextPayload>();
|
||||
handlers.saveTodos = () => gate.promise;
|
||||
handlers.fetch = async () => ({
|
||||
notes: [note({ body: 'from server' })],
|
||||
todos: [{ id: 'stale', text: 'stale', completed: false, createdAt: 0 }],
|
||||
plans: [],
|
||||
});
|
||||
|
||||
const pending = store().saveTodos(PROJECT, [{ id: 'local', text: 'local', completed: false, createdAt: 1 }]);
|
||||
await store().load(PROJECT);
|
||||
|
||||
expect(entry().todos.map((todo) => todo.id)).toEqual(['local']);
|
||||
// The same snapshot still delivers the fields the write did not touch.
|
||||
expect(entry().notes.map((entryNote) => entryNote.body)).toEqual(['from server']);
|
||||
|
||||
gate.resolve({ notes: [], todos: [{ id: 'local', text: 'local', completed: false, createdAt: 1 }], plans: [] });
|
||||
await pending;
|
||||
});
|
||||
|
||||
test('ignores a project without a resolvable path', async () => {
|
||||
expect(await store().saveTodos({ id: 'x', path: '' }, [])).toBe(false);
|
||||
expect(calls.saveTodos).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('notes', () => {
|
||||
test('createNote adopts the committed list', async () => {
|
||||
handlers.createNote = async () => ({
|
||||
note: note({ id: 'n9', body: 'fresh' }),
|
||||
context: { notes: [note({ id: 'n9', body: 'fresh' })], todos: [], plans: [] },
|
||||
});
|
||||
|
||||
const created = await store().createNote(PROJECT, { body: 'fresh' });
|
||||
expect(created?.id).toBe('n9');
|
||||
expect(entry().notes.map((entryNote) => entryNote.id)).toEqual(['n9']);
|
||||
});
|
||||
|
||||
test('createNote refuses a whitespace-only body without calling the server', async () => {
|
||||
expect(await store().createNote(PROJECT, { body: ' ' })).toBeNull();
|
||||
expect(calls.createNote).toBe(0);
|
||||
});
|
||||
|
||||
test('createNote reports failure without inserting a placeholder row', async () => {
|
||||
handlers.createNote = failWith('no space');
|
||||
|
||||
expect(await store().createNote(PROJECT, { body: 'x' })).toBeNull();
|
||||
expect(entry().notes).toEqual([]);
|
||||
expect(entry().error).toBe('no space');
|
||||
});
|
||||
|
||||
test('saveNoteBody applies optimistically and commits the server copy', async () => {
|
||||
await store().createNote(PROJECT, { body: 'before' });
|
||||
handlers.updateNote = async () => note({ body: 'after', updatedAt: 9 });
|
||||
|
||||
expect(await store().saveNoteBody(PROJECT, 'n1', 'after')).toBe(true);
|
||||
expect(entry().notes[0].body).toBe('after');
|
||||
expect(entry().notes[0].updatedAt).toBe(9);
|
||||
});
|
||||
|
||||
test('saveNoteBody rolls back on failure', async () => {
|
||||
await store().createNote(PROJECT, { body: 'before' });
|
||||
handlers.updateNote = failWith('read only');
|
||||
|
||||
expect(await store().saveNoteBody(PROJECT, 'n1', 'after')).toBe(false);
|
||||
expect(entry().notes[0].body).toBe('body');
|
||||
expect(entry().error).toBe('read only');
|
||||
});
|
||||
|
||||
test('saveNoteBody drops a note the server reports as gone', async () => {
|
||||
await store().createNote(PROJECT, { body: 'before' });
|
||||
handlers.updateNote = async () => null;
|
||||
|
||||
expect(await store().saveNoteBody(PROJECT, 'n1', 'after')).toBe(false);
|
||||
expect(entry().notes).toEqual([]);
|
||||
});
|
||||
|
||||
test('setNotePinned applies optimistically', async () => {
|
||||
await store().createNote(PROJECT, { body: 'x' });
|
||||
const gate = deferred<NotePayload | null>();
|
||||
handlers.updateNote = () => gate.promise;
|
||||
|
||||
const pending = store().setNotePinned(PROJECT, 'n1', true);
|
||||
expect(entry().notes[0].pinned).toBe(true);
|
||||
|
||||
gate.resolve(note({ pinned: true }));
|
||||
expect(await pending).toBe(true);
|
||||
});
|
||||
|
||||
test('setNotePinned rolls back on failure', async () => {
|
||||
await store().createNote(PROJECT, { body: 'x' });
|
||||
handlers.updateNote = failWith('locked');
|
||||
|
||||
expect(await store().setNotePinned(PROJECT, 'n1', true)).toBe(false);
|
||||
expect(entry().notes[0].pinned).toBe(false);
|
||||
});
|
||||
|
||||
test('deleteNote removes optimistically and restores on failure', async () => {
|
||||
await store().createNote(PROJECT, { body: 'x' });
|
||||
handlers.deleteNote = failWith('busy');
|
||||
|
||||
expect(await store().deleteNote(PROJECT, 'n1')).toBe(false);
|
||||
expect(entry().notes.map((entryNote) => entryNote.id)).toEqual(['n1']);
|
||||
expect(entry().error).toBe('busy');
|
||||
});
|
||||
|
||||
test('deleteNote commits the server list on success', async () => {
|
||||
await store().createNote(PROJECT, { body: 'x' });
|
||||
|
||||
expect(await store().deleteNote(PROJECT, 'n1')).toBe(true);
|
||||
expect(entry().notes).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('plans', () => {
|
||||
test('createPlan commits the server context', async () => {
|
||||
const plan = await store().createPlan(PROJECT, { title: 'A', body: 'x' });
|
||||
|
||||
expect(plan?.id).toBe('p1');
|
||||
expect(entry().plans.map((item) => item.id)).toEqual(['p1']);
|
||||
});
|
||||
|
||||
test('createPlan reports failure without inserting a placeholder row', async () => {
|
||||
handlers.create = failWith('no space');
|
||||
|
||||
expect(await store().createPlan(PROJECT, { title: 'A', body: 'x' })).toBeNull();
|
||||
expect(entry().plans).toEqual([]);
|
||||
expect(entry().error).toBe('no space');
|
||||
});
|
||||
|
||||
test('deletePlan removes optimistically', async () => {
|
||||
await store().createPlan(PROJECT, { title: 'A', body: 'x' });
|
||||
|
||||
const gate = deferred<ContextPayload>();
|
||||
handlers.remove = () => gate.promise;
|
||||
|
||||
const pending = store().deletePlan(PROJECT, 'p1');
|
||||
expect(entry().plans).toEqual([]);
|
||||
|
||||
gate.resolve(emptyPayload());
|
||||
expect(await pending).toBe(true);
|
||||
});
|
||||
|
||||
test('savePlan folds the refreshed title back into the list', async () => {
|
||||
await store().createPlan(PROJECT, { title: 'A', body: 'x' });
|
||||
handlers.update = async () => ({ plan: planLink({ title: 'Renamed' }), raw: '# Renamed' });
|
||||
|
||||
expect(await store().savePlan(PROJECT, 'p1', '# Renamed')).toBe(true);
|
||||
expect(entry().plans[0].title).toBe('Renamed');
|
||||
});
|
||||
|
||||
test('savePlan drops a plan the server reports as gone', async () => {
|
||||
await store().createPlan(PROJECT, { title: 'A', body: 'x' });
|
||||
handlers.update = async () => null;
|
||||
|
||||
expect(await store().savePlan(PROJECT, 'p1', '# X')).toBe(false);
|
||||
expect(entry().plans).toEqual([]);
|
||||
});
|
||||
|
||||
test('savePlan keeps the row and reports the error when the request fails', async () => {
|
||||
await store().createPlan(PROJECT, { title: 'A', body: 'x' });
|
||||
handlers.update = failWith('read only');
|
||||
|
||||
expect(await store().savePlan(PROJECT, 'p1', '# X')).toBe(false);
|
||||
expect(entry().plans.map((item) => item.id)).toEqual(['p1']);
|
||||
expect(entry().error).toBe('read only');
|
||||
});
|
||||
|
||||
test('setPlanPinned applies optimistically and rolls back on failure', async () => {
|
||||
await store().createPlan(PROJECT, { title: 'A', body: 'x' });
|
||||
handlers.pinPlan = failWith('locked');
|
||||
|
||||
expect(await store().setPlanPinned(PROJECT, 'p1', true)).toBe(false);
|
||||
expect(entry().plans[0].pinned).toBe(false);
|
||||
expect(entry().error).toBe('locked');
|
||||
});
|
||||
|
||||
test('setPlanPinned commits the server copy', async () => {
|
||||
await store().createPlan(PROJECT, { title: 'A', body: 'x' });
|
||||
|
||||
expect(await store().setPlanPinned(PROJECT, 'p1', true)).toBe(true);
|
||||
expect(entry().plans[0].pinned).toBe(true);
|
||||
});
|
||||
|
||||
test('deletePlan restores the row when the request fails', async () => {
|
||||
await store().createPlan(PROJECT, { title: 'A', body: 'x' });
|
||||
handlers.remove = failWith('locked');
|
||||
|
||||
expect(await store().deletePlan(PROJECT, 'p1')).toBe(false);
|
||||
expect(entry().plans.map((item) => item.id)).toEqual(['p1']);
|
||||
expect(entry().error).toBe('locked');
|
||||
});
|
||||
});
|
||||
|
||||
describe('reset', () => {
|
||||
test('drops every cached project', async () => {
|
||||
await store().load(PROJECT);
|
||||
expect(entry().loaded).toBe(true);
|
||||
|
||||
store().reset();
|
||||
expect(entry().loaded).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,450 @@
|
||||
/**
|
||||
* Project context store: notes, todos, and plan links, keyed by project.
|
||||
*
|
||||
* Replaces the `openchamber:project-notes-updated` / `openchamber:project-plan-saved`
|
||||
* window events that previously forced every mounted panel to re-read the whole
|
||||
* config. Writers now mutate the store and every reader re-renders from it.
|
||||
*
|
||||
* Storage is server-owned; this store is a cache with optimistic mutations.
|
||||
* See `packages/web/server/lib/project-context/DOCUMENTATION.md`.
|
||||
*/
|
||||
|
||||
import { create } from 'zustand';
|
||||
|
||||
import {
|
||||
createProjectNote,
|
||||
createProjectPlan,
|
||||
deleteProjectNote,
|
||||
deleteProjectPlan,
|
||||
fetchProjectContext,
|
||||
resolveProjectContextId,
|
||||
saveProjectTodos,
|
||||
setProjectPlanPinned,
|
||||
updateProjectNote,
|
||||
updateProjectPlan,
|
||||
type ProjectNote,
|
||||
type ProjectNoteSource,
|
||||
type ProjectPlanLink,
|
||||
type ProjectRef,
|
||||
type ProjectTodoItem,
|
||||
} from '@/lib/projectContextApi';
|
||||
|
||||
interface ProjectContextEntry {
|
||||
notes: ProjectNote[];
|
||||
todos: ProjectTodoItem[];
|
||||
plans: ProjectPlanLink[];
|
||||
/** True once an authoritative load has succeeded at least once. */
|
||||
loaded: boolean;
|
||||
loading: boolean;
|
||||
/** Last load or save failure. Never clears cached data on its own. */
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface MutationFlags {
|
||||
/** A note write is in flight; a slower load must not overwrite the list. */
|
||||
notes: boolean;
|
||||
/** A todo write is in flight; same rule. */
|
||||
todos: boolean;
|
||||
/** A plan write is in flight; same rule. */
|
||||
plans: boolean;
|
||||
}
|
||||
|
||||
interface ProjectContextState {
|
||||
entries: Record<string, ProjectContextEntry>;
|
||||
}
|
||||
|
||||
interface ProjectContextActions {
|
||||
getEntry: (project: ProjectRef | null | undefined) => ProjectContextEntry;
|
||||
load: (project: ProjectRef, options?: { force?: boolean }) => Promise<void>;
|
||||
saveTodos: (project: ProjectRef, todos: ProjectTodoItem[]) => Promise<boolean>;
|
||||
createNote: (
|
||||
project: ProjectRef,
|
||||
value: { body: string; source?: ProjectNoteSource; origin?: { sessionId: string; messageId?: string } },
|
||||
) => Promise<ProjectNote | null>;
|
||||
saveNoteBody: (project: ProjectRef, noteId: string, body: string) => Promise<boolean>;
|
||||
setNotePinned: (project: ProjectRef, noteId: string, pinned: boolean) => Promise<boolean>;
|
||||
deleteNote: (project: ProjectRef, noteId: string) => Promise<boolean>;
|
||||
createPlan: (project: ProjectRef, value: { title: string; body: string }) => Promise<ProjectPlanLink | null>;
|
||||
savePlan: (project: ProjectRef, planId: string, raw: string) => Promise<boolean>;
|
||||
setPlanPinned: (project: ProjectRef, planId: string, pinned: boolean) => Promise<boolean>;
|
||||
deletePlan: (project: ProjectRef, planId: string) => Promise<boolean>;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
type ProjectContextStore = ProjectContextState & ProjectContextActions;
|
||||
|
||||
export const EMPTY_PROJECT_CONTEXT_ENTRY: ProjectContextEntry = {
|
||||
notes: [],
|
||||
todos: [],
|
||||
plans: [],
|
||||
loaded: false,
|
||||
loading: false,
|
||||
error: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* Per-project write chains and in-flight mutation flags.
|
||||
*
|
||||
* Kept outside the store because they are coordination state, not rendered
|
||||
* state: putting them in the store would re-render every consumer whenever a
|
||||
* write starts or finishes.
|
||||
*/
|
||||
const writeChains = new Map<string, Promise<unknown>>();
|
||||
const mutationFlags = new Map<string, MutationFlags>();
|
||||
|
||||
const flagsFor = (projectId: string): MutationFlags => {
|
||||
const existing = mutationFlags.get(projectId);
|
||||
if (existing) return existing;
|
||||
const created: MutationFlags = { notes: false, todos: false, plans: false };
|
||||
mutationFlags.set(projectId, created);
|
||||
return created;
|
||||
};
|
||||
|
||||
/**
|
||||
* Serialize writes per project so two saves cannot interleave into a
|
||||
* last-writer-wins race against the server's own read-modify-write.
|
||||
*/
|
||||
const enqueueWrite = <T>(projectId: string, operation: () => Promise<T>): Promise<T> => {
|
||||
const previous = writeChains.get(projectId) ?? Promise.resolve();
|
||||
const next = previous.then(operation, operation);
|
||||
writeChains.set(projectId, next.catch(() => undefined));
|
||||
return next;
|
||||
};
|
||||
|
||||
const errorMessage = (error: unknown, fallback: string): string => (
|
||||
error instanceof Error && error.message ? error.message : fallback
|
||||
);
|
||||
|
||||
export const useProjectContextStore = create<ProjectContextStore>((set, get) => {
|
||||
const patchEntry = (projectId: string, patch: Partial<ProjectContextEntry>) => {
|
||||
set((state) => ({
|
||||
entries: {
|
||||
...state.entries,
|
||||
[projectId]: { ...(state.entries[projectId] ?? EMPTY_PROJECT_CONTEXT_ENTRY), ...patch },
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const currentEntry = (projectId: string): ProjectContextEntry => (
|
||||
get().entries[projectId] ?? EMPTY_PROJECT_CONTEXT_ENTRY
|
||||
);
|
||||
|
||||
return {
|
||||
entries: {},
|
||||
|
||||
getEntry: (project) => {
|
||||
const projectId = resolveProjectContextId(project);
|
||||
if (!projectId) return EMPTY_PROJECT_CONTEXT_ENTRY;
|
||||
return get().entries[projectId] ?? EMPTY_PROJECT_CONTEXT_ENTRY;
|
||||
},
|
||||
|
||||
/**
|
||||
* Load authoritative context.
|
||||
*
|
||||
* A failure sets `error` and leaves any previously loaded data in place:
|
||||
* an unreachable server must not read as "this project has no notes",
|
||||
* which is exactly how a user loses trust in a notes panel.
|
||||
*/
|
||||
load: async (project, options = {}) => {
|
||||
const projectId = resolveProjectContextId(project);
|
||||
if (!projectId) return;
|
||||
|
||||
const entry = currentEntry(projectId);
|
||||
if (entry.loading) return;
|
||||
if (entry.loaded && !options.force) return;
|
||||
|
||||
patchEntry(projectId, { loading: true });
|
||||
|
||||
try {
|
||||
const data = await fetchProjectContext(project);
|
||||
const flags = flagsFor(projectId);
|
||||
const committed = currentEntry(projectId);
|
||||
|
||||
// A mutation that started after this load began is newer than the
|
||||
// snapshot; keep the local value for that field group only.
|
||||
patchEntry(projectId, {
|
||||
notes: flags.notes ? committed.notes : data.notes,
|
||||
todos: flags.todos ? committed.todos : data.todos,
|
||||
plans: flags.plans ? committed.plans : data.plans,
|
||||
loaded: true,
|
||||
loading: false,
|
||||
error: null,
|
||||
});
|
||||
} catch (error) {
|
||||
patchEntry(projectId, {
|
||||
loading: false,
|
||||
error: errorMessage(error, 'Failed to load project context'),
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Optimistically apply todos, then persist.
|
||||
*
|
||||
* On failure the previous list is restored, so the panel never shows a
|
||||
* state that is not on disk without also showing the error.
|
||||
*/
|
||||
saveTodos: async (project, todos) => {
|
||||
const projectId = resolveProjectContextId(project);
|
||||
if (!projectId) return false;
|
||||
|
||||
const previous = currentEntry(projectId).todos;
|
||||
patchEntry(projectId, { todos, error: null });
|
||||
|
||||
const flags = flagsFor(projectId);
|
||||
flags.todos = true;
|
||||
|
||||
try {
|
||||
const committed = await enqueueWrite(projectId, () => saveProjectTodos(project, todos));
|
||||
patchEntry(projectId, { todos: committed.todos, loaded: true });
|
||||
return true;
|
||||
} catch (error) {
|
||||
patchEntry(projectId, {
|
||||
todos: previous,
|
||||
error: errorMessage(error, 'Failed to save project todos'),
|
||||
});
|
||||
return false;
|
||||
} finally {
|
||||
flags.todos = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a note. Not optimistic: the id and timestamps come from the
|
||||
* server, and a placeholder row that cannot be edited or pinned is worse
|
||||
* than a brief wait.
|
||||
*
|
||||
* The caller may be a chat action running while the panel is not mounted,
|
||||
* so the committed list is adopted wholesale rather than spliced into a
|
||||
* possibly-empty local one.
|
||||
*/
|
||||
createNote: async (project, value) => {
|
||||
const projectId = resolveProjectContextId(project);
|
||||
const body = value.body.trim();
|
||||
if (!projectId || !body) return null;
|
||||
|
||||
const flags = flagsFor(projectId);
|
||||
flags.notes = true;
|
||||
|
||||
try {
|
||||
const { note, context } = await enqueueWrite(
|
||||
projectId,
|
||||
() => createProjectNote(project, { ...value, body }),
|
||||
);
|
||||
patchEntry(projectId, { notes: context.notes, loaded: true, error: null });
|
||||
return note;
|
||||
} catch (error) {
|
||||
patchEntry(projectId, { error: errorMessage(error, 'Failed to create note') });
|
||||
return null;
|
||||
} finally {
|
||||
flags.notes = false;
|
||||
}
|
||||
},
|
||||
|
||||
saveNoteBody: async (project, noteId, body) => {
|
||||
const projectId = resolveProjectContextId(project);
|
||||
const trimmed = body.trim();
|
||||
if (!projectId || !trimmed) return false;
|
||||
|
||||
const previous = currentEntry(projectId).notes;
|
||||
patchEntry(projectId, {
|
||||
notes: previous.map((note) => (note.id === noteId ? { ...note, body: trimmed } : note)),
|
||||
error: null,
|
||||
});
|
||||
|
||||
const flags = flagsFor(projectId);
|
||||
flags.notes = true;
|
||||
|
||||
try {
|
||||
const saved = await enqueueWrite(projectId, () => updateProjectNote(project, noteId, { body: trimmed }));
|
||||
if (!saved) {
|
||||
patchEntry(projectId, { notes: currentEntry(projectId).notes.filter((note) => note.id !== noteId) });
|
||||
return false;
|
||||
}
|
||||
patchEntry(projectId, {
|
||||
notes: currentEntry(projectId).notes.map((note) => (note.id === noteId ? saved : note)),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
patchEntry(projectId, { notes: previous, error: errorMessage(error, 'Failed to save note') });
|
||||
return false;
|
||||
} finally {
|
||||
flags.notes = false;
|
||||
}
|
||||
},
|
||||
|
||||
/** Sends `pinned` alone, so it cannot roll back a concurrent body edit. */
|
||||
setNotePinned: async (project, noteId, pinned) => {
|
||||
const projectId = resolveProjectContextId(project);
|
||||
if (!projectId) return false;
|
||||
|
||||
const previous = currentEntry(projectId).notes;
|
||||
patchEntry(projectId, {
|
||||
notes: previous.map((note) => (note.id === noteId ? { ...note, pinned } : note)),
|
||||
error: null,
|
||||
});
|
||||
|
||||
const flags = flagsFor(projectId);
|
||||
flags.notes = true;
|
||||
|
||||
try {
|
||||
const saved = await enqueueWrite(projectId, () => updateProjectNote(project, noteId, { pinned }));
|
||||
if (!saved) {
|
||||
patchEntry(projectId, { notes: currentEntry(projectId).notes.filter((note) => note.id !== noteId) });
|
||||
return false;
|
||||
}
|
||||
patchEntry(projectId, {
|
||||
notes: currentEntry(projectId).notes.map((note) => (note.id === noteId ? saved : note)),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
patchEntry(projectId, { notes: previous, error: errorMessage(error, 'Failed to save note') });
|
||||
return false;
|
||||
} finally {
|
||||
flags.notes = false;
|
||||
}
|
||||
},
|
||||
|
||||
deleteNote: async (project, noteId) => {
|
||||
const projectId = resolveProjectContextId(project);
|
||||
if (!projectId) return false;
|
||||
|
||||
const previous = currentEntry(projectId).notes;
|
||||
patchEntry(projectId, { notes: previous.filter((note) => note.id !== noteId), error: null });
|
||||
|
||||
const flags = flagsFor(projectId);
|
||||
flags.notes = true;
|
||||
|
||||
try {
|
||||
const context = await enqueueWrite(projectId, () => deleteProjectNote(project, noteId));
|
||||
patchEntry(projectId, { notes: context.notes });
|
||||
return true;
|
||||
} catch (error) {
|
||||
patchEntry(projectId, { notes: previous, error: errorMessage(error, 'Failed to delete note') });
|
||||
return false;
|
||||
} finally {
|
||||
flags.notes = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a plan. Not optimistic: the id and file name are assigned by the
|
||||
* server, and a placeholder row that cannot be opened is worse than a
|
||||
* short wait.
|
||||
*/
|
||||
createPlan: async (project, value) => {
|
||||
const projectId = resolveProjectContextId(project);
|
||||
if (!projectId) return null;
|
||||
|
||||
const flags = flagsFor(projectId);
|
||||
flags.plans = true;
|
||||
|
||||
try {
|
||||
const { plan, context } = await enqueueWrite(projectId, () => createProjectPlan(project, value));
|
||||
patchEntry(projectId, { plans: context.plans, loaded: true, error: null });
|
||||
return plan;
|
||||
} catch (error) {
|
||||
patchEntry(projectId, { error: errorMessage(error, 'Failed to create plan') });
|
||||
return null;
|
||||
} finally {
|
||||
flags.plans = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Persist an edited plan and fold the refreshed title back into the list,
|
||||
* so renaming a plan's heading in the editor is reflected in the panel
|
||||
* without a reload. Resolves false when the plan is gone.
|
||||
*/
|
||||
savePlan: async (project, planId, raw) => {
|
||||
const projectId = resolveProjectContextId(project);
|
||||
if (!projectId) return false;
|
||||
|
||||
const flags = flagsFor(projectId);
|
||||
flags.plans = true;
|
||||
|
||||
try {
|
||||
const result = await enqueueWrite(projectId, () => updateProjectPlan(project, planId, raw));
|
||||
if (!result) {
|
||||
patchEntry(projectId, {
|
||||
plans: currentEntry(projectId).plans.filter((plan) => plan.id !== planId),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
patchEntry(projectId, {
|
||||
plans: currentEntry(projectId).plans.map((plan) => (plan.id === planId ? result.plan : plan)),
|
||||
error: null,
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
patchEntry(projectId, { error: errorMessage(error, 'Failed to save plan') });
|
||||
return false;
|
||||
} finally {
|
||||
flags.plans = false;
|
||||
}
|
||||
},
|
||||
|
||||
setPlanPinned: async (project, planId, pinned) => {
|
||||
const projectId = resolveProjectContextId(project);
|
||||
if (!projectId) return false;
|
||||
|
||||
const previous = currentEntry(projectId).plans;
|
||||
patchEntry(projectId, {
|
||||
plans: previous.map((plan) => (plan.id === planId ? { ...plan, pinned } : plan)),
|
||||
error: null,
|
||||
});
|
||||
|
||||
const flags = flagsFor(projectId);
|
||||
flags.plans = true;
|
||||
|
||||
try {
|
||||
const saved = await enqueueWrite(projectId, () => setProjectPlanPinned(project, planId, pinned));
|
||||
if (!saved) {
|
||||
patchEntry(projectId, { plans: currentEntry(projectId).plans.filter((plan) => plan.id !== planId) });
|
||||
return false;
|
||||
}
|
||||
patchEntry(projectId, {
|
||||
plans: currentEntry(projectId).plans.map((plan) => (plan.id === planId ? saved : plan)),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
patchEntry(projectId, { plans: previous, error: errorMessage(error, 'Failed to update plan') });
|
||||
return false;
|
||||
} finally {
|
||||
flags.plans = false;
|
||||
}
|
||||
},
|
||||
|
||||
deletePlan: async (project, planId) => {
|
||||
const projectId = resolveProjectContextId(project);
|
||||
if (!projectId) return false;
|
||||
|
||||
const previous = currentEntry(projectId);
|
||||
patchEntry(projectId, { plans: previous.plans.filter((plan) => plan.id !== planId), error: null });
|
||||
|
||||
const flags = flagsFor(projectId);
|
||||
flags.plans = true;
|
||||
|
||||
try {
|
||||
const context = await enqueueWrite(projectId, () => deleteProjectPlan(project, planId));
|
||||
patchEntry(projectId, { plans: context.plans });
|
||||
return true;
|
||||
} catch (error) {
|
||||
patchEntry(projectId, {
|
||||
plans: previous.plans,
|
||||
error: errorMessage(error, 'Failed to delete plan'),
|
||||
});
|
||||
return false;
|
||||
} finally {
|
||||
flags.plans = false;
|
||||
}
|
||||
},
|
||||
|
||||
/** Drop every cached project. Used when the active runtime changes. */
|
||||
reset: () => {
|
||||
writeChains.clear();
|
||||
mutationFlags.clear();
|
||||
set({ entries: {} });
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -35,6 +35,10 @@ type ContextPanelTab = {
|
||||
id: string;
|
||||
mode: ContextPanelMode;
|
||||
targetPath: string | null;
|
||||
/** Saved project plan this tab shows, for `plan` tabs opened from the notes
|
||||
panel. Project plans are addressed by id because their markdown is
|
||||
server-owned and has no client-visible path. */
|
||||
projectPlanId: string | null;
|
||||
dedupeKey: string;
|
||||
label: string | null;
|
||||
sessionTitleFallback: string | null;
|
||||
@@ -47,6 +51,7 @@ type ContextPanelTab = {
|
||||
type ContextPanelTabDescriptor = {
|
||||
mode: ContextPanelMode;
|
||||
targetPath?: string | null;
|
||||
projectPlanId?: string | null;
|
||||
dedupeKey?: string | null;
|
||||
label?: string | null;
|
||||
sessionTitleFallback?: string | null;
|
||||
@@ -241,6 +246,9 @@ const createContextPanelTab = (descriptor: ContextPanelTabDescriptor): ContextPa
|
||||
id: buildContextPanelTabID(descriptor.mode, dedupeKey),
|
||||
mode: descriptor.mode,
|
||||
targetPath: normalizedTargetPath,
|
||||
projectPlanId: typeof descriptor.projectPlanId === 'string' && descriptor.projectPlanId.trim()
|
||||
? descriptor.projectPlanId.trim()
|
||||
: null,
|
||||
dedupeKey,
|
||||
label: normalizeContextTabLabel(descriptor.label),
|
||||
sessionTitleFallback: normalizeContextTabLabel(descriptor.sessionTitleFallback),
|
||||
@@ -300,6 +308,7 @@ const sanitizeContextPanelTabs = (tabs: unknown): ContextPanelTab[] => {
|
||||
const candidate = entry as {
|
||||
mode?: unknown;
|
||||
targetPath?: unknown;
|
||||
projectPlanId?: unknown;
|
||||
dedupeKey?: unknown;
|
||||
label?: unknown;
|
||||
sessionTitleFallback?: unknown;
|
||||
@@ -338,6 +347,9 @@ const sanitizeContextPanelTabs = (tabs: unknown): ContextPanelTab[] => {
|
||||
id,
|
||||
mode: candidate.mode,
|
||||
targetPath,
|
||||
projectPlanId: typeof candidate.projectPlanId === 'string' && candidate.projectPlanId.trim()
|
||||
? candidate.projectPlanId.trim()
|
||||
: null,
|
||||
dedupeKey,
|
||||
label: normalizeContextTabLabel(typeof candidate.label === 'string' ? candidate.label : null),
|
||||
sessionTitleFallback: normalizeContextTabLabel(typeof candidate.sessionTitleFallback === 'string' ? candidate.sessionTitleFallback : null),
|
||||
@@ -607,7 +619,6 @@ interface UIStore {
|
||||
contextEditorTreeVisible: boolean;
|
||||
contextEditorTreeWidth: number;
|
||||
notesPanelHeight: number;
|
||||
todoPanelHeight: number;
|
||||
/** Expanded collapsible sections of the in-chat work-status panel, by id. */
|
||||
workStatusExpandedSections: Record<string, boolean>;
|
||||
/** Scroll offset of that panel, so it survives being unmounted. */
|
||||
@@ -749,6 +760,21 @@ interface UIStore {
|
||||
showOpenCodeUpdateNotifications: boolean;
|
||||
agentControlToolEnabled: boolean;
|
||||
agentWebToolEnabled: boolean;
|
||||
agentMemoryToolEnabled: boolean;
|
||||
/**
|
||||
* Whether this build has agent memory at all. Server-owned and not
|
||||
* persisted: an unreleased feature must not come back from a stale cache.
|
||||
*/
|
||||
agentMemoryFeatureAvailable: boolean;
|
||||
/**
|
||||
* When the user last looked at each memory scope, keyed by scope. Drives the
|
||||
* new/changed badges; there is no stored review state.
|
||||
*/
|
||||
agentMemoryViewedAt: Record<string, number>;
|
||||
/** Width of the project context panel's section sidebar, in pixels. */
|
||||
projectContextSidebarWidth: number;
|
||||
/** Active tab of the project context panel (notes/todos/plans). */
|
||||
projectContextTab: string;
|
||||
inputSpellcheckEnabled: boolean;
|
||||
wideChatLayoutEnabled: boolean;
|
||||
codeBlockLineWrap: boolean;
|
||||
@@ -806,7 +832,6 @@ interface UIStore {
|
||||
setWorkStatusOverlayOpen: (open: boolean) => void;
|
||||
setWorkStatusSectionVisible: (sectionId: string, visible: boolean) => void;
|
||||
setWorkStatusHiddenSections: (sectionIds: string[]) => void;
|
||||
setTodoPanelHeight: (height: number) => void;
|
||||
setSessionSwitcherOpen: (open: boolean) => void;
|
||||
setSessionDropdownOpen: (open: boolean) => void;
|
||||
setActiveMainTab: (tab: MainTab) => void;
|
||||
@@ -923,6 +948,11 @@ interface UIStore {
|
||||
setShowOpenCodeUpdateNotifications: (value: boolean) => void;
|
||||
setAgentControlToolEnabled: (value: boolean) => void;
|
||||
setAgentWebToolEnabled: (value: boolean) => void;
|
||||
setAgentMemoryToolEnabled: (value: boolean) => void;
|
||||
setAgentMemoryFeatureAvailable: (value: boolean) => void;
|
||||
markAgentMemoryViewed: (key: string, viewedAt: number) => void;
|
||||
setProjectContextSidebarWidth: (width: number) => void;
|
||||
setProjectContextTab: (value: string) => void;
|
||||
setInputSpellcheckEnabled: (value: boolean) => void;
|
||||
setWideChatLayoutEnabled: (value: boolean) => void;
|
||||
setCodeBlockLineWrap: (value: boolean) => void;
|
||||
@@ -979,7 +1009,6 @@ export const useUIStore = create<UIStore>()(
|
||||
workStatusPanelFits: false,
|
||||
workStatusOverlayOpen: false,
|
||||
workStatusHiddenSections: [],
|
||||
todoPanelHeight: 259,
|
||||
isSessionSwitcherOpen: false,
|
||||
isSessionDropdownOpen: false,
|
||||
activeMainTab: 'chat',
|
||||
@@ -1082,6 +1111,11 @@ export const useUIStore = create<UIStore>()(
|
||||
showOpenCodeUpdateNotifications: !isWindowsArm64(),
|
||||
agentControlToolEnabled: true,
|
||||
agentWebToolEnabled: true,
|
||||
agentMemoryToolEnabled: false,
|
||||
agentMemoryFeatureAvailable: false,
|
||||
agentMemoryViewedAt: {},
|
||||
projectContextSidebarWidth: 168,
|
||||
projectContextTab: 'notes',
|
||||
inputSpellcheckEnabled: false,
|
||||
wideChatLayoutEnabled: false,
|
||||
codeBlockLineWrap: true,
|
||||
@@ -1576,9 +1610,6 @@ export const useUIStore = create<UIStore>()(
|
||||
set({ workStatusHiddenSections: [...new Set(sectionIds)] });
|
||||
},
|
||||
|
||||
setTodoPanelHeight: (height) => {
|
||||
set({ todoPanelHeight: height });
|
||||
},
|
||||
|
||||
setSessionSwitcherOpen: (open) => {
|
||||
if (get().isSessionSwitcherOpen === open) {
|
||||
@@ -2306,6 +2337,27 @@ export const useUIStore = create<UIStore>()(
|
||||
setAgentWebToolEnabled: (value) => {
|
||||
set({ agentWebToolEnabled: value });
|
||||
},
|
||||
setAgentMemoryToolEnabled: (value) => {
|
||||
set({ agentMemoryToolEnabled: value });
|
||||
},
|
||||
setAgentMemoryFeatureAvailable: (value) => {
|
||||
set({ agentMemoryFeatureAvailable: value });
|
||||
},
|
||||
setProjectContextSidebarWidth: (width) => {
|
||||
set({ projectContextSidebarWidth: width });
|
||||
},
|
||||
markAgentMemoryViewed: (key, viewedAt) => {
|
||||
set((state) => ({
|
||||
// Never moves backwards: a stale unmount landing after a newer look
|
||||
// would otherwise resurrect badges the user has already cleared.
|
||||
agentMemoryViewedAt: viewedAt > (state.agentMemoryViewedAt[key] ?? 0)
|
||||
? { ...state.agentMemoryViewedAt, [key]: viewedAt }
|
||||
: state.agentMemoryViewedAt,
|
||||
}));
|
||||
},
|
||||
setProjectContextTab: (value) => {
|
||||
set({ projectContextTab: value });
|
||||
},
|
||||
setInputSpellcheckEnabled: (value) => {
|
||||
set({ inputSpellcheckEnabled: value });
|
||||
},
|
||||
@@ -2524,9 +2576,6 @@ export const useUIStore = create<UIStore>()(
|
||||
if (typeof state.notesPanelHeight !== 'number' || !Number.isFinite(state.notesPanelHeight)) {
|
||||
state.notesPanelHeight = 112;
|
||||
}
|
||||
if (typeof state.todoPanelHeight !== 'number' || !Number.isFinite(state.todoPanelHeight)) {
|
||||
state.todoPanelHeight = 259;
|
||||
}
|
||||
}
|
||||
|
||||
// v0 -> v1: reset legacy notification templates
|
||||
@@ -2624,7 +2673,6 @@ export const useUIStore = create<UIStore>()(
|
||||
workStatusScrollTop: state.workStatusScrollTop,
|
||||
workStatusPanelEnabled: state.workStatusPanelEnabled,
|
||||
workStatusHiddenSections: state.workStatusHiddenSections,
|
||||
todoPanelHeight: state.todoPanelHeight,
|
||||
isSessionSwitcherOpen: state.isSessionSwitcherOpen,
|
||||
activeMainTab: state.activeMainTab,
|
||||
sidebarSection: state.sidebarSection,
|
||||
@@ -2689,6 +2737,9 @@ export const useUIStore = create<UIStore>()(
|
||||
showOpenCodeUpdateNotifications: state.showOpenCodeUpdateNotifications,
|
||||
agentControlToolEnabled: state.agentControlToolEnabled,
|
||||
agentWebToolEnabled: state.agentWebToolEnabled,
|
||||
agentMemoryToolEnabled: state.agentMemoryToolEnabled,
|
||||
agentMemoryViewedAt: state.agentMemoryViewedAt,
|
||||
projectContextSidebarWidth: state.projectContextSidebarWidth,
|
||||
inputSpellcheckEnabled: state.inputSpellcheckEnabled,
|
||||
wideChatLayoutEnabled: state.wideChatLayoutEnabled,
|
||||
codeBlockLineWrap: state.codeBlockLineWrap,
|
||||
|
||||
Reference in New Issue
Block a user