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
5 changes: 5 additions & 0 deletions .changeset/3963-dialogue-account-ownership.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-server": minor
---

An owner can continue a chat by voice from another device (#3963). Every owner sign-in is its own principal, and a chat's retained voice history belonged to the exact login that started it, so a second login was refused with "Dialogue ownership mismatch". That history now belongs to the account, as its safety history does: another owner login opens voice on it, reads it, binds it and receives its live pages, also after the starting login has been pruned. A typed-first chat's first voice from either login uses the chat's own history owner. A live conversation and its epochs stay with the login that opened them (migration 090 records it), so sharing the history gives no control over another login's conversation. Agents, ambient, system and unknown principals still match only themselves, a pruned or revoked login regains nothing, corrupt or contradictory ownership is refused, coverage stays honestly `legacy` or `partial`, and exact-principal chat deletion is unchanged.
4 changes: 3 additions & 1 deletion api-report/ui-server.txt
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,7 @@ signatures (every public export and the types it is made of)
}
DialogueJournal (packages/ui-server/src/ws/dialogue.ts)
export class DialogueJournal {
constructor(private readonly catalog: SessionCatalog, private readonly publish: (page: DialoguePage, principalId: string) => void, private readonly failed: (owner: DialogueOwner, cause: "queue_pressure" | "storage_error" | "storage_indeterminate", kind?: DialogueEvidence["kind"]) => void);
constructor(private readonly catalog: SessionCatalog, private readonly publish: (page: DialoguePage, principalId: string, owner?: DialogueOwner) => void, private readonly failed: (owner: DialogueOwner, cause: "queue_pressure" | "storage_error" | "storage_indeterminate", kind?: DialogueEvidence["kind"]) => void);
open(input: DialogueOpen): Promise<DialogueOwner | undefined>;
bind(conversationId: string, principalId: string, sessionId: string): void;
voice(conversationId: string, evidence: Extract<DialogueEvidence, {
Expand Down Expand Up @@ -586,6 +586,7 @@ signatures (every public export and the types it is made of)
export interface DialogueOwner {
id: string;
principal_id: string;
principal_account?: string | null;
session_id: string | null;
generation: number;
coverage: DialoguePage["coverage"];
Expand Down Expand Up @@ -2095,6 +2096,7 @@ signatures (every public export and the types it is made of)
dialogueOwnerForConversation?(conversationId: string, principalId: string): DialogueOwner | null;
dialogueOwnerForId?(ownerId: string, principalId: string): DialogueOwner | null;
dialogueOwnerForSession?(sessionId: string): DialogueOwner | null;
dialogueAudience?(owner: DialogueOwner, principalId: string): boolean;
dialogueClose?(conversationId: string, principalId: string, epoch: number, partial: boolean): Promise<void>;
dialogueOpen?(input: DialogueOpen): Promise<DialogueOwner>;
dialogueAppend?(input: DialogueAppend): Promise<import("@schlessera/brain-ui-sdk/protocol").DialogueRecord>;
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -2254,7 +2254,7 @@ The brain's git history stays the durable record of its content.
- **The Activity recorder and its rollups** price those events under the
[cost-tracking rules](cost-tracking.md). An unknown price is never counted as
zero. The session total that counts unknown as zero
(`msg.costUsd ?? 0`, `packages/ui-server/src/ws/session-catalog.ts:500`)
(`msg.costUsd ?? 0`, `packages/ui-server/src/ws/session-catalog.ts:511`)
must not feed any budget.

**Enforcement:**
Expand Down
2 changes: 1 addition & 1 deletion docs/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -630,7 +630,7 @@ key or SSE resumption promise exists.
All are protected; access is to the shared server record, not solely the
calling principal's runs or sessions.

**GET /api/sessions.** Optional `includeRetainedConversations=true` adds principal-owned host-only conversation metadata in `retainedConversations` (`id`, `created_at`), without fabricating backend sessions or tasks. At most 200 metadata rows are returned; `retainedAfter` is the exclusive ID cursor for the next page. Omit it for the first page. Dialogue itself uses the separately negotiated bounded WebSocket history protocol. Returns `{ sessions: ChatSession[],
**GET /api/sessions.** Optional `includeRetainedConversations=true` adds the caller's account's host-only conversation metadata in `retainedConversations` (#3963) (`id`, `created_at`), without fabricating backend sessions or tasks. At most 200 metadata rows are returned; `retainedAfter` is the exclusive ID cursor for the next page. Omit it for the first page. Dialogue itself uses the separately negotiated bounded WebSocket history protocol. Returns `{ sessions: ChatSession[],
unavailableBackends?: string[] }`, newest lastActiveAt first. Each session has
id, nullable title, createdAt, lastActiveAt, totalCostUsd, numTurns and
backendId. Stored nonzero accounting supplements a backend's zero figures.
Expand Down
11 changes: 11 additions & 0 deletions docs/integration-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,17 @@ as a credential, so it cannot enable a provider. `buildSystemPromptAppend`
accepts `webTools: true`, which adds the brief's line on what the web tools
do not offer. This ships in a minor.

## Retained voice history belongs to its account (additive, 0.45.0, #3963)

Another owner login continues a chat's retained dialogue by voice, reads it
and receives its live pages; a pruned starting login no longer strands it. A
live conversation and its epochs stay with the login that opened them, and
other accounts are refused as before. No field changes. See
[wire](integration-contract/wire.md#retained-voice-history-belongs-to-its-account-additive-0450-3963),
[HTTP](integration-contract/http.md#retained-conversations-account-additive-3963)
and [the package API](integration-contract/package-api.md#retained-dialogue-data-3177).
This ships in a minor; no breaking ruling is required.

## Retained barge-in and conversation end (additive, 0.45.0, #3729)

`DialogueEvidence` gains `voice_interruption`, written when the host forwards
Expand Down
12 changes: 12 additions & 0 deletions docs/integration-contract/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,18 @@ evidence is contradictory, which no released host writes, and attribution,
records, verdicts, gaps and generations are not rewritten
([decision](../decisions/session-safety-reviews.md#a-chats-safety-history-outlives-its-login-3962)).

<a id="retained-conversations-account-additive-3963"></a>

### Retained conversations list the account's histories (additive, #3963)

`GET /api/sessions?includeRetainedConversations=true` lists, in
`retainedConversations`, the host-only histories of the caller's account: its
own, and those another owner login started, including one whose login has
since been pruned. An agent, ambient or system principal still lists only its
own. A history whose stored ownership evidence is corrupt or contradictory is
listed for nobody. The shape, paging and `retainedAfter` cursor are unchanged
([wire](wire.md#retained-voice-history-belongs-to-its-account-additive-0450-3963)).

<a id="root-server-warning-additive-1638"></a>

### Root server warning (additive, #1638)
Expand Down
10 changes: 10 additions & 0 deletions docs/integration-contract/package-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5240,6 +5240,16 @@ meaning. No provider history-selection API is delivered by this slice.
write path. The [wire amendment](wire.md#retained-barge-in-and-conversation-end-additive-0450-3729)
defines when each is written and how the client draws them.

For account-owned retained history (#3963, additive in 0.45.0),
`DialogueOwner` gains optional `principal_account`, the stored account beside
`principal_id`; `SessionCatalog` gains optional `dialogueAudience(owner,
principalId)`, whether that login may receive the owner's pages; and the
`DialogueJournal` publish callback receives the owner as an optional third
argument after the unchanged page and `principalId`. Existing catalogs and
callbacks keep compiling and behave as before. The
[wire amendment](wire.md#retained-voice-history-belongs-to-its-account-additive-0450-3963)
defines who may use the history.

Failed-write live text exposes optional `ServerConversationEvent.retention` and
`ServerError.historyOwnerId`, plus the existing client projection's explicit
unsaved recognition/output fields (#3177). These are additive evidence and
Expand Down
49 changes: 46 additions & 3 deletions docs/integration-contract/wire.md
Original file line number Diff line number Diff line change
Expand Up @@ -2705,8 +2705,8 @@ Missing session reads use the same known-chat check as opening/resume and return
`SESSION_NOT_FOUND` with their request ID; absence is not legacy coverage.
A known chat without a journal receives an empty `complete` snapshot, with no
spoken-history warning or latest-conversation control. A session ID alone is not
evidence of prior voice use. `legacy` requires principal/session-scoped native
voice recovery evidence without a matching journal conversation. Missing old
evidence of prior voice use. `legacy` requires account/session-scoped native
voice recovery evidence without a matching journal conversation ([#3963](#retained-voice-history-belongs-to-its-account-additive-0450-3963)). Missing old
recovery metadata cannot reconstruct speech or prove it existed. No spoken words
are invented from task prompts, JSON, drafts or paraphrases.

Expand Down Expand Up @@ -2773,7 +2773,7 @@ so a prior unclosed epoch is still conservatively qualified before Start.
Failure notices latch once per owner/open episode; shutdown still reports the
aggregate writer failure. Draining a failed epoch cannot close its replacement.

Before a backend names a session, a principal-owned host history owner retains
Before a backend names a session, an account-owned host history owner retains
the evidence without creating a backend turn. `conversation_opened` adds optional
`historyOwnerId`/`historyGeneration`. A new `conversation_start.historyOwnerId`
reopens such history without using it as a backend session ID. Exact host task
Expand Down Expand Up @@ -2829,6 +2829,49 @@ answer. Its complete semantic source group remains readable with unknown
cross-stream position until the missing history page or evidence is available.


<a id="retained-voice-history-belongs-to-its-account-additive-0450-3963"></a>

### Retained voice history belongs to its account (additive, 0.45.0, #3963)

A chat's retained dialogue now follows the account that owns it, as its
safety history does ([#3952, #3962](http.md#durable-safety-account-additive-3962)):
another owner login, on another device, continues the chat by voice. The host
reads the same `dialogue_read` page, resolves the same `ownerId`,
`sessionId` and aliases, opens `conversation_start` with `sessionId` or
`historyOwnerId` on the same canonical owner and history, binds and adopts it,
and sends that login's live `dialogue_history` pages and dialogue storage
errors to every connected login of the account. A typed-first chat's first
voice, from either login, reuses the chat's safety history owner. Account
matching is `sameAccount` over the owner's stored account (migration 089), so
the history stays the owner's after the login that started it is pruned.

What stays exact:

- A live conversation and its epochs belong to the login that opened them.
Another login of the account starts a new conversation on the history; it
cannot resume, reopen or close another login's conversation or epoch, or
write voice, interruption or end evidence into it.
Migration `090_dialogue_conversation_principal.sql` records the opening
login on each conversation, and fills it for existing rows from their owner,
which before this change was always the opening login.
- An agent, ambient, system or unknown principal matches only itself. A
pruned, expired or revoked login regains nothing: the caller is still a
current, authorized login. Exact-principal chat deletion is unchanged.
- History whose login was pruned before it stored an account stays unknown
and refused. Corrupt or contradictory stored evidence matches nobody, its
own principal included, and refuses only that chat.
- Coverage never claims more than the evidence: native voice recovery of any
login of the account, or of a login whose row is gone, keeps a chat
`legacy`, and another login's unclosed earlier epoch still marks it
`partial`.

Nothing previously accepted is refused, with two exceptions no released host
reaches in ordinary use: voice opened on a chat whose typed safety owner is
another account, which formerly forked a second history owner, and a record
whose stored evidence is contradictory. Records, order, aliases, attribution
and generations are not rewritten, no field is added, and no ownership data
reaches a provider.

### Retained barge-in and conversation end (additive, 0.45.0, #3729)

`DialogueEvidence` gains two kinds. Both are display evidence, retained on the
Expand Down
12 changes: 6 additions & 6 deletions docs/plans/chat-history-deletion.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ consent for a replacement identity. Existing [session principals](../decisions/s
and [operational recovery](../inbox-recovery.md) remain binding.

There is no general delete operation: `createSessionRoutes` only lists/reads
(`createSessionRoutes`, `packages/ui-server/src/routes/sessions.ts:9-157`).
(`createSessionRoutes`, `packages/ui-server/src/routes/sessions.ts:27-175`).
`AgentBackend` exposes native list/read and read-only storage roots, not deletion
(`AgentBackend`, `packages/ui-sdk/src/server/backend.ts:826-882`). A storage root
is not removal authority. Future supported package/HTTP/wire changes need their
Expand Down Expand Up @@ -191,7 +191,7 @@ must be tested through their installed runtime, not inferred from directory name
Payloads include independent recognition/output evidence and backend range text;
hashes/order/identity are not substitutes for erasing the payload. An owner can
start unbound, bind to a backend session or merge into an existing owner through
aliases (`bindDialogue`, `packages/ui-server/src/ws/dialogue-storage.ts:176-222`).
aliases (`bindDialogue`, `packages/ui-server/src/ws/dialogue-storage.ts:220-266`).
Resolve the complete alias/conversation set transactionally; do not delete only
the current session key or confuse a provisional owner ID with a backend ID.
- **Task recovery and facts.** `069_conversation_tasks.sql` and
Expand All @@ -213,7 +213,7 @@ must be tested through their installed runtime, not inferred from directory name
readable projections according to the adopted extent. Retained digests can
reveal guessed short text; discard unnecessary hashes, not just plaintext.
Native history joins several of these owners
(`prepareHistory`, `packages/ui-server/src/ws/host.ts:642-654`).
(`prepareHistory`, `packages/ui-server/src/ws/host.ts:685-697`).
- **Independent session ledgers.** `retry_receipts`, `session_work`, `turn_boundaries`,
draft send/save/upload receipts and revisions, handoff IDs/lineage, Claude usage
deduplication, worker profiles, provider-exposure and born-masked lineage are
Expand Down Expand Up @@ -256,8 +256,8 @@ must be tested through their installed runtime, not inferred from directory name
handoff preparation, classifier callbacks, DialogueJournal routing/pending writes,
ConversationHost receipts/results/output and frozen startup envelopes can retain
or publish text. Catalog optimistic maps precede worker acknowledgements
(`rowEffects`, `packages/ui-server/src/ws/session-catalog.ts:255-268`;
`activeDialogueEpochs`, `packages/ui-server/src/ws/session-catalog.ts:298-301`).
(`rowEffects`, `packages/ui-server/src/ws/session-catalog.ts:258-271`;
`activeDialogueEpochs`, `packages/ui-server/src/ws/session-catalog.ts:301-304`).
Both submission and worker commit need a generation check.
- **Browser state.** Chat buffers/history chunks, shared timeline, session
title/list cache, dialogue pages/cursors, recognition/generated/unsaved tails,
Expand Down Expand Up @@ -300,7 +300,7 @@ The paired WS dispatcher is `packages/ui-server/src/ws/dispatch.ts`, with one
handler per frame under `ws/handlers/`; gating its resume handler alone would leave HTTP, background readers and provider startup open.

Existing ordinary history publication checks concurrent turn changes
(`publishHistory`, `packages/ui-server/src/ws/host.ts:568-602`). Future deletion
(`publishHistory`, `packages/ui-server/src/ws/host.ts:629-663`). Future deletion
must additionally invalidate it even when no turn starts or ends. Startup reads
native history, canonical evidence and completed facts, and freezes a snapshot
(`readLiveHistory`, `packages/ui-server/src/ws/live-history.ts:9-74`). Recheck the
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
-- A chat's retained dialogue belongs to its account (#3963), as its safety
-- history does (#3962): another login of the same owner continues it by voice
-- from another device. A live conversation does not: only the login that
-- opened it reopens or closes its epochs.
--
-- `principal_id` names that login. The server writes it when the conversation
-- first opens and never rewrites it. The history's ownership stays on
-- dialogue_owners (`principal_id` and 089's `principal_account`); this column
-- is no second ownership record and grants no history access.
--
-- Before this migration an owner opened only with its own exact principal,
-- and adoption joined only two owners of that same principal, so every
-- existing conversation was opened by its owner's principal. That is the
-- verified evidence the backfill copies. Nothing else changes.
ALTER TABLE dialogue_conversations ADD COLUMN principal_id TEXT;
UPDATE dialogue_conversations SET principal_id=
(SELECT o.principal_id FROM dialogue_owners o WHERE o.id=dialogue_conversations.owner_id);
20 changes: 19 additions & 1 deletion packages/ui-server/src/routes/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,24 @@ import type { AgentBackend } from "@schlessera/brain-ui-sdk/server";
import type { BackendRegistry } from "../agent/backend.js";
import { SESSION_NOT_FOUND, type SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol";
import { ChatRetiredError } from "../ws/chat-lifecycle.js";
import { principalAccount } from "../middleware/account-partition.js";

/**
* The caller's host-only retained histories: its own, and those another login
* of its account started (#3963). This is `sameAccount` over each owner's
* stored evidence, kept in SQL so the page stays one indexed range. Evidence
* is consistent when its account is NULL, or 'owner' with no live row that
* says otherwise; corrupt or contradictory evidence lists for nobody. The
* caller's account comes from its own current row. Comparisons use IS, so no
* NULL term can admit a row.
*/
const RETAINED_CONVERSATIONS = `SELECT d.id,d.created_at FROM dialogue_owners d
WHERE d.session_id IS NULL AND d.id>?3
AND (d.principal_account IS NULL OR (d.principal_account IS 'owner'
AND NOT EXISTS (SELECT 1 FROM principals p WHERE p.id=d.principal_id AND p.kind IS NOT 'owner')))
AND (d.principal_id IS ?1 OR (?2 IS 'owner' AND (d.principal_account IS 'owner'
OR EXISTS (SELECT 1 FROM principals p WHERE p.id=d.principal_id AND p.kind IS 'owner'))))
ORDER BY d.id LIMIT 201`;

export function createSessionRoutes(deps: {
registry: BackendRegistry;
Expand Down Expand Up @@ -120,7 +138,7 @@ export function createSessionRoutes(deps: {
if (after && (after.length > 2048 || !c.req.query("includeRetainedConversations")))
return c.json({error:"Invalid retained conversation cursor"},400);
const retainedRows = c.req.query("includeRetainedConversations") === "true" && principal
? db.query("SELECT id,created_at FROM dialogue_owners WHERE principal_id=? AND session_id IS NULL AND id>? ORDER BY id LIMIT 201").all(principal.id,after ?? "") as {id:string;created_at:number}[]
? db.query(RETAINED_CONVERSATIONS).all(principal.id,principalAccount(db,principal.id),after ?? "") as {id:string;created_at:number}[]
: undefined;
const retainedConversations = retainedRows?.slice(0,200).filter(row => !deps.retired?.({ ownerId: row.id }));
const retainedAfter = retainedRows && retainedRows.length > 200 ? retainedConversations!.at(-1)!.id : undefined;
Expand Down
Loading
Loading