File size: 10,570 Bytes
68d7816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Service } from '#/_base/di/service';
import { LifecycleScope } from '#/app/scopes';
import { ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { Emitter, type Event } from '#/_base/event';
import { ILogService } from '#/_base/log/log';
import { defineState } from '#/state/state';
import { ISessionIndexMirror } from '#/app/sessionIndex/sessionIndex';
import { buildSessionSummary } from '#/app/sessionIndex/sessionIndexSource';
import { IAtomicDocumentStore } from '#/persistence/interface/atomicDocumentStore';
import { ISessionContext } from '#/session/sessionContext/sessionContext';
import { ISessionStateService } from '#/session/state/sessionState';

import {
  ISessionMetadata,
  SESSION_META_VERSION,
  type AgentMeta,
  type SessionMeta,
  type SessionMetadataChangedEvent,
  type SessionMetaPatch,
  type SessionTitleKind,
} from './sessionMetadata';

const META_KEY = 'state.json';

const pendingWrites = new Set<Promise<void>>();

export async function drainSessionMetadataWrites(): Promise<void> {
  await Promise.all(pendingWrites);
}

export const sessionMetadataDataKey = defineState<SessionMeta | undefined>(
  'sessionMetadata.data',
  () => undefined,
);

export class SessionMetadata extends Service implements ISessionMetadata {
  declare readonly _serviceBrand: undefined;

  private disposed = false;
  readonly ready: Promise<void>;
  readonly onDidChangeMetadata: Event<SessionMetadataChangedEvent>;

  private readonly _onDidChangeMetadata = this._register(
    new Emitter<SessionMetadataChangedEvent>(),
  );
  private readonly scope: string;
  private updateQueue: Promise<void> = Promise.resolve();

  constructor(
    @ISessionStateService private readonly states: ISessionStateService,
    @ISessionContext private readonly ctx: ISessionContext,
    @IAtomicDocumentStore private readonly store: IAtomicDocumentStore,
    @ILogService private readonly log: ILogService,
    @ISessionIndexMirror private readonly mirror: ISessionIndexMirror,
  ) {
    super();
    this._register({
      dispose: () => {
        this.disposed = true;
      },
    });
    this.states.contributeState(sessionMetadataDataKey);
    this.scope = ctx.metaScope;
    this.onDidChangeMetadata = this._onDidChangeMetadata.event;
    this.ready = this.load();
  }

  private get data(): SessionMeta {
    return this.states.get(sessionMetadataDataKey) as SessionMeta;
  }

  private set data(value: SessionMeta) {
    this.states.set(sessionMetadataDataKey, value);
  }

  async read(): Promise<SessionMeta> {
    await this.ready;
    return this.data;
  }

  async update(
    patch: SessionMetaPatch,
    opts?: { readonly touchUpdatedAt?: boolean },
  ): Promise<void> {
    return this.enqueueUpdate(async () => {
      await this.applyUpdate(patch, opts);
    });
  }

  private async applyUpdate(
    patch: SessionMetaPatch,
    opts?: { readonly touchUpdatedAt?: boolean },
  ): Promise<boolean> {
    await this.ready;
    if (this.disposed) return false;
    const updatedAt =
      patch.updatedAt ?? (opts?.touchUpdatedAt === false ? this.data.updatedAt : Date.now());
    this.data = { ...this.data, ...patch, updatedAt };
    await this.store.set(this.scope, META_KEY, encodeSessionMeta(this.data));
    if (this.disposed) return false;
    this.mirrorToReadModel();
    this._onDidChangeMetadata.fire({
      changed: Object.keys(patch) as (keyof SessionMeta)[],
    });
    return true;
  }

  async setTitle(title: string): Promise<void> {
    await this.update({ title, titleKind: 'custom' }, { touchUpdatedAt: false });
  }

  async setGeneratedTitleIfUncustomized(
    title: string,
    opts?: { force?: boolean },
  ): Promise<boolean> {
    return this.enqueueUpdate(async () => {
      await this.ready;
      if (opts?.force !== true && this.data.titleKind === 'custom') return false;
      return this.applyUpdate({ title, titleKind: 'generated' }, { touchUpdatedAt: false });
    });
  }

  async setArchived(archived: boolean): Promise<void> {
    await this.update(
      archived ? { archived: true, archivedAt: Date.now() } : { archived: false, archivedAt: undefined },
      { touchUpdatedAt: false },
    );
  }

  async registerAgent(agentId: string, meta: AgentMeta): Promise<void> {
    return this.enqueueUpdate(async () => {
      await this.ready;
      const existing = this.data.agents?.[agentId];
      if (existing !== undefined && agentMetaEquals(existing, meta)) return;
      const agents = { ...this.data.agents, [agentId]: meta };
      await this.applyUpdate({ agents }, { touchUpdatedAt: false });
    });
  }

  private enqueueUpdate<T>(work: () => Promise<T>): Promise<T> {
    const run = this.updateQueue.then(work, work);
    const tracked: Promise<void> = run.then(
      () => undefined,
      () => undefined,
    );
    this.updateQueue = tracked;
    pendingWrites.add(tracked);
    void tracked.finally(() => pendingWrites.delete(tracked));
    return run;
  }

  private mirrorToReadModel(): void {
    try {
      this.mirror.record(
        buildSessionSummary({
          id: this.data.id,
          workspaceId: this.ctx.workspaceId,
          cwd: this.ctx.cwd,
          title: this.data.title,
          lastPrompt: this.data.lastPrompt,
          createdAt: this.data.createdAt,
          updatedAt: this.data.updatedAt,
          archived: this.data.archived === true,
          archivedAt: this.data.archivedAt,
          custom: this.data.custom,
          lastTurnReason: this.data.lastTurnReason,
        }),
      );
    } catch (error) {
      this.log.warn('session index mirror record failed; the read model heals by reconciliation', {
        sessionId: this.ctx.sessionId,
        error: error instanceof Error ? error.message : String(error),
      });
    }
  }

  private async load(): Promise<void> {
    const existing = await this.store.get<SessionMeta>(this.scope, META_KEY);
    if (existing !== undefined) {
      this.data = normalizeSessionMeta(existing, this.ctx.sessionId);
      if (
        this.data.agents === undefined ||
        this.data.custom === undefined ||
        sessionMetaTitleNeedsMigration(existing, this.data)
      ) {
        this.data = {
          ...this.data,
          agents: this.data.agents ?? {},
          custom: this.data.custom ?? {},
        };
        await this.store.set(this.scope, META_KEY, encodeSessionMeta(this.data));
      }
      return;
    }
    const now = Date.now();
    this.data = {
      id: this.ctx.sessionId,
      version: SESSION_META_VERSION,
      cwd: this.ctx.cwd,
      createdAt: now,
      updatedAt: now,
      archived: false,
      agents: {},
      custom: {},
    };
    await this.store.set(this.scope, META_KEY, encodeSessionMeta(this.data));
    this.mirrorToReadModel();
    this.log.debug('session metadata created', { sessionId: this.ctx.sessionId });
  }
}

function agentMetaEquals(a: AgentMeta, b: AgentMeta): boolean {
  return (
    a.homedir === b.homedir &&
    a.type === b.type &&
    (a.parentAgentId ?? null) === (b.parentAgentId ?? null) &&
    a.forkedFrom === b.forkedFrom &&
    a.swarmItem === b.swarmItem &&
    recordEquals(a.labels, b.labels)
  );
}

function recordEquals(a: AgentMeta['labels'], b: AgentMeta['labels']): boolean {
  const entriesA = Object.entries(a ?? {});
  const entriesB = Object.entries(b ?? {});
  return (
    entriesA.length === entriesB.length && entriesA.every(([key, value]) => b?.[key] === value)
  );
}

export function normalizeSessionMeta(raw: SessionMeta, sessionId: string): SessionMeta {
  const legacy = raw as unknown as LegacySessionMeta;
  const normalizedTitle = normalizeSessionTitle(legacy);
  const {
    createdAt: legacyCreatedAt,
    updatedAt: legacyUpdatedAt,
    workDir: legacyWorkDir,
    titleSource: _legacyTitleSource,
    isCustomTitle: _legacyIsCustomTitle,
    customTitle: _legacyCustomTitle,
    ...clean
  } = legacy;
  const cwd =
    clean.cwd ?? (typeof legacyWorkDir === 'string' && legacyWorkDir.length > 0
      ? legacyWorkDir
      : undefined);
  const { title, titleKind } = normalizedTitle;
  return {
    ...clean,
    id: clean.version === SESSION_META_VERSION ? clean.id : sessionId,
    version: SESSION_META_VERSION,
    cwd,
    title,
    titleKind,
    createdAt: toEpochMs(legacyCreatedAt),
    updatedAt: toEpochMs(legacyUpdatedAt),
    archived: clean.archived === true,
  };
}

type LegacySessionMeta = Omit<SessionMeta, 'createdAt' | 'updatedAt'> & {
  readonly createdAt?: unknown;
  readonly updatedAt?: unknown;
  readonly workDir?: unknown;
  readonly titleSource?: unknown;
  readonly isCustomTitle?: unknown;
  readonly customTitle?: unknown;
};

function normalizeSessionTitle(
  raw: LegacySessionMeta,
): Pick<SessionMeta, 'title' | 'titleKind'> {
  const title = typeof raw.title === 'string' ? raw.title : undefined;
  if (title !== undefined && raw.isCustomTitle === true) {
    return { title, titleKind: 'custom' };
  }
  if (title !== undefined && isSessionTitleKind(raw.titleKind)) {
    return { title, titleKind: raw.titleKind };
  }
  if (title !== undefined && raw.isCustomTitle === false) {
    return { title, titleKind: 'replaceable' };
  }
  if (typeof raw.customTitle === 'string') {
    return { title: raw.customTitle, titleKind: 'custom' };
  }
  return title === undefined ? {} : { title, titleKind: 'replaceable' };
}

function isSessionTitleKind(value: unknown): value is SessionTitleKind {
  return value === 'replaceable' || value === 'generated' || value === 'custom';
}

type PersistedSessionMeta = SessionMeta & { readonly isCustomTitle: boolean };

export function encodeSessionMeta(meta: SessionMeta): PersistedSessionMeta {
  return { ...meta, isCustomTitle: meta.titleKind === 'custom' };
}

function sessionMetaTitleNeedsMigration(raw: SessionMeta, normalized: SessionMeta): boolean {
  const record = raw as unknown as Record<string, unknown>;
  return (
    raw.title !== normalized.title ||
    raw.titleKind !== normalized.titleKind ||
    record['isCustomTitle'] !== (normalized.titleKind === 'custom') ||
    Object.hasOwn(record, 'titleSource') ||
    Object.hasOwn(record, 'customTitle')
  );
}

export function toEpochMs(value: unknown): number {
  if (typeof value === 'number' && Number.isFinite(value)) return value;
  if (typeof value === 'string') {
    const parsed = Date.parse(value);
    if (!Number.isNaN(parsed)) return parsed;
  }
  return 0;
}

registerScopedService(
  LifecycleScope.Session,
  ISessionMetadata,
  SessionMetadata,
  ScopeActivation.OnScopeCreated,
  'sessionMetadata',
);