diff --git a/.changeset/37861-focus-follows-page-until-first-send.md b/.changeset/37861-focus-follows-page-until-first-send.md new file mode 100644 index 00000000000..a0d686c1e4a --- /dev/null +++ b/.changeset/37861-focus-follows-page-until-first-send.md @@ -0,0 +1,25 @@ +--- +'@objectstack/spec': patch +'@object-ui/plugin-chatbot': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): a new chat conversation is about the record on the page until its first send, shown as a chip at the start of the composer's line; the pin and the offer to switch records are gone + +Clause-②: yes (widening) — `@object-ui/plugin-chatbot` `ChatbotEnhanced` gains the optional `promptInputHeaderSlot`; `@object-ui/app-shell` `UseChatConversationReturn` gains `conversationMetadata` and `createdConversationId` +Metadata-protocol: none +Removed locale keys (`@object-ui/i18n`, every pack): `console.ai.focus.pin`, `console.ai.focus.switchPrompt`, `console.ai.focus.switchAccept`, `console.ai.focus.switchDecline` — shipped only in 19 prereleases. + +Framework ADR-0160 D6, seventh amendment ("The focus of a conversation"). Where the agent the chat runs declares `capabilities.focus: true`: + +- **A conversation that has sent nothing is about the record on the page** (a record page, or a record open in a list's drawer). It follows the page with no prompt: another record is that record, and a list or a dashboard is no record, so the composer shows the page chip ("Viewing: X") there. +- **The chip sits inside the composer's frame, at the start of the line** (the right in Arabic): the object's icon, the record's name, and ×. × shows while the composer has focus or the pointer is over the chip, always on a touch screen, and has a 24px hit area. A record whose name cannot be read shows `object · id`. +- **× removes the focus and nothing adds it again** in that conversation, before or after the first send; the composer falls back to the page chip. +- **The first send fixes the focus**: that turn and every later one send it as `context.focus`, and navigation no longer changes it. A conversation sent without one never takes one. Only the conversation that send creates takes it: a thread a send made during the resolve joins, and a history row opened while the create is under way, keep their own. +- **A conversation opened again restores its own focus**: from this tab, or, in another tab or from history, from the `metadata.focus` its server row stores. The request body stays the authority. +- **Removed**: the pin on the page chip and the 「改为问《X》?」 offer to ask about another record, with their four locale keys (listed above). `console.ai.focus.pinned` now names the chip for assistive technology, and `.remove` labels ×. + +Where the agent does not declare the flag, nothing changes: no chip, no `focus` key, and the page chip stays where it was. + +`@object-ui/plugin-chatbot`: `ChatbotEnhanced` gains `promptInputHeaderSlot`, a row drawn inside the input's frame at the start of the line, in place of the `surfaceContextLabel` chip when given. `@object-ui/app-shell`: `useChatConversation` returns `conversationMetadata`, the `metadata` of the row it holds, and `createdConversationId`, the id of the row its own create minted last. `@objectstack/spec`: the `ToolExecutionContext.focus` docblock and the `capabilities.focus` description no longer speak of a pin; no key, type or gate changes. diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 49fae8703c1..bb9e267afea 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -32,7 +32,7 @@ const result = AiAgentCapabilitiesSchema.parse(data); | **canvas** | `boolean` | ✅ | Drives the Live Canvas split view (ADR-0037) | | **debug** | `boolean` | ✅ | Exposes the build-doctor debug drawer | | **resume** | `boolean` | ✅ | Turns resume durable multi-step runs (ADR-0013) | -| **focus** | `boolean` | optional | Honours a conversation focus: the chat request's `context.focus`, the record the user pinned the conversation to (`ToolExecutionContext.focus`). A client draws the pin and sends the key only when this is true; absent reads as false. | +| **focus** | `boolean` | optional | Honours a conversation focus: the chat request's `context.focus`, the record the conversation is about (`ToolExecutionContext.focus`). A client draws the focus chip and sends the key only when this is true; absent reads as false. | --- @@ -77,7 +77,7 @@ const result = AiAgentCapabilitiesSchema.parse(data); | **canvas** | `boolean` | ✅ | Drives the Live Canvas split view (ADR-0037) | | **debug** | `boolean` | ✅ | Exposes the build-doctor debug drawer | | **resume** | `boolean` | ✅ | Turns resume durable multi-step runs (ADR-0013) | -| **focus** | `boolean` | optional | Honours a conversation focus: the chat request's `context.focus`, the record the user pinned the conversation to (`ToolExecutionContext.focus`). A client draws the pin and sends the key only when this is true; absent reads as false. | +| **focus** | `boolean` | optional | Honours a conversation focus: the chat request's `context.focus`, the record the conversation is about (`ToolExecutionContext.focus`). A client draws the focus chip and sends the key only when this is true; absent reads as false. | --- diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 64a887dd905..7de2ba0035e 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -4729,8 +4729,8 @@ export const AiAgentCapabilitiesSchema = lazySchema(() => z.object({ debug: z.boolean().describe('Exposes the build-doctor debug drawer'), resume: z.boolean().describe('Turns resume durable multi-step runs (ADR-0013)'), focus: z.boolean().optional().describe( - 'Honours a conversation focus: the chat request\'s `context.focus`, the record the user pinned the ' - + 'conversation to (`ToolExecutionContext.focus`). A client draws the pin and sends the key only when ' + 'Honours a conversation focus: the chat request\'s `context.focus`, the record the conversation is ' + + 'about (`ToolExecutionContext.focus`). A client draws the focus chip and sends the key only when ' + 'this is true; absent reads as false.', ), })); diff --git a/packages/spec/src/contracts/ai-service.ts b/packages/spec/src/contracts/ai-service.ts index 34f29fb85ec..e70bf4a6da5 100644 --- a/packages/spec/src/contracts/ai-service.ts +++ b/packages/spec/src/contracts/ai-service.ts @@ -1263,12 +1263,14 @@ export interface ToolExecutionContext { mode?: string; }; /** - * The record(s) the conversation is pinned to — the conversation's FOCUS, + * The record(s) the conversation is about — the conversation's FOCUS, * as the client reports it on every turn (`context.focus` in the chat - * request body), beside the page in view ({@link surfaceContext}). Unlike - * the surface, a focus does not follow navigation: the user pinned it, and - * it stays until they remove or replace it, so "this policy" keeps meaning - * the pinned record while they browse elsewhere. + * request body), beside the page in view ({@link surfaceContext}). Until + * the conversation's first send, its focus is the record on the page + * unless the user removed it; the first send fixes it. Unlike the + * surface, a focus then does not follow navigation: it stays until the + * user removes it, so "this policy" keeps meaning the focused record + * while they browse elsewhere. * * Client-reported and advisory, exactly like {@link surfaceContext}: * NEVER an access decision. A consumer that reads the record re-reads it diff --git a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx index 2f597d80b7d..78f282537e8 100644 --- a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx +++ b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx @@ -213,6 +213,8 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro initialMessages, ensureConversation, createError: conversationCreateError, + conversationMetadata, + createdConversationId, } = useChatConversation({ // Gate resolution on the agent being known: resolving while `activeAgent` // is still undefined (catalog loading) would bind a SCOPELESS conversation @@ -250,10 +252,20 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro const [selectedModelId, setSelectedModelId] = useState(undefined); // objectstack#36999 — the conversation's focus, held here for the same // reason: the keyed pane remounts when the first send mints the id, and that - // first turn must still carry the record the user pinned. - const conversationFocus = useConversationFocus(paneConversationId, conversationCreateError); - // A first send creates the conversation: the id it mints takes the focus - // pinned before it (and no other arriving id does). + // first turn must still carry the conversation's record. This page shows no + // record of its own, so a new conversation here has none (ADR-0160 D6, + // seventh amendment); one opened from history restores its own from this + // tab or from its row's metadata (objectstack#37861). + const conversationFocus = useConversationFocus( + paneConversationId, + conversationCreateError, + null, + scopeMatched ? conversationMetadata : undefined, + undefined, + createdConversationId, + ); + // A first send creates the conversation: the id its create mints takes the + // focus the conversation had at that send (and no other arriving id does). const { markSending: markFocusSending } = conversationFocus; const ensureConversationForSend = useCallback(() => { // With no user there is nothing to create: no mark, so no id that diff --git a/ui/packages/app-shell/src/console/ai/ChatFocusRow.tsx b/ui/packages/app-shell/src/console/ai/ChatFocusRow.tsx index 6368db5085d..56c82d69364 100644 --- a/ui/packages/app-shell/src/console/ai/ChatFocusRow.tsx +++ b/ui/packages/app-shell/src/console/ai/ChatFocusRow.tsx @@ -1,42 +1,44 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectstack#36999 — the composer's context row while the agent honours a - * conversation focus (`capabilities.focus` on its catalog row). + * objectstack#36999 / objectstack#37861 — the composer's context chip while + * the agent honours a conversation focus (`capabilities.focus` on its catalog + * row), drawn inside the input's frame at the start of the line. * - * It takes the place of the page chip the composer draws today - * (`console.ai.discussing`), in the pane's in-flow composer row: the page chip - * with a pin on it when the page shows one record, or — once a record is - * pinned — the focus chip, naming the record by its display name, with a - * remove control. Opening another record while one is pinned asks once - * 「改为问《X》?」; a decline is remembered for the conversation. + * Framework ADR-0160 D6 (seventh amendment): with a focus, the chip names the + * record (the object's icon and the record's name) with × to remove it; × + * shows while the composer has focus or the pointer is over the chip, and + * always on a touch screen. Without a focus — a list or a dashboard, a + * conversation sent without one, or after × — it is the page chip + * 「正在看:X」 (`console.ai.discussing`), with no ×. There is no pin and no + * offer to switch records: an unsent conversation follows the page on its + * own, and a sent one keeps the record it was sent with. * * The record's name is read client-side, as the user: the object definition - * and one `findOne`, through the same seams the record page reads with. A + * and one `findOne`, through the same seams the record page reads with. Until + * that answers, the label the conversation's metadata stored stands in; a * record the user cannot read keeps its `object · id` pair. */ import * as React from 'react'; -import { Pin, X } from 'lucide-react'; +import { X } from 'lucide-react'; +import { ObjectIconTile } from '@object-ui/components'; import { useObjectTranslation } from '@object-ui/i18n'; import { useMetadataItem } from '@object-ui/react'; import { useAdapter } from '../../providers/AdapterProvider.js'; import { getRecordDisplayName } from '../../utils/index.js'; -import type { ChatSurfaceContext } from '../../layout/chatSurfaceContext.js'; -import { sameChatFocus, type ChatFocus, type ConversationFocus } from '../../layout/chatFocus.js'; +import type { ChatFocus, ConversationFocus } from '../../layout/chatFocus.js'; -/** The record a surface shows on its own (a record page, a record open in a list's drawer), or null. */ -export function surfaceRecord(surface: ChatSurfaceContext | undefined): ChatFocus | null { - const object = surface?.artifact?.type === 'object' ? surface.artifact.name : undefined; - const id = surface?.selection?.kind === 'record' ? surface.selection.id : undefined; - return object && id ? { object, id } : null; +/** What the chip shows of a record: its display name and its object's icon and colour. */ +export interface ChatRecordFace { + /** The display name, undefined while it loads and when the record or its definition cannot be read. */ + title?: string; + icon?: string; + color?: string; } -/** - * The display name of `record`, read as the user: undefined while it loads, - * and when the record or its definition cannot be read. - */ -export function useChatRecordTitle(record: ChatFocus | null): string | undefined { +/** The face of `record`, read as the user. */ +export function useChatRecordFace(record: ChatFocus | null): ChatRecordFace { const dataSource = useAdapter() as { findOne?: (object: string, id: string) => unknown } | null; const { item: objectDef } = useMetadataItem('object', record?.object ?? null); const object = record?.object; @@ -67,103 +69,75 @@ export function useChatRecordTitle(record: ChatFocus | null): string | undefined }; }, [object, id, canRead, dataSource]); - if (!record || !answer || answer.key !== key || !answer.row || !objectDef) return undefined; + const def = record ? (objectDef as { icon?: unknown; color?: unknown } | undefined) : undefined; + const icon = typeof def?.icon === 'string' ? def.icon : undefined; + const color = typeof def?.color === 'string' ? def.color : undefined; + if (!record || !answer || answer.key !== key || !answer.row || !objectDef) return { icon, color }; const title = getRecordDisplayName(objectDef, answer.row, { fallback: '' }); - return title || undefined; + return { title: title || undefined, icon, color }; } const CHIP = - 'inline-flex min-w-0 max-w-full items-center gap-1 rounded-full border bg-muted/40 px-2 py-0.5 text-[11px] text-muted-foreground'; -const CHIP_BUTTON = - 'inline-flex shrink-0 items-center justify-center rounded-full p-0.5 hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring'; + 'group/focus-chip inline-flex min-w-0 max-w-full items-center gap-1 rounded-full border bg-muted/40 py-0.5 text-[11px] text-muted-foreground'; +/** + * × — a 24px hit area around a 12px glyph (WCAG 2.5.8). Revealed while the + * pointer is over the chip, while anything in the composer has focus (the + * frame is the `group/input-group`), on its own keyboard focus, and always on + * a coarse pointer, where there is no hover. + */ +const REMOVE = + '-my-1 -me-1 inline-flex size-6 shrink-0 items-center justify-center rounded-full opacity-0 transition-opacity hover:bg-muted hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring group-hover/focus-chip:opacity-100 group-focus-within/input-group:opacity-100 pointer-coarse:opacity-100'; export interface ChatFocusRowProps { /** The host's focus state for the conversation on screen. */ focus: ConversationFocus; - /** The page in view (`context.surface`). */ - surface?: ChatSurfaceContext; /** The page chip's text, as the composer draws it today; absent → no page chip. */ surfaceLabel?: string; /** The page chip's tooltip (the internal `type · name` pair). */ surfaceTitle?: string; } -export function ChatFocusRow({ focus, surface, surfaceLabel, surfaceTitle }: ChatFocusRowProps) { +export function ChatFocusRow({ focus, surfaceLabel, surfaceTitle }: ChatFocusRowProps) { const { t } = useObjectTranslation(); - const pinned = focus.focus; - const pageRecord = surfaceRecord(surface); - const offerSwitch = Boolean(pinned && pageRecord && !sameChatFocus(pinned, pageRecord) && !focus.declined); - const pinnedTitle = useChatRecordTitle(pinned); - const pageTitle = useChatRecordTitle(offerSwitch ? pageRecord : null); + const record = focus.focus; + const face = useChatRecordFace(record); - if (pinned) { - const pair = `${pinned.object} · ${pinned.id}`; + if (record) { + const pair = `${record.object} · ${record.id}`; + const name = face.title || focus.label || pair; + const described = t('console.ai.focus.pinned', { defaultValue: 'Asking about: {{target}}', target: name }); return ( -
- -
+ + ); } if (!surfaceLabel) return null; return ( -
- - {surfaceLabel} - {pageRecord ? ( - - ) : null} - -
+ + {surfaceLabel} + ); } diff --git a/ui/packages/app-shell/src/console/ai/ChatPane.tsx b/ui/packages/app-shell/src/console/ai/ChatPane.tsx index 15de774004b..48e14be9558 100644 --- a/ui/packages/app-shell/src/console/ai/ChatPane.tsx +++ b/ui/packages/app-shell/src/console/ai/ChatPane.tsx @@ -105,9 +105,9 @@ interface ChatPaneProps { * pane it keys on the conversation id, so the first send still carries it; * see `useConversationFocus`). Drawn and sent only while the agent's catalog * row declares `capabilities.focus`: then every turn carries - * `context.focus`, and the composer's context row replaces the page chip + * `context.focus`, and the composer's context chip replaces the page chip * ({@link ChatFocusRow}). Absent, or an agent that does not honour it → - * nothing changes: no pin, no chip, no key. + * nothing changes: no chip, no key. */ conversationFocus?: ConversationFocus; agents: AgentDescriptor[]; @@ -371,9 +371,9 @@ export function ChatPane({ // transport reads the body per send, so this stays fresh per turn). // The console dock sends the page in view too (objectstack#30043). ...(surfaceContext ? { surface: surfaceContext } : {}), - // objectstack#36999 — the record the conversation is pinned to, on - // EVERY turn while it is pinned (the body is the authority; nothing - // the server stored replaces it). No key at all otherwise. + // objectstack#36999 — the record the conversation is about, on EVERY + // turn while it has one (the body is the authority; nothing the + // server stored replaces it). No key at all otherwise. ...buildFocusContext(conversationFocus?.focus, focusHonoured), // The language this console renders in, so a reply that names a card // control names it as the card draws it. Only `Accept-Language` reaches @@ -778,17 +778,13 @@ export function ChatPane({ target: surfaceArtifactLabel || surfaceChipTitle, }) : undefined; - // objectstack#36999 — while the agent honours a focus, the composer's - // context row (the page chip with its pin, or the pinned record's chip) is - // drawn here instead of the composer's text-only page chip. + // objectstack#36999 / objectstack#37861 — while the agent honours a focus, + // the composer's context chip (the conversation's record with ×, or the + // page chip without one) is drawn here, inside the input's frame at the + // start of the line, instead of the composer's text-only page chip. const focusRow = - focusHonoured && conversationFocus ? ( - + focusHonoured && conversationFocus && (conversationFocus.focus || surfaceChipLabel) ? ( + ) : null; return ( @@ -854,9 +850,9 @@ export function ChatPane({ surface="plain" maxHeight="100%" headerSlot={hideHeader || !headerHasContent ? undefined : headerSlot} - // objectstack#36999 — the focus row is a row of the composer's own - // area, in flow above the input. - promptHeaderSlot={focusRow ?? undefined} + // objectstack#37861 — the focus chip sits inside the input's frame, + // at the start of the line. + promptInputHeaderSlot={focusRow ?? undefined} messages={shownMessages} // Keys the question card's skip marks to this conversation. conversationId={conversationId} @@ -946,7 +942,7 @@ export function ChatPane({ // free text in any language into the same field) and by the model on // its next turn. No code parses it, so it follows the UI locale. toolDenyReason={t('console.ai.toolDenyReason')} - // The page chip (see `surfaceChipLabel` above); the focus row draws it + // The page chip (see `surfaceChipLabel` above); the focus chip draws it // instead while the agent honours a focus (objectstack#36999). surfaceContextLabel={focusRow ? undefined : surfaceChipLabel} surfaceContextTitle={focusRow ? undefined : surfaceChipTitle} diff --git a/ui/packages/app-shell/src/hooks/useChatConversation.ts b/ui/packages/app-shell/src/hooks/useChatConversation.ts index abf797f4bf7..7d8b5ca1880 100644 --- a/ui/packages/app-shell/src/hooks/useChatConversation.ts +++ b/ui/packages/app-shell/src/hooks/useChatConversation.ts @@ -142,6 +142,21 @@ export interface UseChatConversationReturn { */ conversationScope: string | undefined; initialMessages: HydratedUIMessage[]; + /** + * objectstack#37861 — the `metadata` of the row `conversationId` names, as + * the conversation routes returned it when the hook read or created that + * row (`AiConversationSchema.metadata`, `@objectstack/spec/api`). `undefined` + * while no conversation is held, or for a row served without one. + */ + conversationMetadata: Readonly> | undefined; + /** + * objectstack#37861 — the id of the row this hook's own create minted last + * (a first send, through `ensureConversation`), `undefined` before any. It + * is never cleared: a host that reads it as "the row this send created" + * compares it with the value it saw when the send was made, since a thread + * an earlier send created can be resolved again or opened from history. + */ + createdConversationId: string | undefined; isLoading: boolean; /** * Create the conversation on the FIRST SEND. The hook never mints a row on @@ -771,6 +786,12 @@ export function useChatConversation( adoptLegacyRef.current = adoptLegacy; const [conversationId, setConversationId] = useState(undefined); const [initialMessages, setInitialMessages] = useState([]); + // The metadata of the row last read or created, tagged with its id so a + // stale row never answers for another conversation. + const [heldMetadata, setHeldMetadata] = useState< + { id: string; metadata: Readonly> | undefined } | undefined + >(undefined); + const [createdConversationId, setCreatedConversationId] = useState(undefined); const [isLoading, setIsLoading] = useState(Boolean(userId)); const [createError, setCreateError] = useState(undefined); const mountedRef = useRef(true); @@ -830,6 +851,8 @@ export function useChatConversation( resolvedForUserRef.current = forUser; resolvedScopeRef.current = forScope; setConversationId(fresh.id); + setCreatedConversationId(fresh.id); + setHeldMetadata({ id: fresh.id, metadata: fresh.metadata }); setInitialMessages(toUIMessages(fresh.messages)); } return fresh.id; @@ -950,6 +973,7 @@ export function useChatConversation( if (existing) { writeCache(key, existing.id); setConversationId(existing.id); + setHeldMetadata({ id: existing.id, metadata: existing.metadata }); const messages = toUIMessages(existing.messages); const next = messages.length > 0 ? messages : readMessageCache(existing.id); // A re-resolve of the conversation we ALREADY hold (e.g. the scope @@ -1001,6 +1025,7 @@ export function useChatConversation( if (adoptLegacyRef.current?.(judged)) { writeCache(key, legacy.id); setConversationId(legacy.id); + setHeldMetadata({ id: legacy.id, metadata: legacy.metadata }); setInitialMessages(judged); resolvedForUserRef.current = userId; resolvedScopeRef.current = scope; @@ -1027,6 +1052,7 @@ export function useChatConversation( const reuse = resumeMode !== 'fresh' || messages.length === 0; if (reuse) { setConversationId(existing.id); + setHeldMetadata({ id: existing.id, metadata: existing.metadata }); setInitialMessages( resumeMode === 'fresh' ? [] @@ -1067,6 +1093,7 @@ export function useChatConversation( if (createdId) { conversationIdRef.current = createdId; setConversationId(createdId); + setCreatedConversationId(createdId); setInitialMessages([]); resolvedForUserRef.current = userId; resolvedScopeRef.current = scope; @@ -1229,6 +1256,9 @@ export function useChatConversation( conversationId, conversationScope: resolvedScopeRef.current, initialMessages, + conversationMetadata: + conversationId && heldMetadata?.id === conversationId ? heldMetadata.metadata : undefined, + createdConversationId, isLoading, ensureConversation, createError: conversationId ? undefined : createError, diff --git a/ui/packages/app-shell/src/layout/ChatDockConversation.tsx b/ui/packages/app-shell/src/layout/ChatDockConversation.tsx index eb0609d495d..a0262f66592 100644 --- a/ui/packages/app-shell/src/layout/ChatDockConversation.tsx +++ b/ui/packages/app-shell/src/layout/ChatDockConversation.tsx @@ -27,7 +27,7 @@ import { chatConversationScope, chatProductOfAgent } from '../hooks/chatScope.js import { resolveSurfaceAgent } from '../hooks/surfaceAgent.js'; import { isAiStudioEnabled } from '../runtime-config.js'; import type { ChatSurfaceContext } from './chatSurfaceContext.js'; -import { useConversationFocus } from './chatFocus.js'; +import { surfaceRecord, useConversationFocus } from './chatFocus.js'; import { sameDockTarget, type ChatDockConversationActions, @@ -186,6 +186,8 @@ export function ChatDockConversation({ initialMessages, ensureConversation, createError, + conversationMetadata, + createdConversationId, } = useChatConversation({ userId: conversationUserId, scope, @@ -227,13 +229,26 @@ export function ChatDockConversation({ // ADR-0028 — the composer's picked model, held here so it outlives the keyed // pane's remount when the first send mints the conversation. const [selectedModelId, setSelectedModelId] = React.useState(undefined); - // objectstack#36999 — the thread's focus (the record the user pinned it to), - // held here for the same reason. It rides on the thread the scope resolved - // and never re-keys it: a focus does not change which conversation the - // drawer shows (ADR-0057 as amended for objectui#10926). - const conversationFocus = useConversationFocus(paneConversationId, createError); - // A first send creates the conversation: the id it mints takes the focus - // pinned before it (and no other arriving id does). + // objectstack#36999 — the thread's focus (the record it is about), held here + // for the same reason. It rides on the thread the scope resolved and never + // re-keys it: a focus does not change which conversation the drawer shows + // (ADR-0057 as amended for objectui#10926). + // objectstack#37861 (ADR-0160 D6, seventh amendment) — until the first send + // the focus is the page's record; a thread opened again restores its own + // from this tab or from its row's metadata. Another target while unsent is + // another conversation, so × on the last one does not carry over. + const pageRecord = React.useMemo(() => surfaceRecord(surfaceContext), [surfaceContext]); + const focusOrigin = React.useMemo(() => (target ? JSON.stringify(target) : undefined), [target]); + const conversationFocus = useConversationFocus( + paneConversationId, + createError, + pageRecord, + scopeMatched ? conversationMetadata : undefined, + focusOrigin, + createdConversationId, + ); + // A first send creates the conversation: the id its create mints takes the + // focus the conversation had at that send (and no other arriving id does). const { markSending: markFocusSending } = conversationFocus; const ensureConversationForSend = React.useCallback(() => { // With no user there is nothing to create: no mark, so no id that diff --git a/ui/packages/app-shell/src/layout/__tests__/chatFocus-36999.test.tsx b/ui/packages/app-shell/src/layout/__tests__/chatFocus-36999.test.tsx index ca049a8ab3d..2636521ae17 100644 --- a/ui/packages/app-shell/src/layout/__tests__/chatFocus-36999.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/chatFocus-36999.test.tsx @@ -1,22 +1,25 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectstack#36999 — conversation focus: a record pinned to the chat is sent - * as `context.focus` on every turn, shown as a chip in the composer, and kept - * across navigation; only where the agent's catalog row declares - * `capabilities.focus`. + * objectstack#36999 / objectstack#37861 — conversation focus, as framework + * ADR-0160 D6 (seventh amendment, "The focus of a conversation") rules it: + * state `{ focus, dismissed }`; before the first send the focus is the record + * on the page unless dismissed, and follows the page; × removes it and nothing + * adds it again; the first send fixes both; a conversation opened again + * restores its own focus, from this tab or from its row's `metadata.focus`. + * Only where the agent's catalog row declares `capabilities.focus`. * * ## Real subjects * * The console dock body (`ChatDockConversation`) and the full-page chat * (`AiChatPage` at `/ai/ask`), each with the REAL `ChatPane`, the REAL * `useChatConversation`, the REAL `useObjectChat` transport, the REAL focus - * state (`useConversationFocus`) and the REAL composer row - * (`ChatFocusRow`). What is pinned is the JSON body of each POST to the - * agent's chat route (captured off a `fetch` stub) and the row the pane hands - * the composer. The stand-ins: the agent catalog, the model allowlist, and - * `ChatbotEnhanced` (a recorder that renders the composer row it is handed and - * exposes the send). + * state (`useConversationFocus`) and the REAL chip (`ChatFocusRow`). What is + * pinned is the JSON body of each POST to the agent's chat route (captured off + * a `fetch` stub) and the chip the pane hands the composer's input frame. The + * stand-ins: the agent catalog, the model allowlist, the conversation rows the + * server returns, and `ChatbotEnhanced` (a recorder that renders the chip it + * is handed inside a focusable frame and exposes the send). */ // AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it @@ -38,6 +41,7 @@ const state = { onSendMessage?: (text: string) => void; surfaceContextLabel?: string; promptHeaderSlot?: React.ReactNode; + promptInputHeaderSlot?: React.ReactNode; } | undefined, /** The JSON body of every chat POST, in order. */ @@ -47,8 +51,23 @@ const state = { createAttempts: 0, /** The next creates fail (the server answers 500). */ failCreate: false, + /** The `metadata` each existing conversation's row is served with. */ + rows: {} as Record | undefined>, + /** While set, a create waits on it before the server answers. */ + holdCreate: null as Promise | null, + /** A row's read waits on its entry before the server answers. */ + holdRead: {} as Record | undefined>, }; +/** A gate a stub waits on, and the call that opens it. */ +function gate(): { wait: Promise; open: () => void } { + let open!: () => void; + const wait = new Promise((resolve) => { + open = resolve; + }); + return { wait, open }; +} + vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { const actual = await importOriginal>(); return { @@ -59,8 +78,15 @@ vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { state.pane = props; return (
- {props.surfaceContextLabel ? {props.surfaceContextLabel} : null} {props.promptHeaderSlot} +
+ {props.promptInputHeaderSlot ? ( +
{props.promptInputHeaderSlot}
+ ) : props.surfaceContextLabel ? ( + {props.surfaceContextLabel} + ) : null} +