forked from xorespesp/claude-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime-session-ownership.ts
More file actions
366 lines (320 loc) · 9.51 KB
/
Copy pathruntime-session-ownership.ts
File metadata and controls
366 lines (320 loc) · 9.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import type { EventLog, Session } from './types';
import {
readBrowserStorage,
removeBrowserStorage,
writeBrowserStorage,
} from './runtime-browser-storage';
import { getRuntimeStorageScope } from './runtime-url';
const OWNERSHIP_STORAGE_PREFIX = 'botvalia.runtime.ownership';
export type RuntimeSessionOwnershipMetadata = {
customTitle?: string;
archived?: boolean;
pinned?: boolean;
notes?: string;
workspacePath?: string;
updatedAt: string;
};
export type RuntimeSessionDraft = {
id: string;
title: string;
workspacePath: string;
projectName: string;
notes?: string;
archived?: boolean;
pinned?: boolean;
createdAt: string;
updatedAt: string;
};
type RuntimeSessionOwnershipStore = {
version: 1;
sessions: Record<string, RuntimeSessionOwnershipMetadata>;
drafts: Record<string, RuntimeSessionDraft>;
};
const EMPTY_STORE: RuntimeSessionOwnershipStore = {
version: 1,
sessions: {},
drafts: {},
};
function cloneStore(
store: RuntimeSessionOwnershipStore = EMPTY_STORE,
): RuntimeSessionOwnershipStore {
return {
version: 1,
sessions: { ...store.sessions },
drafts: { ...store.drafts },
};
}
function compactStore(
store: RuntimeSessionOwnershipStore = EMPTY_STORE,
): RuntimeSessionOwnershipStore {
const nextStore = cloneStore(store);
nextStore.sessions = Object.fromEntries(
Object.entries(nextStore.sessions).flatMap(([sessionId, metadata]) => {
const customTitle = metadata.customTitle?.trim() || undefined;
const notes = metadata.notes?.trim() || undefined;
const workspacePath = metadata.workspacePath?.trim() || undefined;
const archived = metadata.archived === true ? true : undefined;
const pinned = metadata.pinned === true ? true : undefined;
if (!customTitle && !notes && !workspacePath && !archived && !pinned) {
return [];
}
return [
[
sessionId,
{
...metadata,
customTitle,
notes,
workspacePath,
archived,
pinned,
},
] satisfies [string, RuntimeSessionOwnershipMetadata],
];
}),
);
nextStore.drafts = Object.fromEntries(
Object.entries(nextStore.drafts).map(([draftId, draft]) => [
draftId,
{
...draft,
title: draft.title.trim(),
workspacePath: draft.workspacePath.trim(),
notes: draft.notes?.trim() || undefined,
},
]),
);
return nextStore;
}
function getStorageKey(runtimeUrl: string | null | undefined): string | null {
const scope = getRuntimeStorageScope(runtimeUrl);
if (!scope) {
return null;
}
return `${OWNERSHIP_STORAGE_PREFIX}:${scope}`;
}
function getLegacyStorageKey(runtimeUrl: string | null | undefined): string | null {
if (!runtimeUrl?.trim()) {
return null;
}
return `${OWNERSHIP_STORAGE_PREFIX}:${runtimeUrl.trim()}`;
}
function sortSessions(sessions: Session[]): Session[] {
return [...sessions].sort((left, right) => {
if (Boolean(left.pinned) !== Boolean(right.pinned)) {
return left.pinned ? -1 : 1;
}
return Date.parse(right.updatedAt) - Date.parse(left.updatedAt);
});
}
function createDraftEvent(timestamp: string, message: string): EventLog {
return {
id: `draft-event-${timestamp}-${message.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`,
timestamp,
type: 'warn',
message,
};
}
function createDraftSession(draft: RuntimeSessionDraft): Session {
const timestamp = draft.updatedAt || draft.createdAt;
return {
id: draft.id,
shortId: 'draft',
projectName: draft.projectName,
title: draft.title,
workspaceName: draft.workspacePath || draft.projectName,
status: 'idle',
activeChannel: 'web-ui',
activeChannelUpdatedAt: timestamp,
permissionMode: 'default',
isBypassPermissionsModeAvailable: false,
isAutoModeAvailable: false,
model: 'pending-cli-runtime',
messages: [
{
id: `${draft.id}-intro`,
role: 'system',
content:
'Este borrador vive solo en la UI. Para convertirlo en una sesion runtime real todavia necesitas iniciarla desde el CLI.',
timestamp,
label: 'draft',
},
],
swarm: undefined,
events: [
createDraftEvent(
timestamp,
'Borrador creado en la UI. Pendiente de backend/create_session para lanzar el worker desde browser.',
),
],
startedAt: draft.createdAt,
updatedAt: draft.updatedAt,
archived: draft.archived || false,
pinned: draft.pinned || false,
notes: draft.notes,
isDraft: true,
messageCount: 0,
taskCount: 0,
rawSnapshot: draft,
rawDetail: draft,
};
}
export function readRuntimeSessionOwnershipStore(
runtimeUrl: string | null | undefined,
): RuntimeSessionOwnershipStore {
if (typeof window === 'undefined') {
return cloneStore();
}
const storageKey = getStorageKey(runtimeUrl);
if (!storageKey) {
return cloneStore();
}
try {
const legacyStorageKey = getLegacyStorageKey(runtimeUrl);
const raw =
readBrowserStorage(storageKey, 'session') ||
(legacyStorageKey ? readBrowserStorage(legacyStorageKey, 'local') : null);
if (!raw) {
return cloneStore();
}
const parsed = JSON.parse(raw) as Partial<RuntimeSessionOwnershipStore>;
const hydratedStore: RuntimeSessionOwnershipStore = {
version: 1,
sessions:
parsed.sessions && typeof parsed.sessions === 'object' ? parsed.sessions : {},
drafts: parsed.drafts && typeof parsed.drafts === 'object' ? parsed.drafts : {},
};
if (!readBrowserStorage(storageKey, 'session')) {
writeBrowserStorage(storageKey, JSON.stringify(hydratedStore), 'session');
}
if (legacyStorageKey) {
removeBrowserStorage(legacyStorageKey, 'local');
}
return hydratedStore;
} catch {
return cloneStore();
}
}
export function writeRuntimeSessionOwnershipStore(
runtimeUrl: string | null | undefined,
store: RuntimeSessionOwnershipStore,
): void {
if (typeof window === 'undefined') {
return;
}
const storageKey = getStorageKey(runtimeUrl);
if (!storageKey) {
return;
}
const compactedStore = compactStore(store);
const legacyStorageKey = getLegacyStorageKey(runtimeUrl);
const hasStoredSessions =
Object.keys(compactedStore.sessions).length > 0 ||
Object.keys(compactedStore.drafts).length > 0;
if (!hasStoredSessions) {
removeBrowserStorage(storageKey, 'session');
} else {
writeBrowserStorage(storageKey, JSON.stringify(compactedStore), 'session');
}
if (legacyStorageKey) {
removeBrowserStorage(legacyStorageKey, 'local');
}
}
export function applyRuntimeSessionOwnership(
sessions: Session[],
store: RuntimeSessionOwnershipStore,
): Session[] {
const liveSessions = sessions.map(session => {
if (session.isDraft) {
return session;
}
const metadata = store.sessions[session.id];
if (!metadata) {
return {
...session,
pinned: session.pinned || false,
notes: session.notes,
};
}
return {
...session,
title: metadata.customTitle?.trim() || session.title,
workspaceName: metadata.workspacePath?.trim() || session.workspaceName,
archived: metadata.archived ?? session.archived ?? false,
pinned: metadata.pinned ?? session.pinned ?? false,
notes: metadata.notes ?? session.notes,
};
});
const drafts = Object.values(store.drafts).map(createDraftSession);
return sortSessions([...liveSessions, ...drafts]);
}
export function stripDraftSessions(sessions: Session[]): Session[] {
return sessions.filter(session => !session.isDraft);
}
export function upsertSessionOwnershipMetadata(
store: RuntimeSessionOwnershipStore,
sessionId: string,
patch: Partial<Omit<RuntimeSessionOwnershipMetadata, 'updatedAt'>>,
): RuntimeSessionOwnershipStore {
const nextStore = cloneStore(store);
const previous = nextStore.sessions[sessionId] || { updatedAt: new Date().toISOString() };
nextStore.sessions[sessionId] = {
...previous,
...patch,
updatedAt: new Date().toISOString(),
};
return nextStore;
}
export function createSessionDraft(params: {
title: string;
workspacePath: string;
}): RuntimeSessionDraft {
const timestamp = new Date().toISOString();
const trimmedPath = params.workspacePath.trim();
const trimmedTitle = params.title.trim();
return {
id: `draft-${crypto.randomUUID()}`,
title: trimmedTitle,
workspacePath: trimmedPath,
projectName:
trimmedTitle ||
trimmedPath.replace(/\\/g, '/').split('/').filter(Boolean).at(-1) ||
'Runtime Draft',
createdAt: timestamp,
updatedAt: timestamp,
};
}
export function upsertSessionDraft(
store: RuntimeSessionOwnershipStore,
draft: RuntimeSessionDraft,
): RuntimeSessionOwnershipStore {
const nextStore = cloneStore(store);
nextStore.drafts[draft.id] = draft;
return nextStore;
}
export function updateSessionDraft(
store: RuntimeSessionOwnershipStore,
draftId: string,
patch: Partial<Omit<RuntimeSessionDraft, 'id' | 'createdAt'>>,
): RuntimeSessionOwnershipStore {
const existing = store.drafts[draftId];
if (!existing) {
return cloneStore(store);
}
const nextStore = cloneStore(store);
nextStore.drafts[draftId] = {
...existing,
...patch,
updatedAt: new Date().toISOString(),
};
return nextStore;
}
export function getNextVisibleSessionId(
sessions: Session[],
excludedSessionId: string,
): string | null {
const candidate = sessions.find(
session => session.id !== excludedSessionId && !session.archived,
);
return candidate?.id || null;
}