From cc67a5711a0a086ac0817dadbe4f8ae474652e7e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:53:32 +0000 Subject: [PATCH 01/12] wip(app-shell): conversation focus follows the page until the first send Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibwivzADop4jGmFZ81y --- packages/spec/src/api/protocol.zod.ts | 4 +- packages/spec/src/contracts/ai-service.ts | 12 +- .../app-shell/src/console/ai/AiChatPage.tsx | 15 +- .../app-shell/src/console/ai/ChatFocusRow.tsx | 168 ++++---- .../app-shell/src/console/ai/ChatPane.tsx | 34 +- .../src/hooks/useChatConversation.ts | 18 + .../src/layout/ChatDockConversation.tsx | 31 +- ui/packages/app-shell/src/layout/chatFocus.ts | 383 +++++++++--------- .../__tests__/de-quote-pairing-3876.test.ts | 7 +- ui/packages/i18n/src/locales/ar.ts | 4 - ui/packages/i18n/src/locales/de.ts | 4 - ui/packages/i18n/src/locales/en.ts | 6 +- ui/packages/i18n/src/locales/es.ts | 4 - ui/packages/i18n/src/locales/fr.ts | 4 - ui/packages/i18n/src/locales/ja.ts | 4 - ui/packages/i18n/src/locales/ko.ts | 4 - ui/packages/i18n/src/locales/pt-BR.ts | 4 - ui/packages/i18n/src/locales/ru.ts | 4 - ui/packages/i18n/src/locales/zh-Hans.ts | 4 - ui/packages/i18n/src/locales/zh-Hant.ts | 4 - .../plugin-chatbot/src/ChatbotEnhanced.tsx | 9 +- ui/packages/plugin-chatbot/src/chat/types.ts | 9 + ui/packages/plugin-chatbot/src/useAgents.ts | 6 +- 23 files changed, 358 insertions(+), 384 deletions(-) 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..c19a424e2fb 100644 --- a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx +++ b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx @@ -213,6 +213,7 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro initialMessages, ensureConversation, createError: conversationCreateError, + conversationMetadata, } = useChatConversation({ // Gate resolution on the agent being known: resolving while `activeAgent` // is still undefined (catalog loading) would bind a SCOPELESS conversation @@ -250,10 +251,18 @@ 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); + // 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, + ); // A first send creates the conversation: the id it mints takes the focus - // pinned before it (and no other arriving id does). + // 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 932c2cafc65..6f3539d7b58 100644 --- a/ui/packages/app-shell/src/console/ai/ChatPane.tsx +++ b/ui/packages/app-shell/src/console/ai/ChatPane.tsx @@ -99,9 +99,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[]; @@ -343,9 +343,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 @@ -694,17 +694,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 ( @@ -768,9 +764,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} placeholder={ activeAgent @@ -857,7 +853,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 293c688fc5e..776ac77f80c 100644 --- a/ui/packages/app-shell/src/hooks/useChatConversation.ts +++ b/ui/packages/app-shell/src/hooks/useChatConversation.ts @@ -134,6 +134,13 @@ 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; isLoading: boolean; /** * Create the conversation on the FIRST SEND. The hook never mints a row on @@ -752,6 +759,11 @@ 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 [isLoading, setIsLoading] = useState(Boolean(userId)); const [createError, setCreateError] = useState(undefined); const mountedRef = useRef(true); @@ -811,6 +823,7 @@ export function useChatConversation( resolvedForUserRef.current = forUser; resolvedScopeRef.current = forScope; setConversationId(fresh.id); + setHeldMetadata({ id: fresh.id, metadata: fresh.metadata }); setInitialMessages(toUIMessages(fresh.messages)); } return fresh.id; @@ -928,6 +941,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 @@ -979,6 +993,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; @@ -1005,6 +1020,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' ? [] @@ -1207,6 +1223,8 @@ export function useChatConversation( conversationId, conversationScope: resolvedScopeRef.current, initialMessages, + conversationMetadata: + conversationId && heldMetadata?.id === conversationId ? heldMetadata.metadata : undefined, 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 e1e6cb726db..6729edc2b83 100644 --- a/ui/packages/app-shell/src/layout/ChatDockConversation.tsx +++ b/ui/packages/app-shell/src/layout/ChatDockConversation.tsx @@ -26,7 +26,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, @@ -178,6 +178,7 @@ export function ChatDockConversation({ initialMessages, ensureConversation, createError, + conversationMetadata, } = useChatConversation({ userId: conversationUserId, scope, @@ -214,17 +215,25 @@ 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). - // objectstack#37142 — keyed on the target too: a hand-off's carry goes to the - // thread this target resolves, never to a history row or another app's - // thread the user moves to before the first send. - const focusTarget = React.useMemo(() => (target ? JSON.stringify(target) : undefined), [target]); - const conversationFocus = useConversationFocus(paneConversationId, createError, focusTarget); + // 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, + ); // A first send creates the conversation: the id it mints takes the focus - // pinned before it (and no other arriving id does). + // 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/chatFocus.ts b/ui/packages/app-shell/src/layout/chatFocus.ts index f9555fb5f8c..a6412fbc7e4 100644 --- a/ui/packages/app-shell/src/layout/chatFocus.ts +++ b/ui/packages/app-shell/src/layout/chatFocus.ts @@ -1,46 +1,55 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectstack#36999 — the conversation's FOCUS: the record a user pinned the - * chat to, sent as `context.focus` on every turn (the spec's + * objectstack#36999 — the conversation's FOCUS: the record a conversation is + * about, sent as `context.focus` on every turn (the spec's * `ToolExecutionContext.focus`) and shown as a chip in the composer. * - * Three rules shape this module (topic #36996's rulings and the card's): + * objectstack#37861 (framework ADR-0160 D6, seventh amendment, "The focus of a + * conversation") — a conversation's state is `{ focus, dismissed }`: * - * - Per conversation, one record in phase 1, client-reported and advisory: + * - **Before the first send, the focus is the record on the page** (the + * console's `surfaceRecord()`), unless the user removed it with × + * (`dismissed`). It follows the page with no prompt: another record is that + * record, a page with no record is no focus. + * - **× removes it.** Nothing adds a focus to that conversation again. + * - **The first send fixes both.** The focus the conversation has at its first + * send rides that turn and every later one; navigation no longer moves it. + * After the first send × is the one change left. + * + * Three rules from topic #36996 still shape this module: + * + * - One record per conversation in phase 1, client-reported and advisory: * never an access decision. The server re-reads the record as the caller. - * - The request body is the authority. What is stored here only restores the - * chip of a conversation the host shows again (another page, the drawer - * closed and reopened, a reload of the tab). The stored copy is per tab - * (`sessionStorage`, like the drawer's own target), so the chip is never - * shown where the key would not also be sent. + * - The request body is the authority. What is stored only restores the chip + * of a conversation the host shows again: this tab's copy (`sessionStorage`, + * like the drawer's own target) and, for a conversation this tab never held + * (another tab, a history row), the conversation's own `metadata.focus`, + * which the in-app assistant writes from the turns it served. * - A focus rides on its conversation and never re-keys it: the dock resolves * the same thread with or without one (ADR-0057 as amended for * objectui#10926). The state is held by the HOST, above the pane it keys on * the conversation id, so the first send — which mints that id and remounts * the pane — still carries it. - * - * Kept free of chat code: `setChatFocus` is exported from the package root, so - * the record drawer and the `ask_ai` action can call it from the eager console - * graph (objectui#13410). */ import * as React from 'react'; +import type { ChatSurfaceContext } from './chatSurfaceContext.js'; -/** One pinned record: the object's machine name and the record id. */ +/** One focused record: the object's machine name and the record id. */ export interface ChatFocus { object: string; id: string; } -/** A conversation's focus and whether the user declined the 「ask about this one instead?」 offer. */ +/** A conversation's stored focus state (ADR-0160 D6, seventh amendment). */ export interface ChatFocusEntry { focus: ChatFocus | null; - /** Remembered for the conversation: once declined, opening another record asks no more. */ - declined: boolean; + /** The user removed the focus with ×: nothing adds one to this conversation again. */ + dismissed: boolean; } -const EMPTY_ENTRY: ChatFocusEntry = Object.freeze({ focus: null, declined: false }) as ChatFocusEntry; +const EMPTY_ENTRY: ChatFocusEntry = Object.freeze({ focus: null, dismissed: false }) as ChatFocusEntry; /** sessionStorage key prefix; the conversation id follows. */ export const CHAT_FOCUS_STORAGE_PREFIX = 'ai-chat-focus:'; @@ -51,39 +60,82 @@ function isChatFocus(value: unknown): value is ChatFocus { return typeof v.object === 'string' && v.object !== '' && typeof v.id === 'string' && v.id !== ''; } +/** + * The record a surface shows on its own (a record page, a record open in a + * list's drawer), or null: a list or a dashboard has none. An unsent + * conversation's focus (ADR-0160 D6, seventh amendment). + */ +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; +} + /** Two foci name the same record. */ export function sameChatFocus(a: ChatFocus | null | undefined, b: ChatFocus | null | undefined): boolean { if (!a || !b) return !a && !b; return a.object === b.object && a.id === b.id; } -/** The stored entry of `conversationId`, or the empty one. Never throws. */ -export function readStoredChatFocus(conversationId: string | undefined): ChatFocusEntry { - if (!conversationId) return EMPTY_ENTRY; +/** A conversation's focus as its `metadata.focus` carries it, with the record's label when the server read one. */ +export interface ChatFocusFromMetadata extends ChatFocus { + label?: string; +} + +/** + * The focus a conversation's `metadata` records, or null. The in-app + * assistant stores `focus` in the shape the request sends (`context.focus`): + * an array whose first entry is the record, with an optional display `label`. + * It deletes the key when a turn carries no focus. Anything else (a bare + * object, an entry without a string `object` and `id`) reads as no focus. + */ +export function chatFocusFromMetadata(metadata: Readonly> | undefined): ChatFocusFromMetadata | null { + const raw = metadata?.focus; + if (!Array.isArray(raw)) return null; + const first: unknown = raw[0]; + if (!isChatFocus(first)) return null; + const label = (first as { label?: unknown }).label; + return { + object: first.object, + id: first.id, + ...(typeof label === 'string' && label.trim() !== '' ? { label: label.trim() } : {}), + }; +} + +/** The stored entry of `conversationId` in this tab, or null when there is none. Never throws. */ +function readStoredEntry(conversationId: string | undefined): ChatFocusEntry | null { + if (!conversationId) return null; try { const raw = window.sessionStorage.getItem(`${CHAT_FOCUS_STORAGE_PREFIX}${conversationId}`); - if (!raw) return EMPTY_ENTRY; - const parsed = JSON.parse(raw) as { focus?: unknown; declined?: unknown }; - return { focus: isChatFocus(parsed.focus) ? parsed.focus : null, declined: parsed.declined === true }; + if (!raw) return null; + const parsed = JSON.parse(raw) as { focus?: unknown; dismissed?: unknown }; + const focus = isChatFocus(parsed.focus) ? { object: parsed.focus.object, id: parsed.focus.id } : null; + const dismissed = parsed.dismissed === true; + return focus || dismissed ? { focus, dismissed } : null; } catch { - return EMPTY_ENTRY; + return null; } } +/** The stored entry of `conversationId` in this tab, or the empty one. Never throws. */ +export function readStoredChatFocus(conversationId: string | undefined): ChatFocusEntry { + return readStoredEntry(conversationId) ?? EMPTY_ENTRY; +} + function writeStoredChatFocus(conversationId: string, entry: ChatFocusEntry): void { try { const key = `${CHAT_FOCUS_STORAGE_PREFIX}${conversationId}`; - if (!entry.focus && !entry.declined) window.sessionStorage.removeItem(key); + if (!entry.focus && !entry.dismissed) window.sessionStorage.removeItem(key); else window.sessionStorage.setItem(key, JSON.stringify(entry)); } catch { - /* private mode / quota — the chip simply is not restored */ + /* private mode / quota — the chip is restored from the conversation's metadata, or not at all */ } } /** * The `context` keys a turn adds for the focus: `{ focus: [record] }` while - * one is pinned AND the agent honours it, else nothing at all — so a turn - * without a focus is byte-identical to a turn before this key existed. + * the conversation has one AND the agent honours it, else nothing at all — so + * a turn without a focus is byte-identical to a turn before this key existed. */ export function buildFocusContext( focus: ChatFocus | null | undefined, @@ -92,219 +144,158 @@ export function buildFocusContext( return honoured && focus ? { focus: [{ object: focus.object, id: focus.id }] } : {}; } -// ── The one setter ───────────────────────────────────────────────────────── -// Every entry point pins through `setChatFocus`: the pin on the page chip, the -// record drawer and the `ask_ai` action. It applies to the chat host on -// screen; with none mounted (the drawer is closed) it waits, and the next host -// to mount takes it, so "pin, then open the drawer" lands on the drawer's -// conversation. -// -// objectstack#37142 — a caller that MOVES the chat in the same event (the -// `ask_ai` action opens a fresh thread) says so with `follow`: the focus is the -// next conversation's, so a host that shows one now leaves it untouched and -// hands the focus to the conversation it moves to. - -/** How `setChatFocus` lands. */ -export interface SetChatFocusOptions { - /** - * The caller is moving the chat to another conversation in this same event: - * the focus belongs to that one, not to the conversation on screen. A host - * with no conversation id yet takes it at once; a host showing one keeps - * that conversation's focus and gives this one to the next it shows. - */ - follow?: boolean; -} - -type ChatFocusHost = (focus: ChatFocus | null, follow: boolean) => void; -const hosts: ChatFocusHost[] = []; -let pending: { focus: ChatFocus | null; follow: boolean } | null = null; - -/** - * Pins `focus` to the conversation the chat shows (or clears it with `null`). - * A new focus starts with a fresh 「ask about this one instead?」 offer. - */ -export function setChatFocus(focus: ChatFocus | null, options?: SetChatFocusOptions): void { - const next = focus && isChatFocus(focus) ? { object: focus.object, id: focus.id } : null; - const follow = options?.follow === true; - const host = hosts[hosts.length - 1]; - if (host) host(next, follow); - else pending = { focus: next, follow }; -} - -function registerChatFocusHost(host: ChatFocusHost): () => void { - hosts.push(host); - if (pending) { - const { focus, follow } = pending; - pending = null; - host(focus, follow); - } - return () => { - const at = hosts.lastIndexOf(host); - if (at >= 0) hosts.splice(at, 1); - }; -} - -/** Test seam: forget every host and a waiting request. */ -export function resetChatFocusForTests(): void { - hosts.length = 0; - pending = null; -} - /** What a chat host hands its pane. */ -export interface ConversationFocus extends ChatFocusEntry { - /** Pin (or clear) the focus of the conversation on screen. */ - setFocus: (focus: ChatFocus | null) => void; - /** Decline the offer to switch; remembered for the conversation. */ - decline: () => void; +export interface ConversationFocus { + /** The conversation's focus now: the page's record while it has sent nothing (unless dismissed), else the one it was sent with. */ + focus: ChatFocus | null; + /** The user removed the focus with ×. */ + dismissed: boolean; + /** The conversation has sent nothing yet, so its focus follows the page. */ + unsent: boolean; + /** The record's display name as the conversation's metadata stored it, when the chip was restored from there. */ + label?: string; + /** × on the focus chip: clears the focus and sets `dismissed`. */ + dismiss: () => void; /** * The host is creating the conversation for a first send (it calls this * beside `ensureConversation`, and only while it has a user to create it - * for): the id that arrives next is the one that send goes to, so a focus - * pinned before it is carried onto it. A create that fails spends the mark - * (see the hook's `createError`). + * for): the id that arrives next is the one that send goes to, so it takes + * the focus the conversation had at this moment. A create that fails spends + * the mark (see the hook's `createError`). */ markSending: () => void; } interface FocusState { + /** The conversation the state is for; `undefined` is one with no id yet (unsent). */ key: string | undefined; + /** A sent conversation's entry; for an unsent one only `dismissed` is read. */ entry: ChatFocusEntry; - /** - * The id that arrives next takes this conversation's focus: set by a - * `setChatFocus` hand-off that landed before the host had an id ("pin, then - * open the drawer"); a first send says the same through `markSending`. Any - * other arrival of an id — a resumed thread resolving, a history row, the - * scope blanking the id between apps — reads that conversation's own stored - * focus instead. Only the hand-off's own focus is carried: the chip's pin, - * remove or decline drops the flag, and so does any change of what the host - * was asked to show ({@link FocusState.target}): an id that arrives for a - * history row picked, or an app moved to, before the first send is that - * conversation's own (objectstack#37142). - */ - carry: boolean; - /** - * What the host was asked to show when the state last moved (a key of the - * dock's target). A change drops the hand-off's carry. - */ - target: string | undefined; - /** - * A `follow` hand-off that landed while this host showed a conversation - * (objectstack#37142): the focus of the NEXT conversation the host shows, - * applied when the id changes (and carried, as a hand-off is, when that - * next one has no id yet). The chip's own moves drop it. - */ - follow?: { focus: ChatFocus | null }; + /** The metadata label of a focus restored from the conversation's metadata. */ + label?: string; + /** What the host was asked to show when the state last moved (see `origin`). */ + origin: string | undefined; +} + +/** The entry a conversation the host arrives at restores: this tab's copy, else its metadata's. */ +function restoredState( + key: string | undefined, + origin: string | undefined, + fromMetadata: ChatFocusFromMetadata | null, +): FocusState { + const stored = readStoredEntry(key); + if (stored) return { key, entry: stored, origin }; + if (key !== undefined && fromMetadata) { + return { + key, + entry: { focus: { object: fromMetadata.object, id: fromMetadata.id }, dismissed: false }, + label: fromMetadata.label, + origin, + }; + } + return { key, entry: EMPTY_ENTRY, origin }; } /** * The focus of the conversation `conversationId` names, held by the chat - * host. `undefined` is a conversation the host has no id for yet. A focus - * pinned there reaches an id only on a CARRY (see {@link FocusState.carry}): - * the first send minting it, or the setter's hand-off — and then in the same - * render, so the first turn, sent by the pane that remounts on that id, - * already carries it. Every other move to a conversation restores that one's - * chip from storage. + * host. `undefined` is a conversation the host has no id for yet: it has sent + * nothing, so its focus is `pageRecord` unless the user dismissed it. The + * first send fixes that focus onto the id it mints, in the same render, so the + * first turn, sent by the pane that remounts on that id, already carries it. + * Every other arrival of an id (a resumed thread resolving, a history row, the + * scope blanking the id between apps) restores that conversation's own focus: + * this tab's stored copy, else `metadata.focus` from the conversation's row. */ export function useConversationFocus( conversationId: string | undefined, /** The host's `createError`: a first send whose create failed minted nothing. */ createError?: unknown, + /** The record on the page in view (`surfaceRecord()`), or null on a page that shows no one record. */ + pageRecord?: ChatFocus | null, + /** The `metadata` of the conversation `conversationId` names, as its row returned it. */ + conversationMetadata?: Readonly>, /** - * A key of what the host was asked to show (the dock's target): while it - * holds, an id the host resolves takes a hand-off's carry; once it changes, - * the next id is the conversation's own. A host that passes none keeps the - * carry until an id arrives. + * A key of what the host was asked to show (the dock's target). While the + * conversation is unsent, a change starts another one: its `dismissed` is + * dropped. A host that passes none keeps it until an id arrives. */ - target?: string, + origin?: string, ): ConversationFocus { - const [state, setState] = React.useState(() => ({ - key: conversationId, - entry: readStoredChatFocus(conversationId), - carry: false, - target, - })); - // A first send in flight: a ref, not state, so marking it re-renders - // nothing while the pane holds the message it is creating the row for. - const sendingRef = React.useRef(false); + const fromMetadata = React.useMemo(() => chatFocusFromMetadata(conversationMetadata), [conversationMetadata]); + const [state, setState] = React.useState(() => restoredState(conversationId, origin, fromMetadata)); + // The focus a first send in flight fixes: a ref, not state, so marking it + // re-renders nothing while the pane holds the message it is creating the + // row for. + const sendingRef = React.useRef(null); let current = state; - // The host was asked for something else (a history row, another app): a - // hand-off's carry does not go with it. A pending `follow` does — the caller - // that moved the target set it for exactly that move. - if (current.target !== target) current = { ...current, target, carry: false }; if (current.key !== conversationId) { - const carried = - current.key === undefined && - conversationId !== undefined && - (current.carry || sendingRef.current) && - current.entry.focus !== null; - current = current.follow - ? { - key: conversationId, - entry: { focus: current.follow.focus, declined: false }, - carry: conversationId === undefined, - target, - } - : { - key: conversationId, - entry: carried ? current.entry : readStoredChatFocus(conversationId), - carry: false, - target, - }; + const sending = current.key === undefined && conversationId !== undefined ? sendingRef.current : null; + current = sending + ? { key: conversationId, entry: sending, origin } + : restoredState(conversationId, origin, fromMetadata); + } else if (current.origin !== origin) { + // Another target while unsent is another conversation: × on the last one + // does not carry over. A sent conversation keeps its own entry. + current = current.key === undefined ? { key: undefined, entry: EMPTY_ENTRY, origin } : { ...current, origin }; + } else if ( + current.key !== undefined && + fromMetadata && + !current.entry.focus && + !current.entry.dismissed && + readStoredEntry(current.key) === null + ) { + // The conversation's row arrived after its id: its metadata restores the + // chip this tab never held. + current = restoredState(current.key, origin, fromMetadata); } // Derived state set during render: React re-renders before committing, so // no child of this commit sees the previous conversation's focus. if (current !== state) setState(current); - const { key, entry } = current; + const { key, entry, label } = current; React.useEffect(() => { if (key !== undefined) writeStoredChatFocus(key, entry); }, [key, entry]); // The send's id has arrived (or another one did): the mark is spent. React.useEffect(() => { - if (key !== undefined) sendingRef.current = false; + if (key !== undefined) sendingRef.current = null; }, [key]); // The send's create failed: no id is coming for it, so the mark is spent - // and the next id to arrive (a history row) reads its own focus. A send + // and the next id to arrive (a history row) restores its own focus. A send // made while the host is still resolving is not spent: the resolve fulfils // it, and the id that arrives is the one that send goes to. React.useEffect(() => { - if (createError) sendingRef.current = false; + if (createError) sendingRef.current = null; }, [createError]); - // The chip's own moves drop a hand-off's carry: what the user pins (or - // keeps) here is this conversation's, and follows no other one. - const setFocus = React.useCallback((focus: ChatFocus | null) => { - setState((s) => - sameChatFocus(s.entry.focus, focus) && !s.follow - ? s - : { ...s, entry: { focus, declined: false }, carry: false, follow: undefined }, - ); - }, []); - const decline = React.useCallback(() => { - setState((s) => - s.entry.declined && !s.carry && !s.follow - ? s - : { ...s, entry: { ...s.entry, declined: true }, carry: false, follow: undefined }, - ); + const unsent = key === undefined; + const page = pageRecord && isChatFocus(pageRecord) ? pageRecord : null; + const pageObject = page?.object; + const pageId = page?.id; + const effective = React.useMemo(() => { + if (!unsent) return entry.focus; + if (entry.dismissed || !pageObject || !pageId) return null; + return { object: pageObject, id: pageId }; + }, [unsent, entry, pageObject, pageId]); + const effectiveRef = React.useRef({ focus: effective, dismissed: entry.dismissed }); + effectiveRef.current = { focus: effective, dismissed: entry.dismissed }; + + const dismiss = React.useCallback(() => { + setState((s) => (s.entry.dismissed && !s.entry.focus ? s : { ...s, entry: { focus: null, dismissed: true }, label: undefined })); }, []); const markSending = React.useCallback(() => { - sendingRef.current = true; - }, []); - // The setter's hand-off: applied here, and carried onto the id the host - // resolves next when it has none yet. A `follow` hand-off to a host showing - // a conversation waits for the next one instead (see `FocusState.follow`). - const handOff = React.useCallback((focus: ChatFocus | null, follow: boolean) => { - setState((s) => - follow && s.key !== undefined - ? { ...s, follow: { focus } } - : { ...s, entry: { focus, declined: false }, carry: s.key === undefined, follow: undefined }, - ); + sendingRef.current = { ...effectiveRef.current }; }, []); - React.useEffect(() => registerChatFocusHost(handOff), [handOff]); - return React.useMemo( - () => ({ focus: entry.focus, declined: entry.declined, setFocus, decline, markSending }), - [entry, setFocus, decline, markSending], + () => ({ + focus: effective, + dismissed: entry.dismissed, + unsent, + ...(label && effective ? { label } : {}), + dismiss, + markSending, + }), + [effective, entry.dismissed, unsent, label, dismiss, markSending], ); } diff --git a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index 83ab3f9f17e..c29c631fd40 100644 --- a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts +++ b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts @@ -500,7 +500,9 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // `console.ai.empty.editApp.title`, `chatbot.plan.iterateOrNew.question` and // `.extend`, `chatbot.plan.suggestedFieldLegend`, `chatbot.build.nextStepQuote` // and `chatbot.build.draftPosture` — six spans fewer. - expect(okSpans, 'correctly paired spans').toBe(129); + // 128 once objectstack-ai/objectstack#37861 removed `console.ai.focus.switchPrompt` + // with the offer it drew („{{target}}“) — one interpolated span fewer. + expect(okSpans, 'correctly paired spans').toBe(128); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -647,7 +649,8 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // and `grid.import.scopeEntry`. // 129 / 129 / 0 after objectstack-ai/objectstack#37682 retired six build-chat // keys, one matched pair each. - expect({ open, close, rdq }).toEqual({ open: 129, close: 129, rdq: 0 }); + // 128 / 128 / 0 after objectstack-ai/objectstack#37861 removed `console.ai.focus.switchPrompt`. + expect({ open, close, rdq }).toEqual({ open: 128, close: 128, rdq: 0 }); // The durable shape: every „ closed by a “, every surplus “ an English // opener answered by a ”. Survived translating the two English values. expect(close).toBe(open + rdq); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 7aad391e849..62a955525d4 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -2649,12 +2649,8 @@ const ar = { }, discussing: "قيد العرض: {{target}}", focus: { - pin: "مواصلة السؤال عن هذا السجل", pinned: "السؤال عن: {{target}}", remove: "التوقف عن السؤال عن هذا السجل", - switchPrompt: "هل تريد السؤال عن «{{target}}» بدلاً من ذلك؟", - switchAccept: "تبديل", - switchDecline: "إبقاء", }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index bf443a5a9fc..97118400494 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2377,12 +2377,8 @@ const de = { }, discussing: "Angezeigt: {{target}}", focus: { - pin: "Weiter zu diesem Datensatz fragen", pinned: "Fragen zu: {{target}}", remove: "Nicht mehr zu diesem Datensatz fragen", - switchPrompt: "Stattdessen zu „{{target}}“ fragen?", - switchAccept: "Wechseln", - switchDecline: "Beibehalten", }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 7242665c70a..16b2649dc80 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3180,14 +3180,10 @@ const en = { hideChats: 'Hide chats', showChats: 'Show chats', discussing: 'Viewing: {{target}}', - // objectstack#36999 — the conversation focus: the record the chat is pinned to. + // objectstack#36999 — the conversation focus: the record the conversation is about. focus: { - pin: 'Keep asking about this record', pinned: 'Asking about: {{target}}', remove: 'Stop asking about this record', - switchPrompt: 'Ask about "{{target}}" instead?', - switchAccept: 'Switch', - switchDecline: 'Keep', }, justNow: 'just now', minutesAgo: '{{count}}m ago', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 106310c7133..35326e1c473 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -2447,12 +2447,8 @@ const es = { }, discussing: "Viendo: {{target}}", focus: { - pin: "Seguir preguntando sobre este registro", pinned: "Preguntando sobre: {{target}}", remove: "Dejar de preguntar sobre este registro", - switchPrompt: "¿Preguntar sobre «{{target}}» en su lugar?", - switchAccept: "Cambiar", - switchDecline: "Mantener", }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 9dd3e6a56f0..56e89b3e8cb 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -2443,12 +2443,8 @@ const fr = { }, discussing: "Affiché : {{target}}", focus: { - pin: "Continuer à poser des questions sur cet enregistrement", pinned: "Questions sur : {{target}}", remove: "Ne plus poser de questions sur cet enregistrement", - switchPrompt: "Poser plutôt des questions sur « {{target}} » ?", - switchAccept: "Changer", - switchDecline: "Conserver", }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 8fecce1e1e7..70a4f9c005b 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2379,12 +2379,8 @@ const ja = { }, discussing: "表示中: {{target}}", focus: { - pin: "このレコードについて質問し続ける", pinned: "質問対象: {{target}}", remove: "このレコードについての質問をやめる", - switchPrompt: "代わりに「{{target}}」について質問しますか?", - switchAccept: "切り替える", - switchDecline: "このまま", }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 2cbfdc1e883..e21b3ede2e5 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2377,12 +2377,8 @@ const ko = { }, discussing: "보는 중: {{target}}", focus: { - pin: "이 레코드에 대해 계속 질문", pinned: "질문 대상: {{target}}", remove: "이 레코드에 대한 질문 중지", - switchPrompt: "대신 \"{{target}}\"에 대해 질문할까요?", - switchAccept: "전환", - switchDecline: "유지", }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 1176e882d23..6b0c176f745 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -2442,12 +2442,8 @@ const pt = { }, discussing: "Vendo: {{target}}", focus: { - pin: "Continuar perguntando sobre este registro", pinned: "Perguntando sobre: {{target}}", remove: "Parar de perguntar sobre este registro", - switchPrompt: "Perguntar sobre \"{{target}}\" em vez disso?", - switchAccept: "Trocar", - switchDecline: "Manter", }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 9e7ba809ee9..a77f6e62207 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2519,12 +2519,8 @@ const ru = { }, discussing: "Просмотр: {{target}}", focus: { - pin: "Продолжать спрашивать об этой записи", pinned: "Вопросы о записи: {{target}}", remove: "Больше не спрашивать об этой записи", - switchPrompt: "Спрашивать вместо этого о «{{target}}»?", - switchAccept: "Переключить", - switchDecline: "Оставить", }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 4ab8b0cd431..cd2052a2455 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -2702,12 +2702,8 @@ const zh = { showChats: '显示对话列表', discussing: '正在看:{{target}}', focus: { - pin: '钉住这条记录,换页后仍问它', pinned: '正在问:{{target}}', remove: '不再问这条记录', - switchPrompt: '改为问《{{target}}》?', - switchAccept: '改为问它', - switchDecline: '不用', }, justNow: '刚刚', minutesAgo: '{{count}} 分钟前', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 28fff9b6892..bab26f43a2c 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2702,12 +2702,8 @@ const zhHant = { showChats: '顯示對話列表', discussing: '正在看:{{target}}', focus: { - pin: '釘住這條記錄,換頁後仍問它', pinned: '正在問:{{target}}', remove: '不再問這條記錄', - switchPrompt: '改為問《{{target}}》?', - switchAccept: '改為問它', - switchDecline: '不用', }, justNow: '剛剛', minutesAgo: '{{count}} 分鐘前', diff --git a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx index 52288cc8001..a2d147b4edc 100644 --- a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx +++ b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx @@ -216,6 +216,7 @@ const ChatbotEnhanced = React.forwardRef( onOpenList, surfaceContextLabel, surfaceContextTitle, + promptInputHeaderSlot, processVisibility = 'summary', surface = 'card', ...props @@ -997,7 +998,13 @@ const ChatbotEnhanced = React.forwardRef( {/* objectstack#35445 — the page in view sits on the input's top edge, inside its frame: it belongs to what the next message carries, and it never lies over the conversation. */} - {surfaceContextLabel ? ( + {/* objectstack#37861 — the host's own context row takes that + place, at the start of the line inside the frame. */} + {promptInputHeaderSlot ? ( + + {promptInputHeaderSlot} + + ) : surfaceContextLabel ? ( Date: Fri, 27 Nov 2026 14:55:28 +0000 Subject: [PATCH 02/12] wip(app-shell): rewrite the conversation focus test Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibwivzADop4jGmFZ81y --- .../layout/__tests__/chatFocus-36999.test.tsx | 505 +++++++++--------- 1 file changed, 247 insertions(+), 258 deletions(-) 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 dccaff45936..5e6465ac40a 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`, `setChatFocus`) 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,6 +51,8 @@ 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>, }; vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { @@ -59,8 +65,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} +