Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/memory/codex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { promises as fs } from 'fs';
import { resolve, basename, join } from 'path';
import { getDateLocale } from '../locale/index.js';
import { homedir } from 'os';
import { createHash } from 'crypto';
import { createHash, randomUUID } from 'crypto';
import { withFileLock } from '../support/fileLock.js';
import { atomicWriteFile } from '../support/atomicFile.js';

Expand Down Expand Up @@ -364,6 +364,15 @@ async function updateIndex(session: CodexSession, summaryPath: string): Promise<
});
}

/**
* A session id that does not collide when two sessions start in the same
* millisecond (parallel workers). Keeps the `session-<ms>` prefix so ids still
* sort and read by start time; the random suffix makes them unique.
*/
export function newSessionId(now: number = Date.now()): string {
return `session-${now}-${randomUUID()}`;
}

/**
* Session builder - incrementally construct a session
*/
Expand All @@ -373,7 +382,7 @@ export class SessionBuilder {

constructor(title: string) {
this.session = {
id: `session-${Date.now()}`,
id: newSessionId(),
title,
startedAt: Date.now(),
tags: [],
Expand Down
35 changes: 35 additions & 0 deletions src/memory/sessionId.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// ============================================
// OpenSwarm - codex session id uniqueness tests
// ============================================
//
// Session ids used to be `session-${Date.now()}`, so two sessions started in
// the same millisecond (parallel workers) got the same id and their records
// mixed. The id keeps the `session-<ms>` prefix and adds a random suffix.

import { afterEach, describe, expect, it, vi } from 'vitest';
import { SessionBuilder, newSessionId, sessionFilenameSuffix } from './codex.js';

const AT = 1_785_050_644_884;

describe('codex session id', () => {
afterEach(() => {
vi.useRealTimers();
});

it('gives two sessions started in the same millisecond different ids', () => {
vi.useFakeTimers();
vi.setSystemTime(AT);
const a = new SessionBuilder('same title').getSession();
const b = new SessionBuilder('same title').getSession();
expect(a.startedAt).toBe(b.startedAt);
expect(a.id).not.toBe(b.id);
expect(sessionFilenameSuffix(a.id)).not.toBe(sessionFilenameSuffix(b.id));
});

it('keeps the session-<ms> prefix so ids still read by start time', () => {
vi.useFakeTimers();
vi.setSystemTime(AT);
expect(new SessionBuilder('t').getSession().id.startsWith(`session-${AT}-`)).toBe(true);
expect(newSessionId(AT)).toMatch(new RegExp(`^session-${AT}-[0-9a-f-]{36}$`));
});
});
Loading