@hienlh/ppm 0.9.0-beta.8 → 0.9.1
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 +238 -0
- package/bun.lock +17 -0
- package/dist/web/assets/api-settings-BUvk6Saw.js +1 -0
- package/dist/web/assets/arrow-up-BYhx9ckd.js +1 -0
- package/dist/web/assets/browser-tab-CrkhFCaw.js +1 -0
- package/dist/web/assets/chat-tab-C6jpiwh7.js +8 -0
- package/dist/web/assets/chevron-right-5HgK6l7K.js +1 -0
- package/dist/web/assets/code-editor-CBIPzlP2.js +2 -0
- package/dist/web/assets/columns-2-cEVJHYd7.js +1 -0
- package/dist/web/assets/createLucideIcon-PuMiQgHl.js +1 -0
- package/dist/web/assets/{csv-preview-DLqYtXxt.js → csv-preview-ncSOnJSC.js} +2 -2
- package/dist/web/assets/database-viewer-BqOJR_zi.js +1 -0
- package/dist/web/assets/diff-viewer-CcLyp4eY.js +4 -0
- package/dist/web/assets/{dist-CALwEtco.js → dist-DIV6WgAG.js} +1 -1
- package/dist/web/assets/{dist-DGDPTxs1.js → dist-ovWkrgO-.js} +1 -1
- package/dist/web/assets/extension-webview-NiZ7Ybvv.js +3 -0
- package/dist/web/assets/git-graph-CoTvMrIo.js +1 -0
- package/dist/web/assets/index-C8byznLO.js +37 -0
- package/dist/web/assets/index-KwC2YrG4.css +2 -0
- package/dist/web/assets/jsx-runtime-kMwlnEGE.js +1 -0
- package/dist/web/assets/keybindings-store-DPYzBe_M.js +1 -0
- package/dist/web/assets/{markdown-renderer-DklUd_Gv.js → markdown-renderer-DPLdR9xc.js} +4 -4
- package/dist/web/assets/postgres-viewer-BeiK4lCa.js +1 -0
- package/dist/web/assets/settings-tab-D3AvU4lu.js +1 -0
- package/dist/web/assets/sqlite-viewer-nA2sD4Yv.js +1 -0
- package/dist/web/assets/tab-store-BOgTrqRr.js +1 -0
- package/dist/web/assets/table-DFevCOMd.js +1 -0
- package/dist/web/assets/tag-CXMT0QB6.js +1 -0
- package/dist/web/assets/{terminal-tab-CqRuiIFn.js → terminal-tab-BBi0pEji.js} +2 -2
- package/dist/web/assets/{use-monaco-theme-Dcz3aLAE.js → use-monaco-theme-B5pG2d1w.js} +1 -1
- package/dist/web/index.html +8 -8
- package/dist/web/monacoeditorwork/css.worker.bundle.js +122 -122
- package/dist/web/monacoeditorwork/editor.worker.bundle.js +78 -78
- package/dist/web/monacoeditorwork/html.worker.bundle.js +110 -110
- package/dist/web/monacoeditorwork/json.worker.bundle.js +108 -108
- package/dist/web/monacoeditorwork/ts.worker.bundle.js +81 -81
- package/dist/web/sw.js +1 -1
- package/docs/code-standards.md +128 -1
- package/docs/codebase-summary.md +79 -12
- package/docs/extension-development-guide.md +532 -0
- package/docs/project-changelog.md +51 -1
- package/docs/project-roadmap.md +9 -3
- package/docs/streaming-input-guide.md +267 -0
- package/docs/system-architecture.md +432 -3
- package/package.json +6 -3
- package/packages/ext-database/package.json +41 -0
- package/packages/ext-database/src/connection-tree.ts +142 -0
- package/packages/ext-database/src/extension.ts +346 -0
- package/packages/ext-database/src/query-panel.ts +120 -0
- package/packages/ext-database/src/table-viewer-panel.ts +410 -0
- package/packages/ext-database/tsconfig.json +8 -0
- package/packages/vscode-compat/package.json +16 -0
- package/packages/vscode-compat/src/commands.ts +39 -0
- package/packages/vscode-compat/src/context.ts +65 -0
- package/packages/vscode-compat/src/disposable.ts +21 -0
- package/packages/vscode-compat/src/env.ts +20 -0
- package/packages/vscode-compat/src/event-emitter.ts +28 -0
- package/packages/vscode-compat/src/index.ts +93 -0
- package/packages/vscode-compat/src/not-supported.ts +15 -0
- package/packages/vscode-compat/src/types.ts +167 -0
- package/packages/vscode-compat/src/uri.ts +65 -0
- package/packages/vscode-compat/src/window.ts +229 -0
- package/packages/vscode-compat/src/workspace.ts +76 -0
- package/packages/vscode-compat/tsconfig.json +10 -0
- package/snapshot-state.md +1526 -0
- package/src/cli/commands/autostart.ts +1 -1
- package/src/cli/commands/ext-cmd.ts +121 -0
- package/src/cli/commands/restart.ts +9 -1
- package/src/cli/commands/status.ts +19 -0
- package/src/index.ts +5 -3
- package/src/providers/claude-agent-sdk.ts +221 -17
- package/src/providers/cli-provider-base.ts +6 -0
- package/src/server/index.ts +55 -155
- package/src/server/routes/chat.ts +81 -11
- package/src/server/routes/extensions.ts +81 -0
- package/src/server/routes/project-scoped.ts +2 -0
- package/src/server/routes/settings.ts +27 -0
- package/src/server/routes/workspace.ts +35 -0
- package/src/server/ws/chat.ts +9 -3
- package/src/server/ws/extensions.ts +175 -0
- package/src/services/account-selector.service.ts +14 -5
- package/src/services/account.service.ts +20 -15
- package/src/services/claude-usage.service.ts +29 -24
- package/src/services/cloud-ws.service.ts +228 -0
- package/src/services/cloud.service.ts +11 -6
- package/src/services/contribution-registry.ts +110 -0
- package/src/services/db.service.ts +181 -4
- package/src/services/extension-host-worker.ts +160 -0
- package/src/services/extension-installer.ts +112 -0
- package/src/services/extension-manifest.ts +65 -0
- package/src/services/extension-rpc-handlers.ts +235 -0
- package/src/services/extension-rpc.ts +105 -0
- package/src/services/extension.service.ts +228 -0
- package/src/services/mcp-config.service.ts +15 -6
- package/src/services/supervisor.ts +271 -25
- package/src/types/api.ts +1 -0
- package/src/types/chat.ts +4 -0
- package/src/types/extension-messages.ts +64 -0
- package/src/types/extension.ts +131 -0
- package/src/web/app.tsx +69 -48
- package/src/web/components/chat/account-rotation-settings.tsx +163 -0
- package/src/web/components/chat/chat-history-bar.tsx +106 -10
- package/src/web/components/chat/chat-tab.tsx +15 -10
- package/src/web/components/chat/chat-welcome.tsx +148 -0
- package/src/web/components/chat/message-list.tsx +19 -6
- package/src/web/components/chat/session-picker.tsx +80 -32
- package/src/web/components/chat/usage-badge.tsx +68 -8
- package/src/web/components/editor/editor-breadcrumb.tsx +20 -29
- package/src/web/components/extensions/extension-inputbox.tsx +92 -0
- package/src/web/components/extensions/extension-quickpick.tsx +194 -0
- package/src/web/components/extensions/extension-tree-view.tsx +240 -0
- package/src/web/components/extensions/extension-webview.tsx +83 -0
- package/src/web/components/layout/command-palette.tsx +22 -2
- package/src/web/components/layout/editor-panel.tsx +163 -18
- package/src/web/components/layout/mobile-nav.tsx +2 -1
- package/src/web/components/layout/sidebar.tsx +21 -3
- package/src/web/components/layout/status-bar.tsx +64 -0
- package/src/web/components/layout/tab-bar.tsx +2 -0
- package/src/web/components/layout/tab-content.tsx +5 -0
- package/src/web/components/layout/upgrade-banner.tsx +15 -5
- package/src/web/components/settings/change-password-section.tsx +128 -0
- package/src/web/components/settings/extension-manager-section.tsx +214 -0
- package/src/web/components/settings/settings-tab.tsx +9 -2
- package/src/web/components/shared/connection-lost-overlay.tsx +89 -0
- package/src/web/hooks/use-chat.ts +28 -0
- package/src/web/hooks/use-extension-ws.ts +181 -0
- package/src/web/hooks/use-global-keybindings.ts +18 -2
- package/src/web/hooks/use-server-reload.ts +9 -0
- package/src/web/hooks/use-url-sync.ts +173 -21
- package/src/web/stores/connection-store.ts +39 -0
- package/src/web/stores/extension-store.ts +204 -0
- package/src/web/stores/panel-store.ts +63 -9
- package/src/web/stores/panel-utils.ts +145 -3
- package/src/web/stores/settings-store.ts +7 -2
- package/src/web/stores/tab-store.ts +2 -1
- package/test-session-ops.mjs +444 -0
- package/test-tokens.mjs +212 -0
- package/tsconfig.json +3 -1
- package/dist/web/assets/api-settings-D21InCnR.js +0 -1
- package/dist/web/assets/arrow-up--LjUXLEt.js +0 -1
- package/dist/web/assets/browser-tab-BEe89aSD.js +0 -1
- package/dist/web/assets/chat-tab-9lqvWozA.js +0 -7
- package/dist/web/assets/chevron-right-CHnjJt4E.js +0 -1
- package/dist/web/assets/code-editor-COAIZx-B.js +0 -2
- package/dist/web/assets/columns-2-DbesTfa7.js +0 -1
- package/dist/web/assets/database-viewer-aRR9n_Ui.js +0 -1
- package/dist/web/assets/diff-viewer-C4KMvpHr.js +0 -4
- package/dist/web/assets/dist-CVTST7Gc.js +0 -1
- package/dist/web/assets/git-graph-CfJjl4E3.js +0 -1
- package/dist/web/assets/index-Db8uky1a.css +0 -2
- package/dist/web/assets/index-DxZuwBDe.js +0 -37
- package/dist/web/assets/jsx-runtime-BRW_vwa9.js +0 -1
- package/dist/web/assets/keybindings-store-_uWVCZMv.js +0 -1
- package/dist/web/assets/postgres-viewer-DEAvAyaX.js +0 -1
- package/dist/web/assets/settings-tab-BQedc-No.js +0 -1
- package/dist/web/assets/sqlite-viewer-BPA5idzT.js +0 -1
- package/dist/web/assets/tab-store-DhK6EpBT.js +0 -1
- package/dist/web/assets/table-CQVQM2SB.js +0 -1
- package/dist/web/assets/tag-Q2dZiSPX.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomId } from "@/lib/utils";
|
|
2
|
-
import type { Tab } from "./tab-store";
|
|
2
|
+
import type { Tab, TabType } from "./tab-store";
|
|
3
3
|
|
|
4
4
|
// ---------------------------------------------------------------------------
|
|
5
5
|
// Panel types
|
|
@@ -69,6 +69,62 @@ export function findPanelPosition(grid: string[][], panelId: string): { row: num
|
|
|
69
69
|
return null;
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
// Deterministic tab IDs
|
|
74
|
+
// ---------------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
/** Derive deterministic tab ID from type + metadata */
|
|
77
|
+
export function deriveTabId(type: TabType, metadata?: Record<string, unknown>): string {
|
|
78
|
+
switch (type) {
|
|
79
|
+
case "editor":
|
|
80
|
+
return `editor:${metadata?.filePath ?? "untitled"}`;
|
|
81
|
+
case "chat": {
|
|
82
|
+
const provider = metadata?.providerId ?? "default";
|
|
83
|
+
return `chat:${provider}/${metadata?.sessionId ?? randomId()}`;
|
|
84
|
+
}
|
|
85
|
+
case "terminal":
|
|
86
|
+
return `terminal:${metadata?.terminalIndex ?? 1}`;
|
|
87
|
+
case "database":
|
|
88
|
+
return `database:${metadata?.connectionId ?? "default"}:${metadata?.tableName ?? ""}`;
|
|
89
|
+
case "sqlite":
|
|
90
|
+
return `sqlite:${metadata?.filePath ?? "default"}`;
|
|
91
|
+
case "postgres":
|
|
92
|
+
return `postgres:${metadata?.connectionId ?? "default"}:${metadata?.tableName ?? ""}`;
|
|
93
|
+
case "git-graph":
|
|
94
|
+
return "git-graph";
|
|
95
|
+
case "git-diff":
|
|
96
|
+
return `git-diff:${metadata?.filePath ?? "unknown"}`;
|
|
97
|
+
case "settings":
|
|
98
|
+
return "settings";
|
|
99
|
+
case "browser":
|
|
100
|
+
return `browser:${metadata?.url ?? "blank"}`;
|
|
101
|
+
default:
|
|
102
|
+
return `${type}:${randomId()}`;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Migrate old random tab IDs to deterministic IDs */
|
|
107
|
+
export function migrateTabIds(layout: PanelLayout): PanelLayout {
|
|
108
|
+
const migrated = { ...layout, panels: { ...layout.panels } };
|
|
109
|
+
for (const [panelId, panel] of Object.entries(migrated.panels)) {
|
|
110
|
+
const newTabs = panel.tabs.map((tab) => {
|
|
111
|
+
if (tab.id.startsWith("tab-")) {
|
|
112
|
+
const newId = deriveTabId(tab.type, tab.metadata);
|
|
113
|
+
return { ...tab, id: newId };
|
|
114
|
+
}
|
|
115
|
+
return tab;
|
|
116
|
+
});
|
|
117
|
+
const idMap = new Map<string, string>();
|
|
118
|
+
panel.tabs.forEach((old, i) => {
|
|
119
|
+
if (old.id !== newTabs[i]!.id) idMap.set(old.id, newTabs[i]!.id);
|
|
120
|
+
});
|
|
121
|
+
const newActive = idMap.get(panel.activeTabId ?? "") ?? panel.activeTabId;
|
|
122
|
+
const newHistory = panel.tabHistory.map((h) => idMap.get(h) ?? h);
|
|
123
|
+
migrated.panels[panelId] = { ...panel, tabs: newTabs, activeTabId: newActive, tabHistory: newHistory };
|
|
124
|
+
}
|
|
125
|
+
return migrated;
|
|
126
|
+
}
|
|
127
|
+
|
|
72
128
|
// ---------------------------------------------------------------------------
|
|
73
129
|
// Persistence
|
|
74
130
|
// ---------------------------------------------------------------------------
|
|
@@ -81,20 +137,106 @@ function storageKey(projectName: string): string {
|
|
|
81
137
|
|
|
82
138
|
export function savePanelLayout(projectName: string, layout: PanelLayout): void {
|
|
83
139
|
try {
|
|
84
|
-
|
|
140
|
+
const withTimestamp = { ...layout, updatedAt: new Date().toISOString() };
|
|
141
|
+
localStorage.setItem(storageKey(projectName), JSON.stringify(withTimestamp));
|
|
142
|
+
// Debounced server sync
|
|
143
|
+
syncWorkspaceToServer(projectName, layout);
|
|
85
144
|
} catch { /* ignore */ }
|
|
86
145
|
}
|
|
87
146
|
|
|
88
147
|
export function loadPanelLayout(projectName: string): PanelLayout | null {
|
|
89
148
|
try {
|
|
90
149
|
const raw = localStorage.getItem(storageKey(projectName));
|
|
91
|
-
if (raw)
|
|
150
|
+
if (raw) {
|
|
151
|
+
const layout = JSON.parse(raw) as PanelLayout;
|
|
152
|
+
return migrateTabIds(layout);
|
|
153
|
+
}
|
|
92
154
|
} catch { /* ignore */ }
|
|
93
155
|
|
|
94
156
|
// Migrate from old tab-store format
|
|
95
157
|
return migrateOldTabStore(projectName);
|
|
96
158
|
}
|
|
97
159
|
|
|
160
|
+
// ---------------------------------------------------------------------------
|
|
161
|
+
// Server sync
|
|
162
|
+
// ---------------------------------------------------------------------------
|
|
163
|
+
|
|
164
|
+
export interface PanelLayoutWithTimestamp extends PanelLayout {
|
|
165
|
+
updatedAt: string;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Fetch workspace from server */
|
|
169
|
+
export async function fetchWorkspaceFromServer(
|
|
170
|
+
projectName: string,
|
|
171
|
+
): Promise<PanelLayoutWithTimestamp | null> {
|
|
172
|
+
try {
|
|
173
|
+
const headers: Record<string, string> = {};
|
|
174
|
+
const token = localStorage.getItem("ppm-auth-token");
|
|
175
|
+
if (token) headers["Authorization"] = `Bearer ${token}`;
|
|
176
|
+
|
|
177
|
+
const res = await fetch(`/api/project/${encodeURIComponent(projectName)}/workspace`, { headers });
|
|
178
|
+
if (!res.ok) return null;
|
|
179
|
+
const json = await res.json();
|
|
180
|
+
if (!json.ok || !json.data) return null;
|
|
181
|
+
return { ...json.data.layout, updatedAt: json.data.updatedAt };
|
|
182
|
+
} catch {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Save workspace to server (debounced per project) */
|
|
188
|
+
const syncTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
189
|
+
|
|
190
|
+
function syncWorkspaceToServer(projectName: string, layout: PanelLayout): void {
|
|
191
|
+
const existing = syncTimers.get(projectName);
|
|
192
|
+
if (existing) clearTimeout(existing);
|
|
193
|
+
|
|
194
|
+
syncTimers.set(projectName, setTimeout(async () => {
|
|
195
|
+
syncTimers.delete(projectName);
|
|
196
|
+
try {
|
|
197
|
+
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
198
|
+
const token = localStorage.getItem("ppm-auth-token");
|
|
199
|
+
if (token) headers["Authorization"] = `Bearer ${token}`;
|
|
200
|
+
|
|
201
|
+
const res = await fetch(`/api/project/${encodeURIComponent(projectName)}/workspace`, {
|
|
202
|
+
method: "PUT",
|
|
203
|
+
headers,
|
|
204
|
+
body: JSON.stringify({ layout }),
|
|
205
|
+
});
|
|
206
|
+
if (res.ok) {
|
|
207
|
+
const json = await res.json();
|
|
208
|
+
if (json.data?.updatedAt) {
|
|
209
|
+
const key = `${STORAGE_PREFIX}${projectName}`;
|
|
210
|
+
const raw = localStorage.getItem(key);
|
|
211
|
+
if (raw) {
|
|
212
|
+
const local = JSON.parse(raw);
|
|
213
|
+
local.updatedAt = json.data.updatedAt;
|
|
214
|
+
localStorage.setItem(key, JSON.stringify(local));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
} catch { /* silent fail — localStorage is still the cache */ }
|
|
219
|
+
}, 1500));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Compare local vs server timestamps, return newer layout */
|
|
223
|
+
export function resolveWorkspaceConflict(
|
|
224
|
+
local: PanelLayoutWithTimestamp | null,
|
|
225
|
+
server: PanelLayoutWithTimestamp | null,
|
|
226
|
+
): PanelLayoutWithTimestamp | null {
|
|
227
|
+
if (!local && !server) return null;
|
|
228
|
+
if (!local) return server!;
|
|
229
|
+
if (!server) return local;
|
|
230
|
+
|
|
231
|
+
const localTime = new Date(local.updatedAt).getTime();
|
|
232
|
+
const serverTime = new Date(server.updatedAt).getTime();
|
|
233
|
+
return serverTime >= localTime ? server : local;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ---------------------------------------------------------------------------
|
|
237
|
+
// Old format migration
|
|
238
|
+
// ---------------------------------------------------------------------------
|
|
239
|
+
|
|
98
240
|
function migrateOldTabStore(projectName: string): PanelLayout | null {
|
|
99
241
|
try {
|
|
100
242
|
const raw = localStorage.getItem(`${OLD_STORAGE_PREFIX}${projectName}`);
|
|
@@ -2,7 +2,7 @@ import { create } from "zustand";
|
|
|
2
2
|
|
|
3
3
|
export type Theme = "light" | "dark" | "system";
|
|
4
4
|
export type GitStatusViewMode = "flat" | "tree";
|
|
5
|
-
export type SidebarActiveTab = "explorer" | "git" | "settings" | "database" | "search"
|
|
5
|
+
export type SidebarActiveTab = "explorer" | "git" | "settings" | "database" | "search" | `ext:${string}`;
|
|
6
6
|
|
|
7
7
|
const STORAGE_KEY = "ppm-settings";
|
|
8
8
|
|
|
@@ -44,6 +44,11 @@ function loadPersistedSettings(): PersistedSettings {
|
|
|
44
44
|
return {};
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
+
function isValidSidebarTab(tab: unknown): tab is SidebarActiveTab {
|
|
48
|
+
if (typeof tab !== "string") return false;
|
|
49
|
+
return ["explorer", "git", "settings", "database", "search"].includes(tab) || tab.startsWith("ext:");
|
|
50
|
+
}
|
|
51
|
+
|
|
47
52
|
function persistSettings(update: Partial<PersistedSettings>) {
|
|
48
53
|
const current = loadPersistedSettings();
|
|
49
54
|
localStorage.setItem(STORAGE_KEY, JSON.stringify({ ...current, ...update }));
|
|
@@ -79,7 +84,7 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
|
|
|
79
84
|
sidebarWidth: _initial.sidebarWidth ?? 280,
|
|
80
85
|
gitStatusViewMode: _initial.gitStatusViewMode === "flat" ? "flat" : "tree",
|
|
81
86
|
wordWrap: _initial.wordWrap ?? false,
|
|
82
|
-
sidebarActiveTab: (
|
|
87
|
+
sidebarActiveTab: isValidSidebarTab(_initial.sidebarActiveTab) ? _initial.sidebarActiveTab : "explorer",
|
|
83
88
|
deviceName: null,
|
|
84
89
|
version: null,
|
|
85
90
|
|
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Test script: Advanced Session Operations
|
|
3
|
+
* Tests: listSessions, getSessionMessages, forkSession (mid-message), deleteSession, resumeSessionAt
|
|
4
|
+
*
|
|
5
|
+
* Usage: bun test-session-ops.mjs [test-name]
|
|
6
|
+
* Tests: list | messages | fork-mid | delete | resume-at | compact-summary | all
|
|
7
|
+
*/
|
|
8
|
+
import {
|
|
9
|
+
query,
|
|
10
|
+
listSessions,
|
|
11
|
+
getSessionMessages,
|
|
12
|
+
getSessionInfo,
|
|
13
|
+
forkSession,
|
|
14
|
+
renameSession,
|
|
15
|
+
tagSession,
|
|
16
|
+
} from "@anthropic-ai/claude-agent-sdk";
|
|
17
|
+
import { existsSync, unlinkSync, readdirSync } from "node:fs";
|
|
18
|
+
import { homedir } from "node:os";
|
|
19
|
+
import { resolve } from "node:path";
|
|
20
|
+
|
|
21
|
+
// Remove CLAUDECODE to avoid nested session error
|
|
22
|
+
delete process.env.CLAUDECODE;
|
|
23
|
+
|
|
24
|
+
const PROJECT_DIR = "/Users/hienlh/Projects/ppm";
|
|
25
|
+
const CLAUDE_PROJECTS_DIR = resolve(homedir(), ".claude/projects");
|
|
26
|
+
const testName = process.argv[2] || "all";
|
|
27
|
+
|
|
28
|
+
// Helpers
|
|
29
|
+
function log(label, data) {
|
|
30
|
+
console.log(`\n${"=".repeat(60)}`);
|
|
31
|
+
console.log(`[${label}]`);
|
|
32
|
+
console.log("=".repeat(60));
|
|
33
|
+
if (data !== undefined) console.log(typeof data === "string" ? data : JSON.stringify(data, null, 2));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function logOk(msg) { console.log(` ✅ ${msg}`); }
|
|
37
|
+
function logFail(msg) { console.log(` ❌ ${msg}`); }
|
|
38
|
+
function logInfo(msg) { console.log(` ℹ️ ${msg}`); }
|
|
39
|
+
|
|
40
|
+
// ─── Test 1: List Sessions ──────────────────────────────────────────────────
|
|
41
|
+
async function testListSessions() {
|
|
42
|
+
log("TEST: listSessions");
|
|
43
|
+
|
|
44
|
+
// List all sessions for PPM project
|
|
45
|
+
const sessions = await listSessions({ dir: PROJECT_DIR, limit: 10 });
|
|
46
|
+
logInfo(`Found ${sessions.length} sessions for PPM project`);
|
|
47
|
+
|
|
48
|
+
for (const s of sessions.slice(0, 5)) {
|
|
49
|
+
console.log(` - ${s.sessionId.slice(0, 8)}... | "${s.summary?.slice(0, 50)}" | modified=${new Date(s.lastModified).toISOString().slice(0, 16)} | tag=${s.tag ?? "none"}`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (sessions.length > 0) logOk("listSessions works");
|
|
53
|
+
else logFail("No sessions found");
|
|
54
|
+
|
|
55
|
+
return sessions;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// ─── Test 2: Get Session Messages ───────────────────────────────────────────
|
|
59
|
+
async function testGetMessages(sessionId) {
|
|
60
|
+
log("TEST: getSessionMessages");
|
|
61
|
+
|
|
62
|
+
if (!sessionId) {
|
|
63
|
+
const sessions = await listSessions({ dir: PROJECT_DIR, limit: 5 });
|
|
64
|
+
sessionId = sessions[0]?.sessionId;
|
|
65
|
+
if (!sessionId) { logFail("No session to test"); return; }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
logInfo(`Reading messages from session ${sessionId.slice(0, 8)}...`);
|
|
69
|
+
|
|
70
|
+
// Test with no limit
|
|
71
|
+
const allMsgs = await getSessionMessages(sessionId, { dir: PROJECT_DIR });
|
|
72
|
+
logInfo(`Total messages: ${allMsgs.length}`);
|
|
73
|
+
|
|
74
|
+
// Show first few messages with UUIDs (needed for fork-mid test)
|
|
75
|
+
for (const [i, msg] of allMsgs.slice(0, 6).entries()) {
|
|
76
|
+
const preview = typeof msg.message === "object"
|
|
77
|
+
? JSON.stringify(msg.message).slice(0, 80)
|
|
78
|
+
: String(msg.message).slice(0, 80);
|
|
79
|
+
console.log(` [${i}] type=${msg.type} uuid=${msg.uuid.slice(0, 8)}... | ${preview}`);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Test with limit/offset
|
|
83
|
+
const page1 = await getSessionMessages(sessionId, { dir: PROJECT_DIR, limit: 2 });
|
|
84
|
+
const page2 = await getSessionMessages(sessionId, { dir: PROJECT_DIR, limit: 2, offset: 2 });
|
|
85
|
+
logInfo(`Pagination: page1=${page1.length} msgs, page2=${page2.length} msgs`);
|
|
86
|
+
|
|
87
|
+
if (allMsgs.length > 0) logOk(`getSessionMessages works (${allMsgs.length} messages)`);
|
|
88
|
+
else logFail("No messages found");
|
|
89
|
+
|
|
90
|
+
return allMsgs;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ─── Test 3: Fork at Mid-Message ────────────────────────────────────────────
|
|
94
|
+
async function testForkMid() {
|
|
95
|
+
log("TEST: forkSession with upToMessageId");
|
|
96
|
+
|
|
97
|
+
// Find a session with multiple messages
|
|
98
|
+
const sessions = await listSessions({ dir: PROJECT_DIR, limit: 20 });
|
|
99
|
+
let sourceSession = null;
|
|
100
|
+
let sourceMessages = [];
|
|
101
|
+
|
|
102
|
+
for (const s of sessions) {
|
|
103
|
+
const msgs = await getSessionMessages(s.sessionId, { dir: PROJECT_DIR });
|
|
104
|
+
if (msgs.length >= 4) {
|
|
105
|
+
sourceSession = s;
|
|
106
|
+
sourceMessages = msgs;
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (!sourceSession) {
|
|
112
|
+
logFail("No session with 4+ messages found");
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
logInfo(`Source: ${sourceSession.sessionId.slice(0, 8)}... (${sourceMessages.length} messages)`);
|
|
117
|
+
|
|
118
|
+
// Fork at the 2nd message (mid-conversation)
|
|
119
|
+
const forkAtMsg = sourceMessages[1]; // 2nd message
|
|
120
|
+
logInfo(`Forking at message[1]: uuid=${forkAtMsg.uuid.slice(0, 8)}... type=${forkAtMsg.type}`);
|
|
121
|
+
|
|
122
|
+
try {
|
|
123
|
+
const result = await forkSession(sourceSession.sessionId, {
|
|
124
|
+
dir: PROJECT_DIR,
|
|
125
|
+
upToMessageId: forkAtMsg.uuid,
|
|
126
|
+
title: `[TEST] Fork at msg[1] - ${new Date().toISOString().slice(11, 19)}`,
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
logOk(`Fork created! New sessionId: ${result.sessionId}`);
|
|
130
|
+
|
|
131
|
+
// Verify forked session has fewer messages
|
|
132
|
+
const forkedMsgs = await getSessionMessages(result.sessionId, { dir: PROJECT_DIR });
|
|
133
|
+
logInfo(`Forked session has ${forkedMsgs.length} messages (source had ${sourceMessages.length})`);
|
|
134
|
+
|
|
135
|
+
if (forkedMsgs.length <= sourceMessages.length) {
|
|
136
|
+
logOk(`Mid-fork works: ${forkedMsgs.length} ≤ ${sourceMessages.length} messages`);
|
|
137
|
+
} else {
|
|
138
|
+
logFail(`Fork has more messages than source?!`);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Get info about forked session
|
|
142
|
+
const info = await getSessionInfo(result.sessionId, { dir: PROJECT_DIR });
|
|
143
|
+
logInfo(`Fork info: title="${info?.summary}" created=${info?.createdAt ? new Date(info.createdAt).toISOString().slice(0, 16) : "?"}`);
|
|
144
|
+
|
|
145
|
+
return result.sessionId;
|
|
146
|
+
} catch (e) {
|
|
147
|
+
logFail(`forkSession failed: ${e.message}`);
|
|
148
|
+
console.error(e);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ─── Test 4: Delete Session (JSONL) ─────────────────────────────────────────
|
|
153
|
+
async function testDelete(sessionIdToDelete) {
|
|
154
|
+
log("TEST: deleteSession (JSONL unlink)");
|
|
155
|
+
|
|
156
|
+
// If no specific session, create a disposable one first via forkSession
|
|
157
|
+
if (!sessionIdToDelete) {
|
|
158
|
+
logInfo("Creating disposable session via fork for delete test...");
|
|
159
|
+
const sessions = await listSessions({ dir: PROJECT_DIR, limit: 5 });
|
|
160
|
+
if (sessions.length === 0) { logFail("No sessions to fork from"); return; }
|
|
161
|
+
|
|
162
|
+
const result = await forkSession(sessions[0].sessionId, {
|
|
163
|
+
dir: PROJECT_DIR,
|
|
164
|
+
title: "[TEST] Disposable for delete test",
|
|
165
|
+
});
|
|
166
|
+
sessionIdToDelete = result.sessionId;
|
|
167
|
+
logInfo(`Created disposable: ${sessionIdToDelete}`);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Find the JSONL file on disk
|
|
171
|
+
const projectDirs = readdirSync(CLAUDE_PROJECTS_DIR);
|
|
172
|
+
let jsonlPath = null;
|
|
173
|
+
|
|
174
|
+
for (const dir of projectDirs) {
|
|
175
|
+
const candidate = resolve(CLAUDE_PROJECTS_DIR, dir, `${sessionIdToDelete}.jsonl`);
|
|
176
|
+
if (existsSync(candidate)) {
|
|
177
|
+
jsonlPath = candidate;
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (!jsonlPath) {
|
|
183
|
+
logFail(`JSONL file not found for session ${sessionIdToDelete}`);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
logInfo(`Found JSONL: ${jsonlPath}`);
|
|
188
|
+
|
|
189
|
+
// Delete the file
|
|
190
|
+
unlinkSync(jsonlPath);
|
|
191
|
+
logInfo("JSONL deleted");
|
|
192
|
+
|
|
193
|
+
// Verify it's gone from listSessions
|
|
194
|
+
const afterSessions = await listSessions({ dir: PROJECT_DIR, limit: 100 });
|
|
195
|
+
const stillExists = afterSessions.some(s => s.sessionId === sessionIdToDelete);
|
|
196
|
+
|
|
197
|
+
if (!stillExists) {
|
|
198
|
+
logOk("Session deleted successfully — no longer in listSessions");
|
|
199
|
+
} else {
|
|
200
|
+
logFail("Session still appears in listSessions after JSONL deletion!");
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ─── Test 5: resumeSessionAt ────────────────────────────────────────────────
|
|
205
|
+
async function testResumeAt() {
|
|
206
|
+
log("TEST: resumeSessionAt (resume from specific message)");
|
|
207
|
+
|
|
208
|
+
// Find a session with enough messages
|
|
209
|
+
const sessions = await listSessions({ dir: PROJECT_DIR, limit: 20 });
|
|
210
|
+
let sourceSession = null;
|
|
211
|
+
let sourceMessages = [];
|
|
212
|
+
|
|
213
|
+
for (const s of sessions) {
|
|
214
|
+
const msgs = await getSessionMessages(s.sessionId, { dir: PROJECT_DIR });
|
|
215
|
+
if (msgs.length >= 4) {
|
|
216
|
+
sourceSession = s;
|
|
217
|
+
sourceMessages = msgs;
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (!sourceSession) {
|
|
223
|
+
logFail("No session with 4+ messages for resumeAt test");
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Pick middle message to resume from
|
|
228
|
+
const midIdx = Math.floor(sourceMessages.length / 2);
|
|
229
|
+
const resumeAtMsg = sourceMessages[midIdx];
|
|
230
|
+
logInfo(`Source: ${sourceSession.sessionId.slice(0, 8)}... (${sourceMessages.length} msgs)`);
|
|
231
|
+
logInfo(`Resuming at message[${midIdx}]: uuid=${resumeAtMsg.uuid.slice(0, 8)}... type=${resumeAtMsg.type}`);
|
|
232
|
+
|
|
233
|
+
try {
|
|
234
|
+
// Use query() with resume + resumeSessionAt + forkSession to test
|
|
235
|
+
const q = query({
|
|
236
|
+
prompt: "Just say 'RESUME_AT_TEST_OK' and nothing else.",
|
|
237
|
+
options: {
|
|
238
|
+
resume: sourceSession.sessionId,
|
|
239
|
+
resumeSessionAt: resumeAtMsg.uuid,
|
|
240
|
+
forkSession: true,
|
|
241
|
+
cwd: PROJECT_DIR,
|
|
242
|
+
maxTurns: 1,
|
|
243
|
+
allowedTools: [],
|
|
244
|
+
permissionMode: "bypassPermissions",
|
|
245
|
+
systemPrompt: { type: "custom", value: "You are a test assistant. Reply exactly as instructed." },
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
let resultSessionId = null;
|
|
250
|
+
let gotText = false;
|
|
251
|
+
|
|
252
|
+
for await (const msg of q) {
|
|
253
|
+
if (msg.type === "assistant") {
|
|
254
|
+
const textBlocks = (msg.message?.content || []).filter(b => b.type === "text");
|
|
255
|
+
if (textBlocks.length > 0) {
|
|
256
|
+
logInfo(`Assistant replied: "${textBlocks.map(b => b.text).join("").slice(0, 100)}"`);
|
|
257
|
+
gotText = true;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (msg.type === "result") {
|
|
261
|
+
resultSessionId = msg.session_id;
|
|
262
|
+
logInfo(`Result: subtype=${msg.subtype} session=${resultSessionId?.slice(0, 8)}... cost=$${msg.total_cost_usd?.toFixed(4)}`);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (gotText && resultSessionId) {
|
|
267
|
+
logOk(`resumeSessionAt works! Forked session: ${resultSessionId}`);
|
|
268
|
+
|
|
269
|
+
// Check the forked session has truncated history
|
|
270
|
+
const forkedMsgs = await getSessionMessages(resultSessionId, { dir: PROJECT_DIR });
|
|
271
|
+
logInfo(`Forked session messages: ${forkedMsgs.length} (original: ${sourceMessages.length})`);
|
|
272
|
+
|
|
273
|
+
// Cleanup: delete test session
|
|
274
|
+
return resultSessionId;
|
|
275
|
+
} else {
|
|
276
|
+
logFail("resumeSessionAt did not produce expected output");
|
|
277
|
+
}
|
|
278
|
+
} catch (e) {
|
|
279
|
+
logFail(`resumeSessionAt failed: ${e.message}`);
|
|
280
|
+
console.error(e);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// ─── Test 6: Compact/Summary for Merge ──────────────────────────────────────
|
|
285
|
+
async function testCompactSummary() {
|
|
286
|
+
log("TEST: Generate summary for merge (using query + compact approach)");
|
|
287
|
+
|
|
288
|
+
// Find a session with enough content
|
|
289
|
+
const sessions = await listSessions({ dir: PROJECT_DIR, limit: 20 });
|
|
290
|
+
let sourceSession = null;
|
|
291
|
+
let sourceMessages = [];
|
|
292
|
+
|
|
293
|
+
for (const s of sessions) {
|
|
294
|
+
const msgs = await getSessionMessages(s.sessionId, { dir: PROJECT_DIR });
|
|
295
|
+
if (msgs.length >= 6) {
|
|
296
|
+
sourceSession = s;
|
|
297
|
+
sourceMessages = msgs;
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
if (!sourceSession) {
|
|
303
|
+
logFail("No session with 6+ messages for compact test");
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
logInfo(`Source: ${sourceSession.sessionId.slice(0, 8)}... (${sourceMessages.length} msgs)`);
|
|
308
|
+
|
|
309
|
+
// Extract conversation text for summary
|
|
310
|
+
const conversationText = sourceMessages.slice(0, 10).map((msg, i) => {
|
|
311
|
+
const content = msg.message?.content;
|
|
312
|
+
let text = "";
|
|
313
|
+
if (typeof content === "string") {
|
|
314
|
+
text = content;
|
|
315
|
+
} else if (Array.isArray(content)) {
|
|
316
|
+
text = content
|
|
317
|
+
.filter(b => b.type === "text")
|
|
318
|
+
.map(b => b.text)
|
|
319
|
+
.join("\n")
|
|
320
|
+
.slice(0, 500);
|
|
321
|
+
}
|
|
322
|
+
return `[${msg.type}] ${text.slice(0, 300)}`;
|
|
323
|
+
}).join("\n---\n");
|
|
324
|
+
|
|
325
|
+
logInfo(`Conversation excerpt (${conversationText.length} chars):\n${conversationText.slice(0, 500)}...`);
|
|
326
|
+
|
|
327
|
+
// Use a cheap query to generate summary
|
|
328
|
+
logInfo("Generating summary via Claude (short query)...");
|
|
329
|
+
try {
|
|
330
|
+
const summaryPrompt = `Summarize this conversation in 3-5 bullet points. Focus on: what was discussed, what decisions were made, what files were modified.
|
|
331
|
+
|
|
332
|
+
CONVERSATION:
|
|
333
|
+
${conversationText.slice(0, 3000)}
|
|
334
|
+
|
|
335
|
+
Reply with ONLY the bullet points, no preamble.`;
|
|
336
|
+
|
|
337
|
+
const q = query({
|
|
338
|
+
prompt: summaryPrompt,
|
|
339
|
+
options: {
|
|
340
|
+
cwd: PROJECT_DIR,
|
|
341
|
+
maxTurns: 1,
|
|
342
|
+
allowedTools: [],
|
|
343
|
+
permissionMode: "bypassPermissions",
|
|
344
|
+
model: "haiku",
|
|
345
|
+
systemPrompt: { type: "custom", value: "You are a concise conversation summarizer." },
|
|
346
|
+
persistSession: false, // Don't save this summary session
|
|
347
|
+
},
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
let summary = "";
|
|
351
|
+
for await (const msg of q) {
|
|
352
|
+
if (msg.type === "assistant") {
|
|
353
|
+
const textBlocks = (msg.message?.content || []).filter(b => b.type === "text");
|
|
354
|
+
summary += textBlocks.map(b => b.text).join("");
|
|
355
|
+
}
|
|
356
|
+
if (msg.type === "result") {
|
|
357
|
+
logInfo(`Summary cost: $${msg.total_cost_usd?.toFixed(4)}`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
if (summary) {
|
|
362
|
+
logOk("Summary generated successfully:");
|
|
363
|
+
console.log(`\n${summary}\n`);
|
|
364
|
+
logInfo("This summary could be injected into a merge session's system prompt");
|
|
365
|
+
} else {
|
|
366
|
+
logFail("No summary text produced");
|
|
367
|
+
}
|
|
368
|
+
} catch (e) {
|
|
369
|
+
logFail(`Summary generation failed: ${e.message}`);
|
|
370
|
+
console.error(e);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// ─── Test 7: Tag Session ────────────────────────────────────────────────────
|
|
375
|
+
async function testTagSession() {
|
|
376
|
+
log("TEST: tagSession");
|
|
377
|
+
|
|
378
|
+
const sessions = await listSessions({ dir: PROJECT_DIR, limit: 5 });
|
|
379
|
+
if (sessions.length === 0) { logFail("No sessions"); return; }
|
|
380
|
+
|
|
381
|
+
const target = sessions[0];
|
|
382
|
+
logInfo(`Tagging session ${target.sessionId.slice(0, 8)}... (current tag: ${target.tag ?? "none"})`);
|
|
383
|
+
|
|
384
|
+
try {
|
|
385
|
+
await tagSession(target.sessionId, "test-tag", { dir: PROJECT_DIR });
|
|
386
|
+
const info = await getSessionInfo(target.sessionId, { dir: PROJECT_DIR });
|
|
387
|
+
logInfo(`After tag: tag="${info?.tag}"`);
|
|
388
|
+
|
|
389
|
+
if (info?.tag === "test-tag") {
|
|
390
|
+
logOk("tagSession works");
|
|
391
|
+
} else {
|
|
392
|
+
logFail(`Expected tag="test-tag", got "${info?.tag}"`);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// Clear tag
|
|
396
|
+
await tagSession(target.sessionId, null, { dir: PROJECT_DIR });
|
|
397
|
+
logInfo("Tag cleared");
|
|
398
|
+
|
|
399
|
+
} catch (e) {
|
|
400
|
+
logFail(`tagSession failed: ${e.message}`);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// ─── Runner ─────────────────────────────────────────────────────────────────
|
|
405
|
+
async function main() {
|
|
406
|
+
console.log(`\n🧪 Session Operations Test Suite`);
|
|
407
|
+
console.log(`Project: ${PROJECT_DIR}`);
|
|
408
|
+
console.log(`Test: ${testName}\n`);
|
|
409
|
+
|
|
410
|
+
const tests = {
|
|
411
|
+
list: testListSessions,
|
|
412
|
+
messages: testGetMessages,
|
|
413
|
+
"fork-mid": testForkMid,
|
|
414
|
+
delete: testDelete,
|
|
415
|
+
"resume-at": testResumeAt,
|
|
416
|
+
"compact-summary": testCompactSummary,
|
|
417
|
+
tag: testTagSession,
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
if (testName === "all") {
|
|
421
|
+
// Run non-destructive tests first
|
|
422
|
+
await testListSessions();
|
|
423
|
+
await testGetMessages();
|
|
424
|
+
await testTagSession();
|
|
425
|
+
await testForkMid();
|
|
426
|
+
// resume-at and compact-summary cost API tokens — ask first
|
|
427
|
+
console.log("\n⚠️ Remaining tests (resume-at, compact-summary) cost API tokens.");
|
|
428
|
+
console.log(" Run individually: bun test-session-ops.mjs resume-at");
|
|
429
|
+
console.log(" Run individually: bun test-session-ops.mjs compact-summary");
|
|
430
|
+
console.log(" Delete test: bun test-session-ops.mjs delete");
|
|
431
|
+
} else if (tests[testName]) {
|
|
432
|
+
await tests[testName]();
|
|
433
|
+
} else {
|
|
434
|
+
console.log(`Unknown test: ${testName}`);
|
|
435
|
+
console.log(`Available: ${Object.keys(tests).join(", ")}, all`);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
log("DONE", `Finished ${testName} test(s)`);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
main().catch(e => {
|
|
442
|
+
console.error("Fatal:", e);
|
|
443
|
+
process.exit(1);
|
|
444
|
+
});
|