File size: 20,990 Bytes
5710dd0 | 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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 | /**
* Left sidebar — a single-column workspace → session tree backed by the v2
* list's grouped projection (`GET /api/v2/sessions?view=by_workspace`, see
* `src/sessions/api.ts`): one request returns every workspace with a matching
* session, each carrying its first `group.page_size` sessions under the
* requested sort plus the workspace's full matching total. Preset views
* (`src/sessions/views.ts`) map onto the endpoint's status / archived / git
* query conditions; the active view, collapsed workspaces, and the panel
* width persist to localStorage. Group pagination is the endpoint's opaque
* cursor (Load more), with a slow poll on top; a workspace whose total
* outruns the served slice expands inline into the flat per-workspace
* listing. Live activity frames (`useSessionActivities`) override the REST
* status badge. Session creation still goes through the v1 REST endpoint.
*/
import { IAgentProfileService } from '@moonshot-ai/agent-core-v2/agent/profile/profile';
import { IConfigService } from '@moonshot-ai/agent-core-v2/app/config/config';
import { ISessionManager } from '@moonshot-ai/agent-core-v2/app/sessionManager/sessionManager';
import {
IWorkspaceService,
type Workspace,
} from '@moonshot-ai/agent-core-v2/app/workspace/workspace';
import { IModelCatalog } from '@moonshot-ai/agent-core-v2/llm-adapter/model/catalog';
import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query';
import { useMemo, useState } from 'react';
import type { SessionWorkFacts } from '../activity/store';
import { useSessionActivities } from '../activity/useSessionActivity';
import type { InspectClient } from '../channel';
import { useConnection } from '../connection';
import {
fetchV2SessionGroups,
fetchV2SessionsPage,
type V2ActivityStatus,
type V2Session,
type V2SessionGroup,
type V2SessionSort,
} from '../sessions/api';
import { SESSION_VIEWS, sessionViewById, type SessionView } from '../sessions/views';
import { Badge, ErrorLine, relTime } from '../ui';
const STORAGE_KEY = 'kimi-inspect.session-table';
const DEFAULT_WIDTH = 320;
const MIN_WIDTH = 240;
const MAX_WIDTH = 640;
const GROUP_PAGE_SIZE = 50;
// ---------------------------------------------------------------------------
// Persisted panel prefs
// ---------------------------------------------------------------------------
interface PanelPrefs {
readonly view?: string;
/** Collapsed workspace ids; absent = everything expanded. */
readonly collapsed?: readonly string[];
readonly width?: number;
}
function readPrefs(): PanelPrefs {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw !== null) return JSON.parse(raw) as PanelPrefs;
} catch {
// corrupt storage — fall through to defaults
}
return {};
}
function writePrefs(prefs: PanelPrefs): void {
localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs));
}
// ---------------------------------------------------------------------------
// Live status override (mirrors the server's mapActivityStatus)
// ---------------------------------------------------------------------------
function liveStatus(facts: SessionWorkFacts | undefined): V2ActivityStatus | undefined {
if (facts === undefined) return undefined;
if (facts.pendingInteraction === 'approval') return 'approval';
if (facts.pendingInteraction === 'question') return 'question';
if (facts.busy || facts.mainTurnActive) return 'running';
if (facts.lastTurnReason === 'failed') return 'failed';
return 'idle';
}
const STATUS_TONES: Record<V2ActivityStatus, 'green' | 'amber' | 'sky' | 'red' | 'neutral'> = {
running: 'green',
approval: 'amber',
question: 'sky',
failed: 'red',
idle: 'neutral',
};
const SORTS: readonly { readonly id: V2SessionSort; readonly label: string }[] = [
{ id: 'meta.updated_at_desc', label: 'Updated ↓' },
{ id: 'meta.updated_at_asc', label: 'Updated ↑' },
{ id: 'meta.created_at_desc', label: 'Created ↓' },
];
/**
* Default model for a fresh session: the configured global `defaultModel`
* first (the same fallback the profile bind uses), then the first connected
* provider's `default_model`. `undefined` means the server has nothing to
* offer — the session stays model-less and the chat surfaces
* `model.not_configured` as before.
*/
async function resolveDefaultModel(klient: InspectClient): Promise<string | undefined> {
const configured: unknown = await klient.core(IConfigService).get('defaultModel');
if (typeof configured === 'string' && configured !== '') return configured;
const providers = await klient.core(IModelCatalog).listProviders();
const withDefault = providers.filter((p) => p.default_model !== undefined);
return (withDefault.find((p) => p.status === 'connected') ?? withDefault[0])?.default_model;
}
// ---------------------------------------------------------------------------
// Sidebar
// ---------------------------------------------------------------------------
export function Sidebar({
activeSessionId,
onSelectSession,
}: {
activeSessionId: string | null;
onSelectSession: (sessionId: string) => void;
}) {
const { klient, baseUrl, config } = useConnection();
const queryClient = useQueryClient();
const activities = useSessionActivities();
const [prefs, setPrefs] = useState<PanelPrefs>(readPrefs);
const view = sessionViewById(prefs.view);
const [sort, setSort] = useState<V2SessionSort>('meta.updated_at_desc');
const width = prefs.width ?? DEFAULT_WIDTH;
const collapsed = useMemo(() => new Set(prefs.collapsed ?? []), [prefs.collapsed]);
const updatePrefs = (patch: PanelPrefs) => {
setPrefs((prev) => {
const next: PanelPrefs = { ...prev, ...patch };
writePrefs(next);
return next;
});
};
const toggleCollapsed = (workspaceId: string) => {
const next = new Set(collapsed);
if (next.has(workspaceId)) next.delete(workspaceId);
else next.add(workspaceId);
updatePrefs({ collapsed: [...next] });
};
const token = config.token.trim();
const authToken = token === '' ? undefined : token;
const workspaces = useQuery({
queryKey: ['workspaces'],
queryFn: () => klient.core(IWorkspaceService).list(),
refetchInterval: 15_000,
});
const workspaceNames = useMemo(
() => new Map((workspaces.data ?? []).map((ws) => [ws.id, ws.name] as const)),
[workspaces.data],
);
const groups = useInfiniteQuery({
queryKey: ['v2-sessions', 'tree', view.id, sort],
queryFn: ({ pageParam }) =>
fetchV2SessionGroups({
baseUrl,
token: authToken,
statuses: view.statuses,
archived: view.archived,
includeGit: view.includeGit,
sort,
pageSize: 50,
groupPageSize: GROUP_PAGE_SIZE,
pageToken: pageParam,
}),
initialPageParam: undefined as string | undefined,
getNextPageParam: (last) => last.nextPageToken,
refetchInterval: 15_000,
});
const groupList = useMemo(
() => groups.data?.pages.flatMap((page) => page.groups) ?? [],
[groups.data],
);
const createSession = async (ws: Workspace | null) => {
// With a workspace, the server derives workDir from workspace.root, so no cwd is needed.
let body: string;
if (ws !== null) {
body = JSON.stringify({ workspace_id: ws.id });
} else {
const cwd = window.prompt('Working directory for the new session:', '');
if (cwd === null || cwd.trim() === '') return;
body = JSON.stringify({ metadata: { cwd: cwd.trim() } });
}
const headers: Record<string, string> = { 'content-type': 'application/json' };
if (token !== '') headers['authorization'] = `Bearer ${token}`;
const res = await fetch(`${baseUrl}/api/v1/sessions`, {
method: 'POST',
headers,
body,
});
const envelope = (await res.json()) as { code: number; msg: string; data: { id: string } };
if (envelope.code !== 0) {
window.alert(`create session failed: ${envelope.msg}`);
return;
}
const sessionId = envelope.data.id;
// The REST create route ignores agent_config, so bind the default model
// over the channel — the same resume + setModel path the Model Catalog's
// "+ Session" button uses. Best-effort: a failure leaves the session
// model-less instead of blocking the creation flow.
try {
const model = await resolveDefaultModel(klient);
if (model !== undefined) {
await klient.core(ISessionManager).resume(sessionId);
await klient.session(sessionId).agent('main').service(IAgentProfileService).setModel(model);
}
} catch (error) {
console.warn('failed to set the default model on the new session', error);
}
await queryClient.invalidateQueries({ queryKey: ['v2-sessions'] });
onSelectSession(sessionId);
};
const cycleSort = () => {
const index = SORTS.findIndex((s) => s.id === sort);
setSort(SORTS[(index + 1) % SORTS.length]!.id);
};
const startResize = (e: React.MouseEvent) => {
e.preventDefault();
const startX = e.clientX;
const startWidth = width;
const onMove = (ev: MouseEvent) => {
const next = Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, startWidth + ev.clientX - startX));
setPrefs((prev) => ({ ...prev, width: next }));
};
const onUp = (ev: MouseEvent) => {
window.removeEventListener('mousemove', onMove);
window.removeEventListener('mouseup', onUp);
const next = Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, startWidth + ev.clientX - startX));
updatePrefs({ width: next });
};
window.addEventListener('mousemove', onMove);
window.addEventListener('mouseup', onUp);
};
return (
<div
className="relative flex h-full shrink-0 flex-col border-r border-neutral-800"
style={{ width }}
>
{/* View tabs */}
<div className="flex items-center gap-1 overflow-x-auto border-b border-neutral-800 px-2 py-1.5">
{SESSION_VIEWS.map((v) => (
<button
key={v.id}
className={`shrink-0 rounded px-2 py-0.5 text-[11px] ${
v.id === view.id
? 'bg-neutral-800 font-medium text-neutral-100'
: 'text-neutral-500 hover:text-neutral-300'
}`}
onClick={() => updatePrefs({ view: v.id })}
>
{v.label}
</button>
))}
</div>
{/* Toolbar: new session + sort */}
<div className="flex items-center justify-between border-b border-neutral-800 px-2 py-1">
<NewSessionMenu workspaces={workspaces.data ?? []} onCreate={createSession} />
<button
className="rounded border border-neutral-700 px-2 py-0.5 text-[11px] text-neutral-400 hover:bg-neutral-800"
title="Click to change sort"
onClick={cycleSort}
>
{SORTS.find((s) => s.id === sort)?.label}
</button>
</div>
{/* Tree body */}
<div className="flex-1 overflow-y-auto">
{groups.isError ? <ErrorLine error={groups.error} /> : null}
{groupList.map((group) => (
<WorkspaceNode
key={group.workspace.id}
group={group}
view={view}
sort={sort}
collapsed={collapsed.has(group.workspace.id)}
onToggleCollapsed={() => toggleCollapsed(group.workspace.id)}
workspaceNames={workspaceNames}
activeSessionId={activeSessionId}
activityOf={(id) => activities.get(id)}
onSelect={onSelectSession}
baseUrl={baseUrl}
token={authToken}
/>
))}
{groups.isLoading ? (
<div className="px-3 py-2 text-[11px] text-neutral-600">loading…</div>
) : null}
{!groups.isLoading && groupList.length === 0 && !groups.isError ? (
<div className="px-3 py-2 text-[11px] text-neutral-600">no sessions</div>
) : null}
{groups.hasNextPage ? (
<button
className="w-full border-t border-neutral-800 px-3 py-1.5 text-[11px] text-sky-500 hover:bg-neutral-800/60 hover:text-sky-400"
disabled={groups.isFetchingNextPage}
onClick={() => void groups.fetchNextPage()}
>
{groups.isFetchingNextPage ? 'loading…' : 'Load more workspaces'}
</button>
) : null}
</div>
{/* Resize handle */}
<div
className="absolute top-0 right-0 h-full w-1 cursor-col-resize hover:bg-sky-700/50"
onMouseDown={startResize}
/>
</div>
);
}
// ---------------------------------------------------------------------------
// Tree nodes
// ---------------------------------------------------------------------------
function WorkspaceNode({
group,
view,
sort,
collapsed,
onToggleCollapsed,
workspaceNames,
activeSessionId,
activityOf,
onSelect,
baseUrl,
token,
}: {
group: V2SessionGroup;
view: SessionView;
sort: V2SessionSort;
collapsed: boolean;
onToggleCollapsed: () => void;
workspaceNames: ReadonlyMap<string, string>;
activeSessionId: string | null;
activityOf: (sessionId: string) => SessionWorkFacts | undefined;
onSelect: (sessionId: string) => void;
baseUrl: string;
token?: string | undefined;
}) {
const [showAll, setShowAll] = useState(false);
const hasMore = group.total > group.sessions.length;
return (
<div>
<div
className="flex cursor-pointer items-center gap-1.5 border-b border-neutral-800 px-2 py-1.5 select-none hover:bg-neutral-800/60"
onClick={onToggleCollapsed}
title={group.workspace.cwd ?? group.workspace.id}
>
<span className="w-3 shrink-0 text-center text-[9px] text-neutral-600">
{collapsed ? '▸' : '▾'}
</span>
<span className="min-w-0 flex-1 truncate text-[11px] font-semibold text-neutral-300">
{workspaceNames.get(group.workspace.id) ?? group.workspace.cwd ?? group.workspace.id}
</span>
<span className="shrink-0 text-[10px] text-neutral-600">{group.total}</span>
</div>
{collapsed ? null : (
<>
{showAll ? null : (
<>
{group.sessions.map((s) => (
<SessionNode
key={s.id}
s={s}
active={s.id === activeSessionId}
activity={activityOf(s.id)}
onClick={() => onSelect(s.id)}
/>
))}
{hasMore ? (
<button
className="w-full border-b border-neutral-800/50 py-1 pl-6 text-left text-[10px] text-sky-500 hover:bg-neutral-800/60 hover:text-sky-400"
onClick={() => setShowAll(true)}
>
Show all {group.total}…
</button>
) : null}
</>
)}
{showAll ? (
<FullGroupList
workspaceId={group.workspace.id}
view={view}
sort={sort}
baseUrl={baseUrl}
token={token}
activeSessionId={activeSessionId}
activityOf={activityOf}
onSelect={onSelect}
/>
) : null}
</>
)}
</div>
);
}
/**
* The flat per-workspace listing behind "Show all" — pages the ungrouped
* projection filtered to this workspace, so sessions beyond the grouped
* slice stay reachable.
*/
function FullGroupList({
workspaceId,
view,
sort,
baseUrl,
token,
activeSessionId,
activityOf,
onSelect,
}: {
workspaceId: string;
view: SessionView;
sort: V2SessionSort;
baseUrl: string;
token?: string | undefined;
activeSessionId: string | null;
activityOf: (sessionId: string) => SessionWorkFacts | undefined;
onSelect: (sessionId: string) => void;
}) {
const sessions = useInfiniteQuery({
queryKey: ['v2-sessions', 'tree-full', workspaceId, view.id, sort],
queryFn: ({ pageParam }) =>
fetchV2SessionsPage({
baseUrl,
token,
workspaceIds: [workspaceId],
statuses: view.statuses,
archived: view.archived,
includeGit: view.includeGit,
sort,
pageSize: 50,
pageToken: pageParam,
}),
initialPageParam: undefined as string | undefined,
getNextPageParam: (last) => last.nextPageToken,
});
const seen = new Set<string>();
const items = (sessions.data?.pages.flatMap((page) => page.items) ?? []).filter((s) => {
if (seen.has(s.id)) return false;
seen.add(s.id);
return true;
});
return (
<div className="bg-neutral-950/40">
{items.map((s) => (
<SessionNode
key={s.id}
s={s}
active={s.id === activeSessionId}
activity={activityOf(s.id)}
onClick={() => onSelect(s.id)}
/>
))}
{sessions.isLoading ? (
<div className="py-1 pl-6 text-[10px] text-neutral-600">loading…</div>
) : null}
{sessions.hasNextPage ? (
<button
className="w-full py-1 pl-6 text-left text-[10px] text-sky-500 hover:bg-neutral-800/60 hover:text-sky-400"
disabled={sessions.isFetchingNextPage}
onClick={() => void sessions.fetchNextPage()}
>
{sessions.isFetchingNextPage ? 'loading…' : 'Load more'}
</button>
) : null}
</div>
);
}
function SessionNode({
s,
active,
activity,
onClick,
}: {
s: V2Session;
active: boolean;
activity?: SessionWorkFacts | undefined;
onClick: () => void;
}) {
const status = liveStatus(activity) ?? s.activity.status;
return (
<div
className={`cursor-pointer border-b border-neutral-800/50 py-1 pr-2 pl-6 hover:bg-neutral-800/60 ${
active ? 'bg-sky-950/60' : ''
}`}
onClick={onClick}
>
<div className="flex items-center gap-1.5">
{status === 'idle' ? null : <Badge tone={STATUS_TONES[status]}>{status}</Badge>}
<span className="min-w-0 flex-1 truncate text-[12px] text-neutral-200">
{s.meta.title ?? s.meta.lastPrompt ?? s.id}
</span>
{s.meta.archived ? <Badge tone="neutral">archived</Badge> : null}
<span className="shrink-0 text-[10px] text-neutral-500">{relTime(s.meta.updatedAt)}</span>
</div>
<div className="flex items-center gap-2 truncate font-mono text-[10px] text-neutral-600">
<span className="truncate">{s.id.slice(0, 12)}</span>
{s.git !== undefined && s.git.branch !== null ? (
<span className="truncate" title={s.git.branch}>
{s.git.branch}
</span>
) : null}
{s.git !== undefined && s.git.pullRequest !== null ? (
<a
className="shrink-0 text-sky-500 hover:text-sky-400"
href={s.git.pullRequest.url}
target="_blank"
rel="noreferrer"
onClick={(e) => e.stopPropagation()}
>
#{s.git.pullRequest.number}
</a>
) : null}
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Toolbar dropdowns
// ---------------------------------------------------------------------------
function useDropdown(): { open: boolean; toggle: () => void; close: () => void } {
const [open, setOpen] = useState(false);
return {
open,
toggle: () => setOpen((v) => !v),
close: () => setOpen(false),
};
}
function NewSessionMenu({
workspaces,
onCreate,
}: {
workspaces: readonly Workspace[];
onCreate: (ws: Workspace | null) => Promise<void>;
}) {
const { open, toggle, close } = useDropdown();
return (
<div className="relative">
<button
className="rounded border border-neutral-700 px-2 py-0.5 text-[11px] text-neutral-300 hover:bg-neutral-800"
onClick={toggle}
>
+ New session
</button>
{open ? (
<>
<div className="fixed inset-0 z-10" onClick={close} />
<div className="absolute left-0 z-20 mt-1 w-64 rounded border border-neutral-700 bg-neutral-900 py-1 shadow-xl">
{workspaces.map((ws) => (
<button
key={ws.id}
className="block w-full truncate px-3 py-1.5 text-left text-[11px] text-neutral-200 hover:bg-neutral-800"
title={ws.root}
onClick={() => {
close();
void onCreate(ws);
}}
>
{ws.name}
</button>
))}
<button
className="block w-full border-t border-neutral-800 px-3 py-1.5 text-left text-[11px] text-neutral-400 hover:bg-neutral-800"
onClick={() => {
close();
void onCreate(null);
}}
>
No workspace (prompt for cwd)…
</button>
</div>
</>
) : null}
</div>
);
}
|