From b048cf44f77eac021af91d1904d76a583d05f108 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:52:58 +0800 Subject: [PATCH] fix(tui): use canonical session handles (#6455) --- tui/src/client/api.ts | 45 +++++++--------- tui/src/client/client.test.ts | 85 ++++++++++++++++++++++++++++-- tui/src/client/types.ts | 3 ++ tui/src/menus/mention-menu.test.ts | 36 ++++++++++--- tui/src/menus/session-menu.test.ts | 13 ++++- tui/src/menus/session-menu.ts | 2 + 6 files changed, 146 insertions(+), 38 deletions(-) diff --git a/tui/src/client/api.ts b/tui/src/client/api.ts index 31241d4d0..f0c8f1b37 100644 --- a/tui/src/client/api.ts +++ b/tui/src/client/api.ts @@ -25,6 +25,7 @@ import { } from "./validation" const SKILL_REFERENCE_NAME = /^[A-Za-z0-9_-]+$/u +const SESSION_HANDLE_NAME = /^[a-z]{4,16}$/u const SLASH_COMMAND_LIFECYCLES = new Set([ "side_channel", "finalize_active_turn", @@ -415,8 +416,13 @@ export async function fetchSessions( const chatId = value.key.slice("websocket:".length) if (!chatId) return [] const titleOverride = titles[value.key] + const handle = value.handle return [{ + key: value.key, chatId, + ...(isRecord(handle) && typeof handle.id === "string" && handle.id + && typeof handle.name === "string" && SESSION_HANDLE_NAME.test(handle.name) + ? { handle: { id: handle.id, name: handle.name } } : {}), title: typeof titleOverride === "string" ? titleOverride : typeof value.title === "string" ? value.title : "", @@ -437,16 +443,6 @@ export async function fetchSessions( }) } -function sessionMentionName(session: SessionSummary): string { - const label = (session.title || session.preview || "session") - .normalize("NFKC") - .replace(/\s+/gu, "-") - .replace(/[^\p{L}\p{N}_-]+/gu, "") - .replace(/-+/gu, "-") - .replace(/^-|-$/gu, "") - return Array.from(label || "session").slice(0, 40).join("") -} - /** Installed capabilities and saved chats share one mention namespace. */ export async function fetchMentionCandidates( apiUrl: string, @@ -464,7 +460,18 @@ export async function fetchMentionCandidates( ).catch(() => null), fetchApi(apiUrl, apiToken, "/api/settings/mcp-presets", reauthenticate).catch(() => null), ]) - const used = new Set() + const sessionCandidates = sessions.flatMap((session) => session.handle ? [{ + kind: "session", + name: session.handle.name, + displayName: sessionLabelForMention(session), + description: session.preview || "Saved session", + session: { + ...session.handle, + session_key: session.key, + title: session.title || undefined, + }, + }] : []) + const used = new Set(sessionCandidates.map((candidate) => candidate.name.toLocaleLowerCase())) const uniqueName = (raw: string) => { const base = raw || "session" let name = base @@ -507,21 +514,7 @@ export async function fetchMentionCandidates( }) } } - for (const session of sessions) { - const name = uniqueName(sessionMentionName(session)) - candidates.push({ - kind: "session", - name, - displayName: sessionLabelForMention(session), - description: session.preview || "Saved session", - session: { - name, - session_key: `websocket:${session.chatId}`, - title: session.title || undefined, - }, - }) - } - return candidates + return [...candidates, ...sessionCandidates] } function sessionLabelForMention(session: SessionSummary): string { diff --git a/tui/src/client/client.test.ts b/tui/src/client/client.test.ts index d5baa0219..a9ffe1a99 100644 --- a/tui/src/client/client.test.ts +++ b/tui/src/client/client.test.ts @@ -1319,6 +1319,7 @@ describe("gateway protocol", () => { sessions: [ { key: "websocket:chat-1", + handle: { id: "handle_plan", name: "luma" }, title: "Release plan", preview: "Prepare the release", created_at: "2026-08-12T10:00:00Z", @@ -1334,6 +1335,8 @@ describe("gateway protocol", () => { try { expect(await fetchSessions("http://nanobot.test", "secret")).toEqual([{ + key: "websocket:chat-1", + handle: { id: "handle_plan", name: "luma" }, chatId: "chat-1", title: "Pinned release", preview: "Prepare the release", @@ -1371,7 +1374,12 @@ describe("gateway protocol", () => { } if (url.includes("sidebar-state")) return Promise.resolve(new Response("{}")) return Promise.resolve(new Response(JSON.stringify({ - sessions: [{ key: "websocket:plan", title: "Release plan", preview: "Ship it" }], + sessions: [{ + key: "websocket:plan", + handle: { id: "handle_plan", name: "luma" }, + title: "Release plan", + preview: "Ship it", + }], }))) }) as typeof fetch @@ -1391,11 +1399,12 @@ describe("gateway protocol", () => { }, { kind: "session", - name: "Release-plan", + name: "luma", displayName: "Release plan", description: "Ship it", session: { - name: "Release-plan", + id: "handle_plan", + name: "luma", session_key: "websocket:plan", title: "Release plan", }, @@ -1405,6 +1414,76 @@ describe("gateway protocol", () => { globalThis.fetch = original } }) + + test("reserves canonical session names across tools, renames, and list reordering", async () => { + const original = globalThis.fetch + let renamed = false + const sessions = [ + { key: "websocket:plan", handle: { id: "handle_plan", name: "luma" }, title: "Same title" }, + { key: "websocket:notes", handle: { id: "handle_notes", name: "bime" }, title: "Same title" }, + ] + globalThis.fetch = ((input: string | URL | Request) => { + const url = String(input) + if (url.includes("cli-apps")) return Promise.resolve(Response.json({ + apps: [{ name: "luma", installed: true }], + })) + if (url.includes("mcp-presets")) return Promise.resolve(Response.json({ + presets: [{ name: "LUMA", installed: true, configured: true }], + })) + if (url.includes("sidebar-state")) return Promise.resolve(Response.json({ + title_overrides: renamed ? { "websocket:plan": "Renamed chat" } : {}, + })) + return Promise.resolve(Response.json({ sessions: renamed ? [...sessions].reverse() : sessions })) + }) as typeof fetch + + try { + const before = await fetchMentionCandidates("http://nanobot.test", "secret") + expect(before.map(({ kind, name, targetName }) => ({ kind, name, targetName }))).toEqual([ + { kind: "cli", name: "luma-2", targetName: "luma" }, + { kind: "mcp", name: "LUMA-3", targetName: "LUMA" }, + { kind: "session", name: "luma", targetName: undefined }, + { kind: "session", name: "bime", targetName: undefined }, + ]) + expect(before.filter((item) => item.kind === "session").map((item) => item.displayName)) + .toEqual(["Same title", "Same title"]) + + renamed = true + const after = await fetchMentionCandidates("http://nanobot.test", "secret") + expect(after.filter((item) => item.kind === "session").map((item) => item.session)).toEqual([ + { id: "handle_notes", name: "bime", session_key: "websocket:notes", title: "Same title" }, + { id: "handle_plan", name: "luma", session_key: "websocket:plan", title: "Renamed chat" }, + ]) + expect(after.find((item) => item.name === "luma")?.displayName).toBe("Renamed chat") + expect(after.slice(0, 2)).toEqual(before.slice(0, 2)) + } finally { + globalThis.fetch = original + } + }) + + test("keeps sessions navigable without inventing handles for missing or malformed API identities", async () => { + const original = globalThis.fetch + globalThis.fetch = ((input: string | URL | Request) => Promise.resolve(Response.json( + String(input).endsWith("/api/sessions") ? { + sessions: [ + { key: "websocket:missing", title: "Missing handle" }, + { key: "websocket:invalid", handle: { id: 42, name: "luma" }, title: "Invalid handle" }, + { key: "websocket:alias", handle: { id: "handle_alias", name: "Release-plan" }, title: "Old alias" }, + ], + } : {}, + ))) as typeof fetch + + try { + const sessions = await fetchSessions("http://nanobot.test", "secret") + expect(sessions.map((session) => [session.key, session.title, session.handle])).toEqual([ + ["websocket:missing", "Missing handle", undefined], + ["websocket:invalid", "Invalid handle", undefined], + ["websocket:alias", "Old alias", undefined], + ]) + expect(await fetchMentionCandidates("http://nanobot.test", "secret")).toEqual([]) + } finally { + globalThis.fetch = original + } + }) }) diff --git a/tui/src/client/types.ts b/tui/src/client/types.ts index b40c592bd..352fd57a3 100644 --- a/tui/src/client/types.ts +++ b/tui/src/client/types.ts @@ -279,6 +279,7 @@ export interface SessionContextSnapshot { } interface SessionMention { + id?: string name: string session_key: string title?: string @@ -324,7 +325,9 @@ export type SlashCommandLifecycle = | "agent_turn_with_args" export interface SessionSummary { + key: string chatId: string + handle?: { id: string; name: string } title: string preview: string createdAt: string | null diff --git a/tui/src/menus/mention-menu.test.ts b/tui/src/menus/mention-menu.test.ts index f4c9c4546..834a5e79d 100644 --- a/tui/src/menus/mention-menu.test.ts +++ b/tui/src/menus/mention-menu.test.ts @@ -8,19 +8,20 @@ const candidates: MentionCandidate[] = [ { kind: "mcp", name: "linear", displayName: "Linear", description: "MCP" }, { kind: "session", - name: "release-plan", + name: "luma", displayName: "Release plan", description: "Session", - session: { name: "release-plan", session_key: "websocket:release", title: "Release plan" }, + session: { id: "handle_release", name: "luma", session_key: "websocket:release", title: "Release plan" }, }, ] describe("mention projection", () => { test("finds and replaces only the mention under the cursor", () => { - const value = "ask @rel about this" - const query = mentionQuery(value, 8) - expect(query).toEqual({ query: "rel", start: 4, end: 8 }) - expect(insertMention(value, candidates[2]!, query!).value).toBe("ask @release-plan about this") + const value = "ask @lu about this" + const query = mentionQuery(value, 7) + expect(query).toEqual({ query: "lu", start: 4, end: 7 }) + const completed = insertMention(value, candidates[2]!, query!).value + expect(completed).toBe("ask @luma about this") }) test("keeps namespaced completion aliases separate from gateway capability ids", () => { @@ -35,12 +36,31 @@ describe("mention projection", () => { expect(options.mcpPresets).toEqual([{ name: "github" }]) }) + test("does not mix a canonical session with colliding tool completion aliases", () => { + const colliding: MentionCandidate[] = [ + candidates[2]!, + { kind: "cli", name: "luma-2", targetName: "luma", displayName: "Luma CLI", description: "CLI" }, + { kind: "mcp", name: "luma-3", targetName: "luma", displayName: "Luma MCP", description: "MCP" }, + ] + expect(mentionOptions("ask @LUMA", colliding)).toEqual({ + cliApps: [], + mcpPresets: [], + sessionMentions: [candidates[2]!.session!], + }) + expect(mentionOptions("use @luma-2 and @luma-3", colliding)).toEqual({ + cliApps: [{ name: "luma" }], + mcpPresets: [{ name: "luma" }], + sessionMentions: [], + }) + }) + test("maps visible mentions onto the gateway metadata lanes", () => { - expect(mentionOptions("Use @github with @linear and @release-plan", candidates)).toEqual({ + expect(mentionOptions("Use @github with @linear and @luma", candidates)).toEqual({ cliApps: [{ name: "github" }], mcpPresets: [{ name: "linear" }], sessionMentions: [{ - name: "release-plan", + id: "handle_release", + name: "luma", session_key: "websocket:release", title: "Release plan", }], diff --git a/tui/src/menus/session-menu.test.ts b/tui/src/menus/session-menu.test.ts index ac0b57d9a..434cc5171 100644 --- a/tui/src/menus/session-menu.test.ts +++ b/tui/src/menus/session-menu.test.ts @@ -6,7 +6,9 @@ import type { SessionSummary } from "../client" const sessions: SessionSummary[] = [ { + key: "websocket:one", chatId: "one", + handle: { id: "handle_one", name: "luma" }, title: "API migration", preview: "Move authentication to the new client", createdAt: "2026-08-12T10:00:00Z", @@ -17,7 +19,9 @@ const sessions: SessionSummary[] = [ archived: false, }, { + key: "websocket:two", chatId: "two", + handle: { id: "handle_two", name: "bime" }, title: "Release checklist", preview: "Prepare the stable release", createdAt: "2026-08-11T10:00:00Z", @@ -55,7 +59,7 @@ describe("SessionMenu", () => { menu.open(sessions, "one", 6, "Codex") await setup.renderOnce() - expect(setup.captureCharFrame()).toContain("› ● API migration") + expect(setup.captureCharFrame()).toContain("› ● API migration @luma") expect(setup.captureCharFrame()).not.toContain("Move authentication") expect(setup.captureCharFrame()).not.toContain("Codex") expect(menu.choose()?.chatId).toBe("one") @@ -64,6 +68,13 @@ describe("SessionMenu", () => { await setup.renderOnce() expect(setup.captureCharFrame()).toContain("⚠ Release checklist") expect(menu.choose()?.chatId).toBe("two") + + for (const query of ["luma", "@luma"]) { + menu.update(query, 6) + await setup.renderOnce() + expect(menu.choose()?.key).toBe("websocket:one") + expect(setup.captureCharFrame()).toContain("API migration @luma") + } }) test("keeps generated multi-line titles on one terminal row", () => { diff --git a/tui/src/menus/session-menu.ts b/tui/src/menus/session-menu.ts index 573f86540..7b48697e1 100644 --- a/tui/src/menus/session-menu.ts +++ b/tui/src/menus/session-menu.ts @@ -49,6 +49,7 @@ export class SessionMenu { key: (session) => session.chatId, searchText: (session) => [ sessionLabel(session), + session.handle ? `@${session.handle.name}` : "", session.modelPreset || "", session.preview, session.chatId, @@ -60,6 +61,7 @@ export class SessionMenu { render: (session, selected) => { const age = updatedLabel(session.updatedAt) const detail = [ + session.handle ? `@${session.handle.name}` : "", this.showWorkspaces ? this.workspaceLabel(session) : "", this.modelOverride(session), ]