@koinzhang/paseo-plugin-inbox 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/LICENSE +21 -0
- package/README.md +36 -0
- package/client/agent-status.tsx +129 -0
- package/client/header-button.ts +127 -0
- package/client/inbox-surface.tsx +1369 -0
- package/client/last-exchange.ts +49 -0
- package/client/panel-visibility.ts +45 -0
- package/client/selection.ts +50 -0
- package/client/use-inbox-filters.ts +83 -0
- package/client/web.ts +84 -0
- package/client/workspace-panel.tsx +18 -0
- package/index.client.tsx +74 -0
- package/index.server.ts +17 -0
- package/package.json +43 -0
- package/paseo-plugin.json +7 -0
- package/server/agents.ts +106 -0
- package/server/daemon.ts +85 -0
- package/server/directory.ts +63 -0
- package/server/handlers.ts +144 -0
- package/server/project-key.ts +42 -0
- package/server/store.ts +394 -0
- package/server/tags.ts +41 -0
- package/shared/agent-status.ts +39 -0
- package/shared/contracts.ts +192 -0
- package/shared/filter-settings.ts +74 -0
- package/shared/item-title.ts +8 -0
- package/shared/last-exchange.ts +124 -0
- package/shared/note.ts +4 -0
- package/shared/plugin-id.ts +4 -0
- package/shared/project-key.ts +55 -0
- package/shared/slash-command.ts +9 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { PaseoApi } from "@getpaseo/client";
|
|
2
|
+
import type { ProjectRef } from "../shared/project-key.ts";
|
|
3
|
+
|
|
4
|
+
const PAGE_LIMIT = 200;
|
|
5
|
+
const MAX_PAGES = 100;
|
|
6
|
+
|
|
7
|
+
export interface DirectoryWorkspace {
|
|
8
|
+
label: string;
|
|
9
|
+
project: ProjectRef;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Active projects (by Inbox project key) and workspaces on the host. */
|
|
13
|
+
export interface Directory {
|
|
14
|
+
projects: Map<string, string>;
|
|
15
|
+
workspaces: Map<string, DirectoryWorkspace>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type ResolveProject = (cwd: string) => Promise<ProjectRef>;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Paseo projects are keyed the way the Inbox keys them (git remote → repository
|
|
22
|
+
* root → directory) by resolving each project root, so older items keep matching.
|
|
23
|
+
* Archived projects and workspaces are absent: the daemon lists active ones only.
|
|
24
|
+
*/
|
|
25
|
+
export async function loadDirectory(paseo: PaseoApi, resolveProject: ResolveProject): Promise<Directory> {
|
|
26
|
+
const roots = new Map<string, { root: string; label: string }>();
|
|
27
|
+
const workspaceProjects = new Map<string, { label: string; projectId: string }>();
|
|
28
|
+
let cursor: string | undefined;
|
|
29
|
+
for (let pages = 0; pages < MAX_PAGES; pages++) {
|
|
30
|
+
const page = await paseo.workspaces.list({
|
|
31
|
+
page: { limit: PAGE_LIMIT, ...(cursor ? { cursor } : {}) },
|
|
32
|
+
});
|
|
33
|
+
for (const workspace of page.entries) {
|
|
34
|
+
workspaceProjects.set(workspace.id, { label: workspace.name, projectId: workspace.projectId });
|
|
35
|
+
roots.set(workspace.projectId, { root: workspace.projectRootPath, label: workspace.projectDisplayName });
|
|
36
|
+
}
|
|
37
|
+
if (!page.pageInfo.hasMore || !page.pageInfo.nextCursor) break;
|
|
38
|
+
cursor = page.pageInfo.nextCursor;
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
const { projects } = await paseo.projects.list();
|
|
42
|
+
for (const project of projects) {
|
|
43
|
+
roots.set(project.projectId, { root: project.projectRootPath, label: project.projectDisplayName });
|
|
44
|
+
}
|
|
45
|
+
} catch (error) {
|
|
46
|
+
console.error("[inbox] projects unavailable; only projects with active workspaces are known", error);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const byId = new Map<string, ProjectRef>();
|
|
50
|
+
await Promise.all(
|
|
51
|
+
[...roots].map(async ([projectId, { root, label }]) => {
|
|
52
|
+
const { key } = await resolveProject(root);
|
|
53
|
+
byId.set(projectId, { key, label });
|
|
54
|
+
}),
|
|
55
|
+
);
|
|
56
|
+
const projects = new Map([...byId.values()].map((project) => [project.key, project.label]));
|
|
57
|
+
const workspaces = new Map<string, DirectoryWorkspace>();
|
|
58
|
+
for (const [id, { label, projectId }] of workspaceProjects) {
|
|
59
|
+
const project = byId.get(projectId);
|
|
60
|
+
if (project) workspaces.set(id, { label, project });
|
|
61
|
+
}
|
|
62
|
+
return { projects, workspaces };
|
|
63
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import type { PaseoApi } from "@getpaseo/client";
|
|
2
|
+
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
|
3
|
+
import {
|
|
4
|
+
agentCandidates,
|
|
5
|
+
agentStates,
|
|
6
|
+
deleteItem,
|
|
7
|
+
listItems,
|
|
8
|
+
saveNote,
|
|
9
|
+
starAgent,
|
|
10
|
+
tagItem,
|
|
11
|
+
tagOptions,
|
|
12
|
+
unarchiveAgent,
|
|
13
|
+
updateItem,
|
|
14
|
+
} from "../shared/contracts.ts";
|
|
15
|
+
import { agentState, lookupAgent, unarchiveAgent as runUnarchive, workspaceAgents } from "./agents.ts";
|
|
16
|
+
import type { createDaemonConnection } from "./daemon.ts";
|
|
17
|
+
import { type Directory, loadDirectory } from "./directory.ts";
|
|
18
|
+
import type { createProjectResolver } from "./project-key.ts";
|
|
19
|
+
import type { InboxStore } from "./store.ts";
|
|
20
|
+
import { resolveTags } from "./tags.ts";
|
|
21
|
+
|
|
22
|
+
interface Deps {
|
|
23
|
+
store: InboxStore;
|
|
24
|
+
resolveProject: ReturnType<typeof createProjectResolver>;
|
|
25
|
+
daemon: ReturnType<typeof createDaemonConnection>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function registerHandlers(server: PluginServerContext, { store, resolveProject, daemon }: Deps): void {
|
|
29
|
+
const directory = (paseo: PaseoApi) => loadDirectory(paseo, resolveProject);
|
|
30
|
+
/** Null when the host directory is unreadable; then nothing is treated as archived. */
|
|
31
|
+
const tryDirectory = (paseo: PaseoApi): Promise<Directory | null> =>
|
|
32
|
+
directory(paseo).catch((error: unknown) => {
|
|
33
|
+
console.error("[inbox] workspaces unavailable; archived tags are not marked", error);
|
|
34
|
+
return null;
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
server.handle(listItems, async ({ inboxOf, ...filter }, { paseo }) => {
|
|
38
|
+
const known = await tryDirectory(paseo);
|
|
39
|
+
if (known) {
|
|
40
|
+
store.refreshLabels(
|
|
41
|
+
known.projects,
|
|
42
|
+
new Map([...known.workspaces].map(([id, workspace]) => [id, workspace.label])),
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
const items = store.list({
|
|
46
|
+
...filter,
|
|
47
|
+
...(inboxOf
|
|
48
|
+
? { inboxOf: { workspaceId: inboxOf, projectKey: known?.workspaces.get(inboxOf)?.project.key ?? null } }
|
|
49
|
+
: {}),
|
|
50
|
+
});
|
|
51
|
+
const projectArchived = (key: string) => Boolean(known && !known.projects.has(key));
|
|
52
|
+
const workspaceArchived = (id: string) => Boolean(known && !known.workspaces.has(id));
|
|
53
|
+
const archived = { projects: new Set<string>(), workspaces: new Set<string>() };
|
|
54
|
+
for (const item of items) {
|
|
55
|
+
if (item.projectKey && projectArchived(item.projectKey)) archived.projects.add(item.projectKey);
|
|
56
|
+
if (item.workspaceId && workspaceArchived(item.workspaceId)) archived.workspaces.add(item.workspaceId);
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
items,
|
|
60
|
+
projects: store.projects(filter.kind).map((entry) => ({ ...entry, archived: projectArchived(entry.key) })),
|
|
61
|
+
workspaces: store.workspaces(filter.kind).map((entry) => ({ ...entry, archived: workspaceArchived(entry.id) })),
|
|
62
|
+
archived: { projects: [...archived.projects], workspaces: [...archived.workspaces] },
|
|
63
|
+
};
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
server.handle(saveNote, async ({ id, kind, title, body, workspaceId, projectOfWorkspace }, { paseo }) => {
|
|
67
|
+
if (id) return { item: store.updateNote(id, { kind, title, body }) };
|
|
68
|
+
const target = workspaceId ?? projectOfWorkspace;
|
|
69
|
+
if (!target) return { item: store.createNote({ kind, title, body }) };
|
|
70
|
+
const found = (await tryDirectory(paseo))?.workspaces.get(target);
|
|
71
|
+
if (!found && workspaceId) throw new Error("This workspace is archived or no longer on this host");
|
|
72
|
+
return {
|
|
73
|
+
item: store.createNote({
|
|
74
|
+
kind,
|
|
75
|
+
title,
|
|
76
|
+
body,
|
|
77
|
+
project: found?.project ?? null,
|
|
78
|
+
workspace: workspaceId && found ? { id: workspaceId, label: found.label } : null,
|
|
79
|
+
}),
|
|
80
|
+
};
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
server.handle(tagItem, async ({ id, projectKey, workspaceId }, { paseo }) => {
|
|
84
|
+
const item = store.get(id);
|
|
85
|
+
if (!item) throw new Error(`Inbox item ${id} not found`);
|
|
86
|
+
const tags = resolveTags(item, { projectKey, workspaceId }, await directory(paseo));
|
|
87
|
+
return { item: store.setTags(id, tags) };
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
server.handle(tagOptions, async (_input, { paseo }) => {
|
|
91
|
+
const known = await directory(paseo);
|
|
92
|
+
return {
|
|
93
|
+
projects: [...known.projects].map(([key, label]) => ({ key, label })),
|
|
94
|
+
workspaces: [...known.workspaces].map(([id, { label, project }]) => ({
|
|
95
|
+
id,
|
|
96
|
+
label,
|
|
97
|
+
projectKey: project.key,
|
|
98
|
+
})),
|
|
99
|
+
};
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
server.handle(updateItem, ({ id, ...patch }) => ({ item: store.update(id, patch) }));
|
|
103
|
+
|
|
104
|
+
server.handle(deleteItem, ({ id }) => {
|
|
105
|
+
store.delete(id);
|
|
106
|
+
return {};
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
server.handle(starAgent, async ({ agentId }, { paseo }) => {
|
|
110
|
+
const existing = store.findByAgent(agentId);
|
|
111
|
+
if (existing) return { item: existing, created: false };
|
|
112
|
+
const found = await lookupAgent(paseo, agentId);
|
|
113
|
+
if (!found) throw new Error("Agent not found on this host");
|
|
114
|
+
const workspaceId = found.snapshot.workspaceId;
|
|
115
|
+
const workspace = workspaceId ? (await tryDirectory(paseo))?.workspaces.get(workspaceId) : undefined;
|
|
116
|
+
const project = workspace?.project ?? (await resolveProject(found.snapshot.cwd));
|
|
117
|
+
return store.starAgent(
|
|
118
|
+
agentId,
|
|
119
|
+
found.snapshot,
|
|
120
|
+
project,
|
|
121
|
+
workspaceId ? { id: workspaceId, label: workspace?.label ?? workspaceId } : null,
|
|
122
|
+
);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
server.handle(agentCandidates, async ({ workspaceId }, { paseo }) => ({
|
|
126
|
+
agents: (await workspaceAgents(paseo, workspaceId)).filter((agent) => !store.findByAgent(agent.id)),
|
|
127
|
+
}));
|
|
128
|
+
|
|
129
|
+
server.handle(agentStates, async ({ agentIds }, { paseo }) => {
|
|
130
|
+
const entries = await Promise.all(
|
|
131
|
+
agentIds.map(async (id) => [id, await agentState(paseo, id)] as const),
|
|
132
|
+
);
|
|
133
|
+
const titlesChanged = store.refreshAgentTitles(
|
|
134
|
+
new Map(entries.flatMap(([id, { title }]) => (title?.trim() ? [[id, title]] : []))),
|
|
135
|
+
);
|
|
136
|
+
return {
|
|
137
|
+
states: Object.fromEntries(entries.map(([id, { state }]) => [id, state])),
|
|
138
|
+
live: Object.fromEntries(entries.flatMap(([id, { live }]) => (live ? [[id, live]] : []))),
|
|
139
|
+
...(titlesChanged ? { titlesChanged } : {}),
|
|
140
|
+
};
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
server.handle(unarchiveAgent, async ({ agentId }) => runUnarchive(await daemon.get(), agentId));
|
|
144
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
import { normalizeRemoteUrl, pathProject, remoteProject, type ProjectRef } from "../shared/project-key.ts";
|
|
4
|
+
|
|
5
|
+
const exec = promisify(execFile);
|
|
6
|
+
|
|
7
|
+
async function git(cwd: string, args: string[]): Promise<string | null> {
|
|
8
|
+
try {
|
|
9
|
+
const { stdout } = await exec("git", ["-C", cwd, ...args], { timeout: 5_000 });
|
|
10
|
+
return stdout.trim() || null;
|
|
11
|
+
} catch {
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function remoteUrl(cwd: string): Promise<string | null> {
|
|
17
|
+
const origin = await git(cwd, ["remote", "get-url", "origin"]);
|
|
18
|
+
if (origin) return origin;
|
|
19
|
+
const first = (await git(cwd, ["remote"]))?.split("\n")[0]?.trim();
|
|
20
|
+
return first ? git(cwd, ["remote", "get-url", first]) : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Project for a directory: normalized git remote → repository root → the directory itself. */
|
|
24
|
+
export async function resolveProject(cwd: string): Promise<ProjectRef> {
|
|
25
|
+
const remote = await remoteUrl(cwd);
|
|
26
|
+
const normalized = remote ? normalizeRemoteUrl(remote) : null;
|
|
27
|
+
if (normalized) return remoteProject(normalized);
|
|
28
|
+
const root = await git(cwd, ["rev-parse", "--show-toplevel"]);
|
|
29
|
+
return pathProject(root ?? cwd);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function createProjectResolver() {
|
|
33
|
+
const cache = new Map<string, Promise<ProjectRef>>();
|
|
34
|
+
return (cwd: string): Promise<ProjectRef> => {
|
|
35
|
+
let pending = cache.get(cwd);
|
|
36
|
+
if (!pending) {
|
|
37
|
+
pending = resolveProject(cwd);
|
|
38
|
+
cache.set(cwd, pending);
|
|
39
|
+
}
|
|
40
|
+
return pending;
|
|
41
|
+
};
|
|
42
|
+
}
|
package/server/store.ts
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdirSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import type { AgentSnapshot, Item, ItemKind, ItemSort } from "../shared/contracts.ts";
|
|
6
|
+
import { itemTitle } from "../shared/item-title.ts";
|
|
7
|
+
import { PLUGIN_ID } from "../shared/plugin-id.ts";
|
|
8
|
+
import { isEmptyNote } from "../shared/note.ts";
|
|
9
|
+
import type { ProjectRef } from "../shared/project-key.ts";
|
|
10
|
+
|
|
11
|
+
type SqliteModule = typeof import("node:sqlite");
|
|
12
|
+
type Database = InstanceType<SqliteModule["DatabaseSync"]>;
|
|
13
|
+
|
|
14
|
+
const SCHEMA = `
|
|
15
|
+
CREATE TABLE IF NOT EXISTS items (
|
|
16
|
+
id TEXT PRIMARY KEY,
|
|
17
|
+
kind TEXT NOT NULL CHECK (kind IN ('agent', 'note', 'scratch')),
|
|
18
|
+
title TEXT,
|
|
19
|
+
body TEXT NOT NULL DEFAULT '',
|
|
20
|
+
project_key TEXT,
|
|
21
|
+
project_label TEXT,
|
|
22
|
+
agent_id TEXT,
|
|
23
|
+
agent_snapshot TEXT,
|
|
24
|
+
workspace_id TEXT,
|
|
25
|
+
workspace_label TEXT,
|
|
26
|
+
pinned INTEGER NOT NULL DEFAULT 0,
|
|
27
|
+
created_at TEXT NOT NULL,
|
|
28
|
+
updated_at TEXT NOT NULL
|
|
29
|
+
);
|
|
30
|
+
CREATE UNIQUE INDEX IF NOT EXISTS items_agent_id ON items(agent_id) WHERE agent_id IS NOT NULL;
|
|
31
|
+
CREATE INDEX IF NOT EXISTS items_project ON items(project_key);
|
|
32
|
+
CREATE INDEX IF NOT EXISTS items_updated ON items(updated_at DESC);
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
/** Runs after columns added since 001 exist. */
|
|
36
|
+
const WORKSPACE_INDEX = "CREATE INDEX IF NOT EXISTS items_workspace ON items(workspace_id);";
|
|
37
|
+
|
|
38
|
+
interface Row {
|
|
39
|
+
id: string;
|
|
40
|
+
kind: ItemKind;
|
|
41
|
+
title: string | null;
|
|
42
|
+
body: string;
|
|
43
|
+
project_key: string | null;
|
|
44
|
+
project_label: string | null;
|
|
45
|
+
agent_id: string | null;
|
|
46
|
+
agent_snapshot: string | null;
|
|
47
|
+
workspace_id: string | null;
|
|
48
|
+
workspace_label: string | null;
|
|
49
|
+
pinned: number;
|
|
50
|
+
created_at: string;
|
|
51
|
+
updated_at: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface WorkspaceRef {
|
|
55
|
+
id: string;
|
|
56
|
+
label: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface ListFilter {
|
|
60
|
+
kind?: ItemKind;
|
|
61
|
+
projectKey?: string;
|
|
62
|
+
query?: string;
|
|
63
|
+
/** Items tagged with exactly this workspace. */
|
|
64
|
+
workspaceId?: string;
|
|
65
|
+
/** A workspace's Inbox: its workspace tag, or no workspace tag and its project tag. */
|
|
66
|
+
inboxOf?: { workspaceId: string; projectKey: string | null };
|
|
67
|
+
sort?: ItemSort;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface NoteInput {
|
|
71
|
+
kind: "note" | "scratch";
|
|
72
|
+
title?: string | null;
|
|
73
|
+
body: string;
|
|
74
|
+
project?: ProjectRef | null;
|
|
75
|
+
workspace?: WorkspaceRef | null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface Tags {
|
|
79
|
+
project: ProjectRef | null;
|
|
80
|
+
workspace: WorkspaceRef | null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function defaultDataDir(): string {
|
|
84
|
+
return join(homedir(), ".paseo", "plugin-data", PLUGIN_ID);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function loadSqlite(): SqliteModule {
|
|
88
|
+
const module = process.getBuiltinModule("node:sqlite") as unknown as SqliteModule | undefined;
|
|
89
|
+
if (!module || typeof module.DatabaseSync !== "function") {
|
|
90
|
+
throw new Error("node:sqlite is not available in this runtime");
|
|
91
|
+
}
|
|
92
|
+
return module;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function toItem(row: Row): Item {
|
|
96
|
+
return {
|
|
97
|
+
id: row.id,
|
|
98
|
+
kind: row.kind,
|
|
99
|
+
title: row.title,
|
|
100
|
+
body: row.body,
|
|
101
|
+
projectKey: row.project_key,
|
|
102
|
+
projectLabel: row.project_label,
|
|
103
|
+
agentId: row.agent_id,
|
|
104
|
+
agentSnapshot: row.agent_snapshot ? (JSON.parse(row.agent_snapshot) as AgentSnapshot) : null,
|
|
105
|
+
workspaceId: row.workspace_id,
|
|
106
|
+
workspaceLabel: row.workspace_label,
|
|
107
|
+
pinned: row.pinned === 1,
|
|
108
|
+
createdAt: row.created_at,
|
|
109
|
+
updatedAt: row.updated_at,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function escapeLike(value: string): string {
|
|
114
|
+
return value.replace(/[\\%_]/g, (char) => `\\${char}`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const SORT_KEY: Record<Exclude<ItemSort, "name">, (item: Item) => string> = {
|
|
118
|
+
starred: (item) => item.createdAt,
|
|
119
|
+
created: (item) => item.agentSnapshot?.createdAt ?? item.createdAt,
|
|
120
|
+
updated: (item) => item.updatedAt,
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/** Pinned first, then newest first (or A→Z for `name`); stable, so ties keep SQL order. */
|
|
124
|
+
function sortItems(items: Item[], sort: ItemSort): Item[] {
|
|
125
|
+
if (sort === "updated") return items;
|
|
126
|
+
const titles = new Map(items.map((item) => [item.id, itemTitle(item)]));
|
|
127
|
+
return [...items].sort((a, b) => {
|
|
128
|
+
if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;
|
|
129
|
+
if (sort === "name") {
|
|
130
|
+
return titles.get(a.id)!.localeCompare(titles.get(b.id)!, undefined, { sensitivity: "base", numeric: true });
|
|
131
|
+
}
|
|
132
|
+
const key = SORT_KEY[sort];
|
|
133
|
+
return key(b).localeCompare(key(a));
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export class InboxStore {
|
|
138
|
+
private readonly db: Database;
|
|
139
|
+
private readonly now: () => string;
|
|
140
|
+
|
|
141
|
+
constructor(options: { dir?: string; now?: () => string } = {}) {
|
|
142
|
+
const dir = options.dir ?? defaultDataDir();
|
|
143
|
+
mkdirSync(dir, { recursive: true });
|
|
144
|
+
const sqlite = loadSqlite();
|
|
145
|
+
this.db = new sqlite.DatabaseSync(join(dir, "inbox.db"));
|
|
146
|
+
this.db.exec("PRAGMA journal_mode = WAL");
|
|
147
|
+
this.db.exec(SCHEMA);
|
|
148
|
+
this.migrate();
|
|
149
|
+
this.db.exec(WORKSPACE_INDEX);
|
|
150
|
+
this.now = options.now ?? (() => new Date().toISOString());
|
|
151
|
+
this.deleteEmptyNotes();
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
private migrate(): void {
|
|
155
|
+
const columns = this.db.prepare("PRAGMA table_info(items)").all() as Array<{ name: string }>;
|
|
156
|
+
if (!columns.some((column) => column.name === "workspace_id")) {
|
|
157
|
+
this.db.exec("ALTER TABLE items ADD COLUMN workspace_id TEXT");
|
|
158
|
+
}
|
|
159
|
+
if (!columns.some((column) => column.name === "workspace_label")) {
|
|
160
|
+
this.db.exec("ALTER TABLE items ADD COLUMN workspace_label TEXT");
|
|
161
|
+
}
|
|
162
|
+
// Agents starred into the old global Inbox are tagged with their own workspace.
|
|
163
|
+
this.db.exec(
|
|
164
|
+
`UPDATE items SET workspace_id = json_extract(agent_snapshot, '$.workspaceId')
|
|
165
|
+
WHERE kind = 'agent' AND workspace_id IS NULL AND agent_snapshot IS NOT NULL`,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Drops notes / scratch with no title or text, e.g. left behind by an interrupted editor. */
|
|
170
|
+
deleteEmptyNotes(): number {
|
|
171
|
+
const result = this.db
|
|
172
|
+
.prepare(
|
|
173
|
+
`DELETE FROM items WHERE kind IN ('note', 'scratch')
|
|
174
|
+
AND trim(coalesce(title, '')) = '' AND trim(body) = ''`,
|
|
175
|
+
)
|
|
176
|
+
.run();
|
|
177
|
+
return Number(result.changes);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
close(): void {
|
|
181
|
+
this.db.close();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
get(id: string): Item | null {
|
|
185
|
+
const row = this.db.prepare("SELECT * FROM items WHERE id = ?").get(id) as Row | undefined;
|
|
186
|
+
return row ? toItem(row) : null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
findByAgent(agentId: string): Item | null {
|
|
190
|
+
const row = this.db.prepare("SELECT * FROM items WHERE agent_id = ?").get(agentId) as
|
|
191
|
+
| Row
|
|
192
|
+
| undefined;
|
|
193
|
+
return row ? toItem(row) : null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
list(filter: ListFilter = {}): Item[] {
|
|
197
|
+
const where: string[] = [];
|
|
198
|
+
const params: string[] = [];
|
|
199
|
+
if (filter.kind) {
|
|
200
|
+
where.push("kind = ?");
|
|
201
|
+
params.push(filter.kind);
|
|
202
|
+
}
|
|
203
|
+
if (filter.projectKey) {
|
|
204
|
+
where.push("project_key = ?");
|
|
205
|
+
params.push(filter.projectKey);
|
|
206
|
+
}
|
|
207
|
+
if (filter.workspaceId) {
|
|
208
|
+
where.push("workspace_id = ?");
|
|
209
|
+
params.push(filter.workspaceId);
|
|
210
|
+
}
|
|
211
|
+
if (filter.inboxOf) {
|
|
212
|
+
const { workspaceId, projectKey } = filter.inboxOf;
|
|
213
|
+
if (projectKey) {
|
|
214
|
+
where.push("(workspace_id = ? OR (workspace_id IS NULL AND project_key = ?))");
|
|
215
|
+
params.push(workspaceId, projectKey);
|
|
216
|
+
} else {
|
|
217
|
+
where.push("workspace_id = ?");
|
|
218
|
+
params.push(workspaceId);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const query = filter.query?.trim();
|
|
222
|
+
if (query) {
|
|
223
|
+
const pattern = `%${escapeLike(query)}%`;
|
|
224
|
+
where.push(
|
|
225
|
+
"(title LIKE ? ESCAPE '\\' OR body LIKE ? ESCAPE '\\' OR json_extract(agent_snapshot, '$.title') LIKE ? ESCAPE '\\')",
|
|
226
|
+
);
|
|
227
|
+
params.push(pattern, pattern, pattern);
|
|
228
|
+
}
|
|
229
|
+
const sql = `SELECT * FROM items ${where.length ? `WHERE ${where.join(" AND ")}` : ""}
|
|
230
|
+
ORDER BY pinned DESC, updated_at DESC, id`;
|
|
231
|
+
const items = (this.db.prepare(sql).all(...params) as unknown as Row[]).map(toItem);
|
|
232
|
+
return sortItems(items, filter.sort ?? "updated");
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
projects(kind?: ItemKind): Array<{ key: string; label: string; count: number }> {
|
|
236
|
+
const rows = this.db
|
|
237
|
+
.prepare(
|
|
238
|
+
`SELECT project_key AS key, MAX(project_label) AS label, COUNT(*) AS count
|
|
239
|
+
FROM items WHERE project_key IS NOT NULL ${kind ? "AND kind = ?" : ""}
|
|
240
|
+
GROUP BY project_key ORDER BY MAX(updated_at) DESC`,
|
|
241
|
+
)
|
|
242
|
+
.all(...(kind ? [kind] : [])) as Array<{ key: string; label: string | null; count: number }>;
|
|
243
|
+
return rows.map((row) => ({ key: row.key, label: row.label ?? row.key, count: Number(row.count) }));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Item counts per workspace tag, most recently updated first. */
|
|
247
|
+
workspaces(kind?: ItemKind): Array<{ id: string; label: string; count: number }> {
|
|
248
|
+
const rows = this.db
|
|
249
|
+
.prepare(
|
|
250
|
+
`SELECT workspace_id AS id, MAX(workspace_label) AS label, COUNT(*) AS count
|
|
251
|
+
FROM items WHERE workspace_id IS NOT NULL ${kind ? "AND kind = ?" : ""}
|
|
252
|
+
GROUP BY workspace_id ORDER BY MAX(updated_at) DESC`,
|
|
253
|
+
)
|
|
254
|
+
.all(...(kind ? [kind] : [])) as Array<{ id: string; label: string | null; count: number }>;
|
|
255
|
+
return rows.map((row) => ({ id: row.id, label: row.label ?? row.id, count: Number(row.count) }));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Writes current names of active projects / workspaces into the snapshots. */
|
|
259
|
+
refreshLabels(projects: ReadonlyMap<string, string>, workspaces: ReadonlyMap<string, string>): void {
|
|
260
|
+
const project = this.db.prepare(
|
|
261
|
+
"UPDATE items SET project_label = ? WHERE project_key = ? AND project_label IS NOT ?",
|
|
262
|
+
);
|
|
263
|
+
for (const [key, label] of projects) project.run(label, key, label);
|
|
264
|
+
const workspace = this.db.prepare(
|
|
265
|
+
"UPDATE items SET workspace_label = ? WHERE workspace_id = ? AND workspace_label IS NOT ?",
|
|
266
|
+
);
|
|
267
|
+
for (const [id, label] of workspaces) workspace.run(label, id, label);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Writes current agent titles into starred agents; true when any title changed. */
|
|
271
|
+
refreshAgentTitles(titles: ReadonlyMap<string, string>): boolean {
|
|
272
|
+
const update = this.db.prepare(
|
|
273
|
+
`UPDATE items SET title = ?, agent_snapshot = json_set(agent_snapshot, '$.title', ?)
|
|
274
|
+
WHERE kind = 'agent' AND agent_id = ? AND agent_snapshot IS NOT NULL
|
|
275
|
+
AND json_extract(agent_snapshot, '$.title') IS NOT ?`,
|
|
276
|
+
);
|
|
277
|
+
let changed = false;
|
|
278
|
+
for (const [agentId, title] of titles) {
|
|
279
|
+
if (Number(update.run(title, title, agentId, title).changes) > 0) changed = true;
|
|
280
|
+
}
|
|
281
|
+
return changed;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
createNote(input: NoteInput): Item {
|
|
285
|
+
if (isEmptyNote(input.title, input.body)) throw new Error("Empty notes are not saved");
|
|
286
|
+
if (input.workspace && !input.project) throw new Error("A workspace tag needs its project");
|
|
287
|
+
const id = randomUUID();
|
|
288
|
+
const now = this.now();
|
|
289
|
+
this.db
|
|
290
|
+
.prepare(
|
|
291
|
+
`INSERT INTO items (id, kind, title, body, project_key, project_label, workspace_id, workspace_label, created_at, updated_at)
|
|
292
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
293
|
+
)
|
|
294
|
+
.run(
|
|
295
|
+
id,
|
|
296
|
+
input.kind,
|
|
297
|
+
input.title ?? null,
|
|
298
|
+
input.body,
|
|
299
|
+
input.project?.key ?? null,
|
|
300
|
+
input.project?.label ?? null,
|
|
301
|
+
input.workspace?.id ?? null,
|
|
302
|
+
input.workspace?.label ?? null,
|
|
303
|
+
now,
|
|
304
|
+
now,
|
|
305
|
+
);
|
|
306
|
+
return this.require(id);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
updateNote(id: string, patch: { kind: "note" | "scratch"; title?: string | null; body: string }): Item {
|
|
310
|
+
const existing = this.require(id);
|
|
311
|
+
if (existing.kind === "agent") throw new Error("Starred agents have no editable note body");
|
|
312
|
+
this.db
|
|
313
|
+
.prepare("UPDATE items SET kind = ?, title = ?, body = ?, updated_at = ? WHERE id = ?")
|
|
314
|
+
.run(patch.kind, patch.title === undefined ? existing.title : patch.title, patch.body, this.now(), id);
|
|
315
|
+
return this.require(id);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
setTags(id: string, tags: Tags): Item {
|
|
319
|
+
const existing = this.require(id);
|
|
320
|
+
if (existing.kind === "agent") throw new Error("A starred agent's tags follow the agent");
|
|
321
|
+
if (tags.workspace && !tags.project) throw new Error("A workspace tag needs its project");
|
|
322
|
+
this.db
|
|
323
|
+
.prepare(
|
|
324
|
+
`UPDATE items SET project_key = ?, project_label = ?, workspace_id = ?, workspace_label = ?, updated_at = ?
|
|
325
|
+
WHERE id = ?`,
|
|
326
|
+
)
|
|
327
|
+
.run(
|
|
328
|
+
tags.project?.key ?? null,
|
|
329
|
+
tags.project?.label ?? null,
|
|
330
|
+
tags.workspace?.id ?? null,
|
|
331
|
+
tags.workspace?.label ?? null,
|
|
332
|
+
this.now(),
|
|
333
|
+
id,
|
|
334
|
+
);
|
|
335
|
+
return this.require(id);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
update(id: string, patch: { pinned?: boolean; kind?: "note" }): Item {
|
|
339
|
+
const existing = this.require(id);
|
|
340
|
+
if (patch.kind && existing.kind !== "scratch") {
|
|
341
|
+
throw new Error("Only scratch items can be promoted to notes");
|
|
342
|
+
}
|
|
343
|
+
this.db
|
|
344
|
+
.prepare("UPDATE items SET pinned = ?, kind = ?, updated_at = ? WHERE id = ?")
|
|
345
|
+
.run(
|
|
346
|
+
patch.pinned === undefined ? (existing.pinned ? 1 : 0) : patch.pinned ? 1 : 0,
|
|
347
|
+
patch.kind ?? existing.kind,
|
|
348
|
+
this.now(),
|
|
349
|
+
id,
|
|
350
|
+
);
|
|
351
|
+
return this.require(id);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Stars an agent once; a repeat star returns the existing item unchanged. */
|
|
355
|
+
starAgent(
|
|
356
|
+
agentId: string,
|
|
357
|
+
snapshot: AgentSnapshot,
|
|
358
|
+
project: ProjectRef | null,
|
|
359
|
+
workspace: WorkspaceRef | null = null,
|
|
360
|
+
): { item: Item; created: boolean } {
|
|
361
|
+
const existing = this.findByAgent(agentId);
|
|
362
|
+
if (existing) return { item: existing, created: false };
|
|
363
|
+
const id = randomUUID();
|
|
364
|
+
const now = this.now();
|
|
365
|
+
this.db
|
|
366
|
+
.prepare(
|
|
367
|
+
`INSERT INTO items (id, kind, title, body, project_key, project_label, agent_id, agent_snapshot, workspace_id, workspace_label, created_at, updated_at)
|
|
368
|
+
VALUES (?, 'agent', ?, '', ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
369
|
+
)
|
|
370
|
+
.run(
|
|
371
|
+
id,
|
|
372
|
+
snapshot.title,
|
|
373
|
+
project?.key ?? null,
|
|
374
|
+
project?.label ?? null,
|
|
375
|
+
agentId,
|
|
376
|
+
JSON.stringify(snapshot),
|
|
377
|
+
workspace?.id ?? null,
|
|
378
|
+
workspace?.label ?? null,
|
|
379
|
+
now,
|
|
380
|
+
now,
|
|
381
|
+
);
|
|
382
|
+
return { item: this.require(id), created: true };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
delete(id: string): void {
|
|
386
|
+
this.db.prepare("DELETE FROM items WHERE id = ?").run(id);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
private require(id: string): Item {
|
|
390
|
+
const item = this.get(id);
|
|
391
|
+
if (!item) throw new Error(`Inbox item ${id} not found`);
|
|
392
|
+
return item;
|
|
393
|
+
}
|
|
394
|
+
}
|
package/server/tags.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Item } from "../shared/contracts.ts";
|
|
2
|
+
import type { Directory } from "./directory.ts";
|
|
3
|
+
import type { Tags } from "./store.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Validates a tag change. Only active projects / workspaces can be newly picked;
|
|
7
|
+
* the item's current tags may stay even once archived. A workspace must belong to
|
|
8
|
+
* the project, and with no project given the project follows the workspace.
|
|
9
|
+
*/
|
|
10
|
+
export function resolveTags(
|
|
11
|
+
item: Pick<Item, "projectKey" | "projectLabel" | "workspaceId" | "workspaceLabel">,
|
|
12
|
+
request: { projectKey: string | null; workspaceId: string | null },
|
|
13
|
+
directory: Directory,
|
|
14
|
+
): Tags {
|
|
15
|
+
let workspace: Tags["workspace"] = null;
|
|
16
|
+
let workspaceProjectKey: string | null = null;
|
|
17
|
+
if (request.workspaceId) {
|
|
18
|
+
const active = directory.workspaces.get(request.workspaceId);
|
|
19
|
+
if (active) {
|
|
20
|
+
workspace = { id: request.workspaceId, label: active.label };
|
|
21
|
+
workspaceProjectKey = active.project.key;
|
|
22
|
+
} else if (request.workspaceId === item.workspaceId) {
|
|
23
|
+
workspace = { id: item.workspaceId, label: item.workspaceLabel ?? item.workspaceId };
|
|
24
|
+
workspaceProjectKey = item.projectKey;
|
|
25
|
+
} else {
|
|
26
|
+
throw new Error("That workspace is archived or no longer on this host");
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const projectKey = request.projectKey ?? workspaceProjectKey;
|
|
31
|
+
if (workspace && projectKey !== workspaceProjectKey) {
|
|
32
|
+
throw new Error(`Workspace ${workspace.label} belongs to another project`);
|
|
33
|
+
}
|
|
34
|
+
if (!projectKey) return { project: null, workspace: null };
|
|
35
|
+
|
|
36
|
+
const label =
|
|
37
|
+
directory.projects.get(projectKey) ??
|
|
38
|
+
(projectKey === item.projectKey ? (item.projectLabel ?? projectKey) : null);
|
|
39
|
+
if (label === null) throw new Error("That project is archived or no longer on this host");
|
|
40
|
+
return { project: { key: projectKey, label }, workspace };
|
|
41
|
+
}
|