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
11 changes: 9 additions & 2 deletions web/src/components/stream/Composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ import { labelsForPart, visibilityStore } from "../../state/visibility";
import { defaultModel, modelsFrom, showModelChrome } from "../../stream/composerChrome";
import { canSendTurn, cancelAvailability, isComposable, isSendKey } from "../../stream/composerGate";
import { chipsFor, envelopeFor, type ContextChip } from "../../stream/composerContext";
import { sessionPromptStore } from "../../stream/sessionPrompts";
import { holderSessionTitle } from "../../stream/sessionTitle";
import { promptFailurePost, runtimeFaultOf, type RuntimeFault } from "../../stream/runtimeFault";
import type { ContextMember } from "../../api/sessions";
import { Fact } from "../Fact";
Expand Down Expand Up @@ -375,6 +377,9 @@ export function Composer(props: ComposerProps): React.JSX.Element {
// Narrowing for `sendPrompt` below: `sessionId === null` is `no_session`
// and is already refused by `canSendTurn`.
if (sessionId === null) return;
// Remember the opening line before the POST returns so the session tab
// retitles on this frame. History will never echo the prompt back.
sessionPromptStore.remember(sessionId, text);
setCancelNote(null);
// Forget the previous run *before* the POST. Otherwise Cancel is aimed
// at a finished id for the whole window until the first new frame (#99).
Expand Down Expand Up @@ -689,8 +694,10 @@ export function Composer(props: ComposerProps): React.JSX.Element {
{post.reason === "run_in_flight" && typeof post.data["session_id"] === "string" ? (
<p data-run-in-flight-session={post.data["session_id"]}>
{copy.composer.runInFlightHolder(
props.sessionTitle?.(post.data["session_id"]) ??
copy.composer.createOrchestrator,
holderSessionTitle(
post.data["session_id"],
props.sessionTitle?.(post.data["session_id"]),
),
)}
</p>
) : null}
Expand Down
50 changes: 42 additions & 8 deletions web/src/components/stream/SessionTabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,19 @@
//
// The widget is `TabBar`: roving tabindex, arrows, Home/End, Tab leaves the
// list. The transcript is the `tabpanel` this list controls (#68).
//
// The visible label is the first prompt this page sent, the bound part, or
// "New session". The UUID stays on `title` / `data-session-id`. History omits
// prompts, so the first line is remembered on Send (`sessionPrompts.ts`).

import { useEffect, useSyncExternalStore } from "react";
import { copy } from "../../copy";
import type { SessionRow } from "../../api/sessions";
import type { ThreadTab } from "../../stream/thread";
import { originPart } from "../../stream/thread";
import { sessionPromptStore } from "../../stream/sessionPrompts";
import {
applySessionDocumentTitle,
sessionLabel,
sessionTabMeta,
sessionTitleAttr,
Expand All @@ -43,6 +50,22 @@ export interface SessionTabsProps {
readonly panelId?: string | undefined;
}

function labelFor(
tab: ThreadTab,
row: SessionRow | undefined,
firstPrompt: string | null,
): string {
return sessionLabel({
sessionId: tab.session_id,
profile: row?.profile ?? null,
part: row?.part ?? null,
kind: tab.kind,
origin: tab.origin,
createdAt: tab.created_at ?? null,
firstPrompt,
});
}

export function SessionTabs({
tabs,
sessions,
Expand All @@ -53,6 +76,23 @@ export function SessionTabs({
}: SessionTabsProps): React.JSX.Element {
const byId = new Map(sessions.map((row) => [row.session_id, row]));
const selectedId = selected ?? tabs[0]?.session_id ?? "";
const firstPrompts = useSyncExternalStore(
sessionPromptStore.subscribe,
sessionPromptStore.getSnapshot,
sessionPromptStore.getServerSnapshot,
);
const selectedTab = tabs.find((tab) => tab.session_id === selectedId);
const selectedLabel =
selectedTab === undefined
? null
: labelFor(selectedTab, byId.get(selectedId), firstPrompts[selectedId] ?? null);

useEffect(() => {
applySessionDocumentTitle(selectedLabel);
return () => {
applySessionDocumentTitle(null);
};
}, [selectedLabel]);

return (
<div className={styles["tabs"]}>
Expand All @@ -73,18 +113,12 @@ export function SessionTabs({
tabs={tabs.map((tab) => {
const row = byId.get(tab.session_id);
const part = row?.part ?? originPart(tab.origin);
const label = sessionLabel({
sessionId: tab.session_id,
profile: row?.profile ?? null,
part: row?.part ?? null,
kind: tab.kind,
origin: tab.origin,
createdAt: tab.created_at ?? null,
});
const label = labelFor(tab, row, firstPrompts[tab.session_id] ?? null);
const meta = sessionTabMeta(tab, row);
return {
id: tab.session_id,
label,
ariaLabel: label,
title: sessionTitleAttr(tab.session_id, tab.thread_state),
trailing:
meta === null ? undefined : <span className={styles["tabMeta"]}>{meta}</span>,
Expand Down
12 changes: 9 additions & 3 deletions web/src/components/stream/StreamPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
// stays stale. All three are the same refetch of the same server projection;
// none merges a tool result, and none moves the pin.

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { WorkspaceError } from "../../api/client";
import { attachProjection, type AttachProjection } from "../../api/attach";
Expand All @@ -68,6 +68,7 @@ import { useWorkspace, workspaceStore } from "../../state/react";
import { sessionEmptyBody, sessionEmptyKind } from "../../stream/sessionEmpty";
import { useStream } from "../../stream/useStream";
import { useFollowScroll } from "../../stream/followScroll";
import { sessionPromptStore } from "../../stream/sessionPrompts";
import { titleForSession } from "../../stream/sessionTitle";
import { Composer, NewSessionAction } from "./Composer";
import { SessionTabs } from "./SessionTabs";
Expand Down Expand Up @@ -149,9 +150,14 @@ export function StreamPanel(): React.JSX.Element {

const scrollRef = useRef<HTMLDivElement | null>(null);
const { following, jumpToLatest } = useFollowScroll(scrollRef, selected, stream.rows.length);
const firstPrompts = useSyncExternalStore(
sessionPromptStore.subscribe,
sessionPromptStore.getSnapshot,
sessionPromptStore.getServerSnapshot,
);
const sessionTitle = useCallback(
(sessionId: string) => titleForSession(sessionId, rows, tabs),
[rows, tabs],
(sessionId: string) => titleForSession(sessionId, rows, tabs, undefined, firstPrompts[sessionId]),
[rows, tabs, firstPrompts],
);

const refusal = sessions.error instanceof WorkspaceError ? sessions.error : null;
Expand Down
64 changes: 64 additions & 0 deletions web/src/stream/sessionPrompts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copyright 2026 The Hephaestus Authors
// SPDX-License-Identifier: Apache-2.0
//
// First-prompt memory for session tab titles (#51).
//
// History omits `user_prompt` by design (`transcript.ts` HISTORICAL_ABSENCES),
// so the tab cannot read the operator's words back from `GET …/history`. The
// page that *sent* the prompt still has them, and that is enough to retitle
// the tab on the same frame as Send — without a reload, and without minting
// an event kind.
//
// First write wins. A later turn is not a new conversation; the tab keeps
// the line the operator opened with. The snapshot is replaced, never mutated,
// so `useSyncExternalStore` identity comparison is a correct change test.

import { firstPromptLine } from "./sessionTitle";

type Listener = () => void;

const EMPTY: Readonly<Record<string, string>> = {};

/**
* First prompt line per session id, as an external store.
*
* Not workspace state (§4.5's record is closed). A link does not need to
* carry the sentence; the UUID in `?s=` is still the identity.
*/
export class SessionPromptStore {
#byId: Readonly<Record<string, string>> = EMPTY;
readonly #listeners = new Set<Listener>();

subscribe = (listener: Listener): (() => void) => {
this.#listeners.add(listener);
return () => {
this.#listeners.delete(listener);
};
};

getSnapshot = (): Readonly<Record<string, string>> => this.#byId;

/** Test / SSR seam: the same empty record, so identity stays stable. */
getServerSnapshot = (): Readonly<Record<string, string>> => EMPTY;

remember(sessionId: string, text: string): void {
if (this.#byId[sessionId] !== undefined) return;
const line = firstPromptLine(text);
if (line === null) return;
this.#commit({ ...this.#byId, [sessionId]: line });
}

/** Test seam: forget every prompt this page has sent. */
reset(): void {
this.#commit(EMPTY);
}

#commit(next: Readonly<Record<string, string>>): void {
if (next === this.#byId) return;
this.#byId = next;
for (const listener of this.#listeners) listener();
}
}

/** The process-wide store. One page, the prompts it has actually sent. */
export const sessionPromptStore = new SessionPromptStore();
66 changes: 61 additions & 5 deletions web/src/stream/sessionTitle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ import { originPart, type ThreadTab } from "./thread";
const UUID =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

/**
* Visible tab width at 1280×800 is ~420px of 12px UI type. A full first-prompt
* sentence does not fit; a truncated UUID pair also does not, and those two
* failures used to look the same. Clip the *conversation*, never the id.
*/
export const SESSION_LABEL_MAX = 56;

export interface SessionTitleInput {
readonly sessionId: string;
readonly profile?: string | null;
Expand All @@ -28,13 +35,23 @@ export interface SessionTitleInput {
readonly now?: Date;
}

function firstLine(text: string | null | undefined): string | null {
export function isSessionId(value: string): boolean {
return UUID.test(value);
}

/** First line of a prompt, or `null` when it is empty or is itself a UUID. */
export function firstPromptLine(text: string | null | undefined): string | null {
if (text === null || text === undefined) return null;
const line = text.trim().split(/\r?\n/, 1)[0]?.trim() ?? "";
if (line === "" || UUID.test(line)) return null;
return line;
}

function clipLabel(text: string): string {
if (text.length <= SESSION_LABEL_MAX) return text;
return `${text.slice(0, SESSION_LABEL_MAX - 1)}…`;
}

function boundPart(input: SessionTitleInput): string | null {
if (typeof input.part === "string" && input.part !== "") return input.part;
return originPart(input.origin ?? {});
Expand All @@ -44,11 +61,12 @@ function boundPart(input: SessionTitleInput): string | null {
* The human label for one session tab. Never a UUID.
*
* Precedence is what the operator can recognise: their own words, then the
* part they asked about, then the create affordance plus a time.
* part they asked about, then the create affordance plus a time. A long
* prompt is clipped; the fallback is never `session.id.slice`.
*/
export function sessionLabel(input: SessionTitleInput): string {
const prompt = firstLine(input.firstPrompt);
if (prompt !== null) return prompt;
const prompt = firstPromptLine(input.firstPrompt);
if (prompt !== null) return clipLabel(prompt);
const part = boundPart(input);
if (part !== null) return copy.composer.createPart(part);
if (input.createdAt !== null && input.createdAt !== undefined) {
Expand All @@ -57,6 +75,41 @@ export function sessionLabel(input: SessionTitleInput): string {
return copy.composer.createOrchestrator;
}

/** Chrome `document.title` for a conversation. Never the raw session id. */
export function sessionDocumentTitle(label: string): string {
return `${label} · ${copy.app.name}`;
}

export function defaultDocumentTitle(): string {
return `${copy.app.name} ${copy.app.tagline}`;
}

/** Apply or restore the browser tab title. The UUID is not a title. */
export function applySessionDocumentTitle(label: string | null): void {
document.title =
label === null || label === "" ? defaultDocumentTitle() : sessionDocumentTitle(label);
}

/**
* The in-flight holder sentence (#66). A callback that still echoes the
* session id is treated as missing — the UUID stays on `data-run-in-flight-session`.
*/
export function holderSessionTitle(
sessionId: string,
resolved: string | null | undefined,
): string {
if (
resolved !== null &&
resolved !== undefined &&
resolved !== "" &&
resolved !== sessionId &&
!isSessionId(resolved)
) {
return resolved;
}
return copy.composer.createOrchestrator;
}

/** Tooltip / `title`: the UUID, plus the unlinked reason when that is a fact. */
export function sessionTitleAttr(
sessionId: string,
Expand Down Expand Up @@ -100,6 +153,7 @@ export function titleInputFor(
sessions: readonly SessionRow[],
tabs: readonly ThreadTab[],
now?: Date,
firstPrompt?: string | null,
): SessionTitleInput {
const row = sessions.find((item) => item.session_id === sessionId);
const tab = tabs.find((item) => item.session_id === sessionId);
Expand All @@ -110,6 +164,7 @@ export function titleInputFor(
kind: tab?.kind ?? null,
origin: tab?.origin ?? {},
createdAt: tab?.created_at ?? null,
firstPrompt: firstPrompt ?? null,
...(now === undefined ? {} : { now }),
};
}
Expand All @@ -120,6 +175,7 @@ export function titleForSession(
sessions: readonly SessionRow[],
tabs: readonly ThreadTab[],
now?: Date,
firstPrompt?: string | null,
): string {
return sessionLabel(titleInputFor(sessionId, sessions, tabs, now));
return sessionLabel(titleInputFor(sessionId, sessions, tabs, now, firstPrompt));
}
7 changes: 7 additions & 0 deletions web/src/system/TabBar.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@
.stack .tab {
width: 100%;
justify-content: flex-start;
overflow: hidden;
}

.stack .tab > span:first-of-type {
overflow: hidden;
text-overflow: ellipsis;
min-width: 0;
}

.stack .tab[aria-selected="true"] {
Expand Down
6 changes: 6 additions & 0 deletions web/src/system/TabBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ export interface TabSpec<Id extends string> {
readonly attrs?: DataAttributes | undefined;
/** Native `title` — session tabs put the UUID here, not in the label. */
readonly title?: string | undefined;
/**
* Accessible name when it must not pick up `title` (session UUID tooltip).
* Stage / Inspector tabs omit this and keep their visible label.
*/
readonly ariaLabel?: string | undefined;
/** Per-tab layout (thread depth indent). */
readonly style?: CSSProperties | undefined;
}
Expand Down Expand Up @@ -115,6 +120,7 @@ export function TabBar<Id extends string>({
className={cx(styles["tab"], roles["label"])}
title={tab.title}
style={tab.style}
{...(tab.ariaLabel === undefined ? {} : { "aria-label": tab.ariaLabel })}
{...{ [attr]: tab.id }}
{...(tab.attrs ?? {})}
onClick={() => {
Expand Down
3 changes: 3 additions & 0 deletions web/test/stream/composer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import { CHIP_ORDER, chipsFor, envelopeFor } from "../../src/stream/composerCont
import { DEFAULT_STATE, type WorkspaceState } from "../../src/state/workspace";
import { workspaceStore } from "../../src/state/react";
import { formatRef } from "../../src/system";
import { sessionPromptStore } from "../../src/stream/sessionPrompts";
import { copy } from "../../src/copy";

// The one route the last block counts calls on. Everything else in the module is
Expand Down Expand Up @@ -631,6 +632,7 @@ afterEach(() => {
vi.mocked(sendPrompt).mockReset();
vi.mocked(cancelRun).mockReset();
workspaceStore.reset(DEFAULT_STATE);
sessionPromptStore.reset();
});

function mount(props: Partial<React.ComponentProps<typeof Composer>> = {}): HTMLDivElement {
Expand Down Expand Up @@ -737,6 +739,7 @@ describe("the paths that bypass Send are gated where Send's gate is decided", ()
type(root, "Bump the kerf to 0.25 mm.");
pressEnter(root);
expect(vi.mocked(sendPrompt)).toHaveBeenCalledTimes(1);
expect(sessionPromptStore.getSnapshot()["sess-1"]).toBe("Bump the kerf to 0.25 mm.");
await act(async () => undefined);
});

Expand Down
Loading
Loading