Repository navigation
Expand file tree
/
Copy pathassistantBus.ts
More file actions
337 lines (300 loc) · 12.9 KB
/
Copy pathassistantBus.ts
File metadata and controls
337 lines (300 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Assistant bus — a tiny framework-agnostic singleton that connects the
* metadata designers to the global AI chat (`ConsoleFloatingChatbot`).
*
* Two channels:
* 1. **Editor context** — a designer publishes *what the user is
* currently editing* (`{ type, name, label, fields }`). The chatbot
* reads it and merges it into the `context` it sends the agent, so
* "add a priority field" acts on the open object without the user
* restating which object they mean.
* 2. **Open signal** — a designer can ask the global chat to open (e.g.
* an "Ask AI" button). The lazy chat FAB arms + opens on the signal.
*
* Why a singleton bus instead of React context? The chat FAB is
* lazy-mounted on a different branch of the tree from the designers, and
* the open-signal must cross that boundary without a shared Provider
* being threaded through every layout. A module singleton + (subscribe,
* getSnapshot) reads cleanly via `useSyncExternalStore`.
*/
import { useEffect, useSyncExternalStore } from 'react';
import { useAuth } from '@object-ui/auth';
export interface AssistantEditorField {
name: string;
type?: string;
label?: string;
required?: boolean;
}
export interface AssistantEditorContext {
/** Metadata type, e.g. 'object'. */
type: string;
/** Item primary-key name (may be empty in create mode). */
name: string;
label?: string;
/** Lightweight field summary — enough for the agent to reason, not the full draft. */
fields?: AssistantEditorField[];
}
/** A metadata item the chat has asked the host to open in review/diff. */
export interface AssistantReviewTarget {
type: string;
name: string;
}
export interface AssistantSnapshot {
/** What the user is currently editing, or null when no designer is active. */
editor: AssistantEditorContext | null;
/** Monotonic counter — bumped each time a surface requests the chat to open. */
openSeq: number;
/**
* Monotonic counter — bumped each time the chat asks the host to open a
* drafted item in review (ADR-0033 Phase B). The host (which knows the app
* base) watches this and navigates to the designer.
*/
reviewSeq: number;
/** The item to review, set alongside the latest `reviewSeq` bump. */
reviewTarget: AssistantReviewTarget | null;
}
let editor: AssistantEditorContext | null = null;
let openSeq = 0;
let reviewSeq = 0;
let reviewTarget: AssistantReviewTarget | null = null;
// Cached snapshot — its reference only changes on a real state change so
// useSyncExternalStore doesn't loop.
let snapshot: AssistantSnapshot = { editor, openSeq, reviewSeq, reviewTarget };
const listeners = new Set<() => void>();
function commit(): void {
snapshot = { editor, openSeq, reviewSeq, reviewTarget };
for (const l of listeners) l();
}
function sameEditor(a: AssistantEditorContext | null, b: AssistantEditorContext | null): boolean {
if (a === b) return true;
return JSON.stringify(a) === JSON.stringify(b);
}
export const assistantBus = {
subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
getSnapshot(): AssistantSnapshot {
return snapshot;
},
/** Publish the currently-edited item (or null to clear). No-op if unchanged. */
setEditor(next: AssistantEditorContext | null): void {
if (sameEditor(editor, next)) return;
editor = next;
commit();
},
/** Ask the global chat to open (and warm/mount the lazy FAB). */
requestOpen(): void {
openSeq += 1;
commit();
},
/**
* Ask the host to open `target` in the designer's review/diff (ADR-0033
* Phase B). The chat calls this from the "Review N change(s)" affordance;
* a navigator that knows the app base performs the routing.
*/
requestReview(target: AssistantReviewTarget): void {
reviewSeq += 1;
reviewTarget = target;
commit();
},
};
// ── ADR-0037 P2.5 — canvas invalidations ───────────────────────────────────
// The chat announces "this draft artifact just changed"; preview surfaces in
// the SAME document (a page open on ?preview=draft while the floating chat
// edits) subscribe and refetch the affected type. Kept OFF the snapshot bus:
// invalidations are fire-and-forget events, not state — putting them in the
// snapshot would re-render every useAssistant consumer per artifact.
export interface CanvasInvalidation {
type: string;
name: string;
}
const invalidateListeners = new Set<(inv: CanvasInvalidation) => void>();
/** Announce that a draft artifact changed (chat hosts call this). */
export function emitCanvasInvalidate(inv: CanvasInvalidation): void {
for (const l of invalidateListeners) l(inv);
}
/** Subscribe to draft-artifact invalidations; returns an unsubscriber. */
export function subscribeCanvasInvalidate(
listener: (inv: CanvasInvalidation) => void,
): () => void {
invalidateListeners.add(listener);
return () => {
invalidateListeners.delete(listener);
};
}
// ── Live-metadata-changed signal ─────────────────────────────
// The live registry just changed out-of-band from the metadata trees — a
// publish promoted staged drafts, or a marketplace install merged a package.
// Unlike the per-artifact, draft-only canvas invalidations above, this is a
// coarse "the live world changed, refetch" pulse: EVERY mounted
// MetadataProvider (nav sidebar included, not just the surface that triggered
// it) refetches its loaded types so already-open forms/views/nav pick up the
// change WITHOUT a full page reload. Fire-and-forget, off the snapshot bus
// (same reasoning as canvas invalidations — an event, not state).
const metadataRefreshListeners = new Set<() => void>();
/** Announce that the live metadata registry changed (publish / install hosts call this). */
export function emitMetadataRefresh(): void {
for (const l of metadataRefreshListeners) l();
}
/** Subscribe to live-metadata-changed events; returns an unsubscriber. */
export function subscribeMetadataRefresh(listener: () => void): () => void {
metadataRefreshListeners.add(listener);
return () => {
metadataRefreshListeners.delete(listener);
};
}
// ── objectui#11666 — a proposed plan awaiting the user's approval ──────────
// The chat knows, per conversation, whether the newest proposed plan still
// waits for the user: `ChatbotEnhanced` derives it from the same producer its
// plan card renders and reports it through `onPlanApprovalPendingChange`, and
// the chat host (`ChatPane`) publishes that reading here. The launchers — the
// console FAB and the ChatDock edge launcher — read it, and they are on screen
// only while the chat is CLOSED, when no chat code is mounted to ask. This
// store is where the reading outlives the chat.
//
// Only a mounted chat writes it, and every change to a plan's state in this
// document happens inside a mounted chat (the approval click, a newer
// proposal, the build that runs), so within the document it is the chat's own
// reading, not a guess. What it cannot see is stated rather than papered over:
// a change made in another tab or device, and a page reload. The durable copy
// is the server conversation, which the launcher cannot read without the chat
// graph it exists to keep out of the first load.
//
// Two keys, both load-bearing:
// * the conversation — opening a chat on ANOTHER thread does not clear a
// plan waiting in this one, so opening a chat clears nothing by itself;
// * the owner — the SPA keeps running across a sign-out (`AuthProvider`), so
// a reading is shown only to the user it was read for, never carried into
// the next session in the tab.
// Kept OFF the snapshot bus above, like the two event channels: a plan's state
// must not re-render every `useAssistant` consumer.
//
// objectstack#25943 — each reading also carries how many items the proposal
// asks the user to confirm (a change plan's rows, 1 for a proposed plan), the
// 「N 项待确认」 Studio's right slot shows beside the folded copilot.
interface PlanApprovalReading {
/** The user whose chat read the proposal as awaiting approval. */
owner: string;
/** Items awaiting confirmation; at least 1. */
count: number;
}
/** conversation id → the reading of its newest proposal, while one awaits approval. */
let planApprovalOwners: ReadonlyMap<string, PlanApprovalReading> = new Map();
const planApprovalListeners = new Set<() => void>();
function subscribePlanApproval(listener: () => void): () => void {
planApprovalListeners.add(listener);
return () => {
planApprovalListeners.delete(listener);
};
}
function getPlanApprovalOwners(): ReadonlyMap<string, PlanApprovalReading> {
return planApprovalOwners;
}
/**
* Record a chat's reading of whether `conversationId`'s newest proposal awaits
* the user's approval, and how many items it asks them to confirm (chat hosts
* call this; `count` defaults to 1 while pending). No-op when unchanged.
* `pending: false` also drops the reading of a conversation that was deleted.
*/
export function publishPlanApprovalPending(reading: {
userId: string | undefined;
conversationId: string;
pending: boolean;
count?: number;
}): void {
const owner = reading.userId ?? '';
const count = Math.max(1, reading.count ?? 1);
const current = planApprovalOwners.get(reading.conversationId);
if (
reading.pending
? current?.owner === owner && current.count === count
: current === undefined
) {
return;
}
const next = new Map(planApprovalOwners);
if (reading.pending) next.set(reading.conversationId, { owner, count });
else next.delete(reading.conversationId);
planApprovalOwners = next;
for (const l of planApprovalListeners) l();
}
/**
* True while any conversation of the signed-in user has a proposed plan
* awaiting approval, as last read by a mounted chat. Read by the launchers.
*/
export function usePlanApprovalPending(): boolean {
return usePlanApprovalPendingCount() > 0;
}
/**
* objectstack#25943 — how many items the signed-in user's chats read as
* awaiting their confirmation, summed over conversations; 0 when none. Read by
* Studio's right slot for its 「N 项待确认」.
*/
export function usePlanApprovalPendingCount(): number {
const readings = useSyncExternalStore(
subscribePlanApproval,
getPlanApprovalOwners,
getPlanApprovalOwners,
);
const { user } = useAuth();
const owner = user?.id ?? '';
let count = 0;
for (const r of readings.values()) if (r.owner === owner) count += r.count;
return count;
}
/** Subscribe a component to the assistant bus snapshot. */
export function useAssistant(): AssistantSnapshot {
return useSyncExternalStore(
assistantBus.subscribe,
assistantBus.getSnapshot,
assistantBus.getSnapshot,
);
}
/**
* Publish the currently-edited item to the assistant for the lifetime of
* the calling component (auto-clears on unmount). Pass `null` to register
* nothing. Stable across renders with equal content.
*/
export function useRegisterAssistantEditor(ctx: AssistantEditorContext | null): void {
// Serialize for a cheap, content-based effect dependency.
const key = ctx ? JSON.stringify(ctx) : '';
useEffect(() => {
assistantBus.setEditor(ctx);
return () => assistantBus.setEditor(null);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key]);
}
/** Open the global AI chat from anywhere (e.g. an "Ask AI" button). */
export function requestAssistantOpen(): void {
assistantBus.requestOpen();
}
/** Ask the host to open a drafted item in the designer's review/diff. */
export function requestAssistantReview(target: AssistantReviewTarget): void {
assistantBus.requestReview(target);
}
// ── objectstack#34610 — a publish landed ───────────────────────────────────
// The screen's one Publish is the shell's bar (the draft bar, or the
// unpublished-app bar for an app not yet published), and the chat draws none
// of its own. So the chat learns a publish landed from here and shows a
// receipt for it. Fire-and-forget, off the snapshot bus, like the two
// signals above; `emitMetadataRefresh` still carries the "re-read" half.
export interface PublishReceipt {
/** The package the publish covered; null when it covered the whole environment. */
packageId: string | null;
}
const publishReceiptListeners = new Set<(receipt: PublishReceipt) => void>();
/** Announce that a publish from the shell's bar landed. */
export function emitPublishReceipt(receipt: PublishReceipt): void {
for (const l of publishReceiptListeners) l(receipt);
}
/** Subscribe to landed publishes; returns an unsubscriber. */
export function subscribePublishReceipt(listener: (receipt: PublishReceipt) => void): () => void {
publishReceiptListeners.add(listener);
return () => {
publishReceiptListeners.delete(listener);
};
}