Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/fix-windows-workspace-duplicates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---

web: Fix duplicate workspace groups on Windows when the same folder is opened with different path spellings, such as a different drive-letter casing; all of the folder's sessions now list under the single merged group.
13 changes: 10 additions & 3 deletions apps/kimi-web/src/composables/client/useWorkspaceState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
STORAGE_KEYS,
} from '../../lib/storage';
import { parseDiff } from '../../lib/parseDiff';
import { workspaceRootKey } from '../../lib/rootKey';
import { sessionExportTraceToJsonl, traceKeyEvent } from '../../debug/trace';
import { readSessionIdFromLocation, sessionUrl } from '../../lib/sessionRoute';
import type { SessionUrlMode } from '../../lib/sessionRoute';
Expand Down Expand Up @@ -963,9 +964,15 @@ export function useWorkspaceState(rawState: ExtendedState, deps: UseWorkspaceSta
// clobber the name with the default basename.
const override = loadWorkspaceNameOverrides()[workspace.root];
const ws = override !== undefined ? { ...workspace, name: override } : workspace;
// Re-adding a path the user previously removed should bring it back.
if (rawState.hiddenWorkspaceRoots.includes(ws.root)) {
rawState.hiddenWorkspaceRoots = rawState.hiddenWorkspaceRoots.filter((r) => r !== ws.root);
// Re-adding a path the user previously removed should bring it back. The
// hidden match in mergeWorkspaces is folded, so the removal must fold too
// — otherwise hiding `C:\Foo` and re-adding `c:\foo` leaves the folded
// entry hiding the workspace forever.
const wsKey = workspaceRootKey(ws.root);
if (rawState.hiddenWorkspaceRoots.some((r) => workspaceRootKey(r) === wsKey)) {
rawState.hiddenWorkspaceRoots = rawState.hiddenWorkspaceRoots.filter(
(r) => workspaceRootKey(r) !== wsKey,
);
saveHiddenWorkspacesToStorage(rawState.hiddenWorkspaceRoots);
}
const index = rawState.workspaces.findIndex(
Expand Down
16 changes: 12 additions & 4 deletions apps/kimi-web/src/composables/useKimiWebClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
type WorkspaceSortMode,
} from '../lib/workspaceOrder';
import { mergeWorkspaces } from '../lib/mergeWorkspaces';
import { workspaceRootKey } from '../lib/rootKey';
import { mergeSnapshotMessages } from '../lib/snapshotMessages';
import { mergeSnapshotSubagents } from '../lib/taskMerge';
import { createCoalescedAsyncRunner } from '../lib/snapshotSync';
Expand Down Expand Up @@ -2263,12 +2264,19 @@ const changesByPath = computed<Record<string, string>>(() => {
// ---------------------------------------------------------------------------

/**
* The workspace id a session belongs to: prefer the daemon-provided
* session.workspaceId; otherwise map by cwd (in derived/fallback mode the
* workspace id IS the cwd).
* The workspace id a session belongs to: the first registered workspace whose
* root identity-matches the session cwd (folds Windows case/slash variants —
* keeps grouping consistent with `mergeWorkspaces` so a session never falls
* out of the group the merge rendered); otherwise the daemon-provided
* session.workspaceId; otherwise the cwd itself (derived/fallback mode).
*/
function workspaceIdForSession(s: { workspaceId?: string; cwd: string }): string {
return rawState.workspaces.find((w) => w.root === s.cwd)?.id ?? s.workspaceId ?? s.cwd;
const cwdKey = workspaceRootKey(s.cwd);
return (
rawState.workspaces.find((w) => workspaceRootKey(w.root) === cwdKey)?.id ??
s.workspaceId ??
s.cwd
);
}

/**
Expand Down
164 changes: 164 additions & 0 deletions apps/kimi-web/src/lib/mergeWorkspaces.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// apps/kimi-web/src/lib/mergeWorkspaces.test.ts
import { describe, expect, it } from 'vitest';
import type { AppWorkspace } from '../api/types';
import { mergeWorkspaces, type MergeWorkspacesInput } from './mergeWorkspaces';
import { workspaceRootKey } from './rootKey';

function ws(root: string, extra: Partial<AppWorkspace> = {}): AppWorkspace {
return { id: `wd_${root}`, root, name: root, sessionCount: 0, ...extra };
}

function input(overrides: Partial<MergeWorkspacesInput>): MergeWorkspacesInput {
return {
workspaces: [],
sessions: [],
hiddenWorkspaceRoots: [],
sessionsHasMoreByWorkspace: {},
...overrides,
};
}

describe('mergeWorkspaces — folded root identity', () => {
it('assigns a session to the registered workspace when only the drive-letter case differs', () => {
const w = ws('C:\\Users\\Foo\\Proj', { id: 'wd_proj' });
const result = mergeWorkspaces(
input({ workspaces: [w], sessions: [{ id: 's1', cwd: 'c:\\Users\\Foo\\Proj' }] }),
);
expect(result).toHaveLength(1); // no derived duplicate group
expect(result[0]!.id).toBe('wd_proj');
expect(result[0]!.root).toBe('C:\\Users\\Foo\\Proj'); // registered spelling kept
expect(result[0]!.sessionCount).toBe(1); // counted under the registered id
});

it('collapses legacy registered duplicates whose roots only differ by case', () => {
const first = ws('C:\\Users\\Foo\\Proj', { id: 'wd_first' });
const second = ws('c:\\Users\\Foo\\Proj', { id: 'wd_second' });
const result = mergeWorkspaces(
input({
workspaces: [first, second],
sessions: [
{ id: 's1', cwd: 'C:\\Users\\Foo\\Proj' },
{ id: 's2', cwd: 'c:\\Users\\Foo\\Proj' },
],
}),
);
expect(result).toHaveLength(1);
expect(result[0]!.id).toBe('wd_first'); // daemon order: first entry wins
expect(result[0]!.root).toBe('C:\\Users\\Foo\\Proj');
expect(result[0]!.sessionCount).toBe(2); // both cwd variants assigned to it
});

it('merges slash variants of the same Windows path', () => {
const w = ws('C:/Users/Foo/Proj', { id: 'wd_proj' });
const result = mergeWorkspaces(
input({ workspaces: [w], sessions: [{ id: 's1', cwd: 'C:\\Users\\Foo\\Proj' }] }),
);
expect(result).toHaveLength(1);
expect(result[0]!.id).toBe('wd_proj');
expect(result[0]!.root).toBe('C:/Users/Foo/Proj');
expect(result[0]!.sessionCount).toBe(1);
});

it('hides Windows-shaped roots case-insensitively', () => {
const w = ws('C:\\Users\\Foo\\Proj', { id: 'wd_proj' });
const result = mergeWorkspaces(
input({
workspaces: [w],
sessions: [{ id: 's1', cwd: 'c:\\Users\\Foo\\Proj' }],
hiddenWorkspaceRoots: ['c:\\users\\foo\\proj'],
}),
);
expect(result).toHaveLength(0); // one casing removed, all spellings hidden
});

it('hides POSIX roots only by exact directory (trailing slash tolerated)', () => {
const hidden = mergeWorkspaces(
input({ workspaces: [ws('/home/Foo')], hiddenWorkspaceRoots: ['/home/Foo/'] }),
);
expect(hidden).toHaveLength(0);
const kept = mergeWorkspaces(
input({ workspaces: [ws('/home/Foo')], hiddenWorkspaceRoots: ['/home/foo'] }),
);
expect(kept).toHaveLength(1);
});

it('keeps POSIX paths case-sensitive', () => {
const result = mergeWorkspaces(
input({ workspaces: [ws('/home/Foo', { id: 'wd_a' }), ws('/home/foo', { id: 'wd_b' })] }),
);
expect(result.map((w) => w.root)).toEqual(['/home/Foo', '/home/foo']);
});

it('keeps case-variant derived POSIX cwds as separate groups', () => {
const result = mergeWorkspaces(
input({
sessions: [
{ id: 's1', cwd: '/home/Foo' },
{ id: 's2', cwd: '/home/foo' },
],
}),
);
expect(result).toHaveLength(2);
});

it('merges derived groups whose session cwds differ only by case', () => {
const result = mergeWorkspaces(
input({
sessions: [
{ id: 's1', cwd: 'C:\\Users\\Foo\\Proj' },
{ id: 's2', cwd: 'c:\\Users\\Foo\\Proj' },
],
}),
);
expect(result).toHaveLength(1);
expect(result[0]!.root).toBe('C:\\Users\\Foo\\Proj'); // first-seen cwd kept
});

it('orders real workspaces in daemon order and derived ones by display root', () => {
const result = mergeWorkspaces(
input({
workspaces: [ws('/home/x/bbb'), ws('/home/x/aaa')],
sessions: [
{ id: 's1', cwd: '/home/x/ccc' },
{ id: 's2', cwd: '/home/x/000' },
],
}),
);
expect(result.map((w) => w.root)).toEqual([
'/home/x/bbb',
'/home/x/aaa',
'/home/x/000',
'/home/x/ccc',
]);
});
});

describe('workspaceRootKey', () => {
it('folds drive-letter casing', () => {
expect(workspaceRootKey('C:\\Users\\Foo')).toBe(workspaceRootKey('c:\\Users\\Foo'));
expect(workspaceRootKey('C:\\Users\\Foo')).toBe('c:/users/foo');
});

it('folds drive roots before separator stripping can mask the shape', () => {
// `C:\` would strip to `C:` and stop reading as Windows-shaped.
expect(workspaceRootKey('C:\\')).toBe('c:');
expect(workspaceRootKey('C:\\')).toBe(workspaceRootKey('c:\\'));
expect(workspaceRootKey('C:\\')).toBe(workspaceRootKey('c:/'));
});

it('folds UNC paths', () => {
expect(workspaceRootKey('\\\\HOST\\Share\\Dir')).toBe('//host/share/dir');
expect(workspaceRootKey('\\\\HOST\\Share\\Dir')).toBe(workspaceRootKey('//host/share/dir'));
});

it('normalizes slashes and strips trailing separators', () => {
expect(workspaceRootKey('C:\\Users\\Foo\\')).toBe('c:/users/foo');
expect(workspaceRootKey('C:/Users/Foo/')).toBe('c:/users/foo');
expect(workspaceRootKey('/home/Foo/')).toBe('/home/Foo');
});

it('never folds POSIX paths', () => {
expect(workspaceRootKey('/home/Foo')).toBe('/home/Foo');
expect(workspaceRootKey('/home/Foo')).not.toBe(workspaceRootKey('/home/foo'));
});
});
70 changes: 42 additions & 28 deletions apps/kimi-web/src/lib/mergeWorkspaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,18 @@

import type { AppSession, AppWorkspace } from '../api/types';
import { basename } from './pathBasename';
import { workspaceRootKey } from './rootKey';

/** The workspace id a session belongs to: prefer the registered workspace whose
* root matches the session cwd; otherwise the daemon-provided workspaceId;
* otherwise the cwd itself (derived/fallback mode). */
* otherwise the cwd itself (derived/fallback mode). Roots compare by folded
* identity key, never by exact string (Windows casing/slash variants). */
function workspaceIdForSession(
workspaces: AppWorkspace[],
s: { workspaceId?: string; cwd: string },
): string {
return workspaces.find((w) => w.root === s.cwd)?.id ?? s.workspaceId ?? s.cwd;
const cwdKey = workspaceRootKey(s.cwd);
return workspaces.find((w) => workspaceRootKey(w.root) === cwdKey)?.id ?? s.workspaceId ?? s.cwd;
}

export interface MergeWorkspacesInput {
Expand Down Expand Up @@ -42,25 +45,30 @@ export function mergeWorkspaces(input: MergeWorkspacesInput): AppWorkspace[] {
sessionsHasMoreByWorkspace,
} = input;

const hidden = new Set(hiddenWorkspaceRoots);
const byRoot = new Map<string, AppWorkspace>();
// Real workspaces win on root (unless the user removed them from the sidebar).
// Keep the FIRST entry per root: the daemon orders by last_opened_at desc, so
// the most recently opened (typically the canonical re-add) comes first. This
// must match `workspaceIdForSession` / the sidebar's first-match session
// assignment — if byRoot kept a different id than sessions are counted and
// grouped under, the only rendered workspace would look empty.
// "Same root?" is always decided by the folded key; the first-seen original
// string is kept for display.
const hidden = new Set(hiddenWorkspaceRoots.map(workspaceRootKey));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear folded hidden roots when re-adding workspaces

When a user removes C:\Foo and later adds the same Windows directory as c:\foo or with different slashes, the stored hidden root is not cleared because upsertWorkspacePreserveOrder still removes hidden entries by exact string. This new folded hidden set then keeps hiding the re-added workspace, so the add flow can succeed while the group remains absent until localStorage is cleared. Clear hidden entries using the same workspaceRootKey comparison on re-add.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — the hide/unhide sides were asymmetric. upsertWorkspacePreserveOrder now clears hidden entries by the same folded workspaceRootKey comparison (in useWorkspaceState.ts), so re-adding an alias spelling un-hides the workspace. Fixed in 7d940b9 with regression tests (Windows-fold unhide, POSIX case-distinct stays hidden).

const byRoot = new Map<string, AppWorkspace>(); // root key -> workspace
// Real workspaces win on root key (unless the user removed them from the
// sidebar). Keep the FIRST entry per key: the daemon orders by
// last_opened_at desc, so the most recently opened (typically the canonical
// re-add) comes first. This must match `workspaceIdForSession` / the
// sidebar's first-match session assignment — if byRoot kept a different id
// than sessions are counted and grouped under, the only rendered workspace
// would look empty. The entry keeps its ORIGINAL `root` string for display.
for (const w of workspaces) {
if (hidden.has(w.root)) continue;
if (!byRoot.has(w.root)) byRoot.set(w.root, { ...w });
const key = workspaceRootKey(w.root);
if (hidden.has(key)) continue;
if (!byRoot.has(key)) byRoot.set(key, { ...w });
}
// Derive from sessions for any cwd without a real workspace.
for (const s of sessions) {
const root = s.cwd;
if (!root) continue;
if (hidden.has(root)) continue; // removed from the sidebar — keep it hidden
if (!byRoot.has(root)) {
byRoot.set(root, {
const key = workspaceRootKey(root);
if (hidden.has(key)) continue; // removed from the sidebar — keep it hidden
if (!byRoot.has(key)) {
byRoot.set(key, {
// Use the session's REAL daemon workspace_id (wd_<slug>_<hash>) so
// createSession({ workspaceId }) is accepted; fall back to cwd only
// when the daemon hasn't tagged the session yet.
Expand All @@ -79,22 +87,28 @@ export function mergeWorkspaces(input: MergeWorkspacesInput): AppWorkspace[] {
}

// Order: real workspaces in listWorkspaces order, then derived workspaces
// sorted by root path so the order is stable (not tied to session activity).
// Hidden roots must be excluded here too — `byRoot` skips them, so a hidden
// real workspace would otherwise make `byRoot.get(root)` return undefined.
// sorted by display root so the order is stable (not tied to session
// activity). Both lists hold root KEYS. Hidden roots must be excluded here
// too — `byRoot` skips them, so a hidden real workspace would otherwise
// make `byRoot.get(key)` return undefined.
//
// Dedup by root: the registry can legitimately hold two entries for the same
// folder (e.g. a legacy id from an older encodeWorkDirKey plus the current
// one). `byRoot` already collapses them, but a duplicated root in the
// ordering list would render the same workspace twice — and because both
// copies share an id, selecting one would highlight both.
const realRoots = [...new Set(workspaces.filter((w) => !hidden.has(w.root)).map((w) => w.root))];
const derivedRoots = [...byRoot.keys()].filter((r) => !realRoots.includes(r));
derivedRoots.sort((a, b) => a.localeCompare(b));
// Dedup by root key: the registry can legitimately hold two entries for the
// same folder (e.g. a legacy id from an older encodeWorkDirKey plus the
// current one, or casing variants of the same Windows path). `byRoot`
// already collapses them, but a duplicated key in the ordering list would
// render the same workspace twice — and because both copies share an id,
// selecting one would highlight both.
const realKeys: string[] = [];
for (const w of workspaces) {
const key = workspaceRootKey(w.root);
if (!hidden.has(key) && !realKeys.includes(key)) realKeys.push(key);
}
const derivedKeys = [...byRoot.keys()].filter((k) => !realKeys.includes(k));
derivedKeys.sort((a, b) => byRoot.get(a)!.root.localeCompare(byRoot.get(b)!.root));

const result: AppWorkspace[] = [];
for (const root of [...realRoots, ...derivedRoots]) {
const w = byRoot.get(root)!;
for (const key of [...realKeys, ...derivedKeys]) {
const w = byRoot.get(key)!;
// When a workspace's sessions are fully loaded (hasMore === false), the
// local count is exact — prefer it so archiving the last session drops the
// count to 0 immediately. While pages remain, the local count is only a
Expand Down
26 changes: 26 additions & 0 deletions apps/kimi-web/src/lib/rootKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// apps/kimi-web/src/lib/rootKey.ts

// Windows-shaped: drive-letter (C:\, C:/) or UNC (\\host\share, //host/share).
// Shape-based detection (not any platform check): the daemon may run on
// Windows while the browser runs anywhere, and tests must fold the same way
// on every host.
const WIN_SHAPED = /^(?:[A-Za-z]:[\\/]|\\\\|\/\/)/;

/**
* Identity key for "same workspace directory?" comparisons: slash-normalize,
* strip trailing separators, case-fold Windows-shaped paths (NTFS lookups are
* case-insensitive by default). Display strings are never rewritten — this is
* for comparison only. Mirrors the server-side copies (agent-core
* session/store/workdir-key.ts, agent-core-v2 _base/utils/workdir-slug.ts);
* keep the three in sync. Per-directory case sensitivity / WSL paths are a
* documented non-goal; POSIX paths never fold.
*/
export function workspaceRootKey(root: string): string {
const slashed = root.replaceAll('\\', '/');
// Test the shape BEFORE stripping trailing separators: a drive root
// (`C:\`) loses its only separator to the strip (`C:`) and would no
// longer read as Windows-shaped, escaping the case-fold.
const shaped = WIN_SHAPED.test(slashed);
const normalized = slashed.replace(/\/+$/, '');
return shaped ? normalized.toLowerCase() : normalized;
}
Loading
Loading