@cosmoops/connect-sdk 0.29.0 → 0.30.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +99 -0
- package/dist/cjs/client/components/ask-ai-history.js +106 -0
- package/dist/cjs/client/components/ask-ai-turns.js +87 -0
- package/dist/cjs/client/components/ask-ai.js +155 -30
- package/dist/cjs/client/provider.js +2 -2
- package/dist/cjs/server/client.js +1 -1
- package/dist/cjs/server/handler.js +75 -0
- package/dist/cjs/server/resources/ai.js +55 -0
- package/dist/esm/client/components/ask-ai-history.js +103 -0
- package/dist/esm/client/components/ask-ai-turns.js +82 -0
- package/dist/esm/client/components/ask-ai.js +122 -30
- package/dist/esm/client/provider.js +2 -2
- package/dist/esm/server/client.js +1 -1
- package/dist/esm/server/handler.js +75 -0
- package/dist/esm/server/resources/ai.js +55 -0
- package/dist/types/client/components/ask-ai-history.d.ts +25 -0
- package/dist/types/client/components/ask-ai-turns.d.ts +55 -0
- package/dist/types/client/components/ask-ai.d.ts +1 -1
- package/dist/types/client/provider.d.ts +8 -1
- package/dist/types/server/client.d.ts +1 -1
- package/dist/types/server/resources/ai.d.ts +49 -1
- package/dist/types/types.d.ts +48 -0
- package/package.json +1 -1
|
@@ -391,6 +391,12 @@ function createConnectHandler(options) {
|
|
|
391
391
|
// decision, so there is nothing for this layer to check more strictly.
|
|
392
392
|
screenContext: body.screenContext,
|
|
393
393
|
screens: body.screens,
|
|
394
|
+
// The browser's own id for this conversation, so the turn is stored
|
|
395
|
+
// and can be reopened. Safe to relay: it decides *which* of the
|
|
396
|
+
// caller's own conversations is written to, never whose - Connect
|
|
397
|
+
// refuses an id belonging to another user or another application, and
|
|
398
|
+
// the owner comes from `asUser` below.
|
|
399
|
+
...(typeof body.conversationId === "string" ? { conversationId: body.conversationId } : {}),
|
|
394
400
|
// Connect re-derives the workspace from this token, so the line above
|
|
395
401
|
// is belt to its braces - the browser cannot reach another tenant's
|
|
396
402
|
// Context Index even if this route were changed to trust the request.
|
|
@@ -409,6 +415,75 @@ function createConnectHandler(options) {
|
|
|
409
415
|
},
|
|
410
416
|
});
|
|
411
417
|
},
|
|
418
|
+
/**
|
|
419
|
+
* Ask AI history - the list, one transcript, and a deletion.
|
|
420
|
+
*
|
|
421
|
+
* The same rule as every other route: the user comes from the caller's own
|
|
422
|
+
* session, forwarded as `asUser`, and Connect reads both the person and
|
|
423
|
+
* the workspace from it. Nothing here takes an owner from the request, so
|
|
424
|
+
* a browser cannot page through anybody else's conversations - which
|
|
425
|
+
* matters more here than on most routes, because a transcript is the most
|
|
426
|
+
* candid record this API holds of what somebody was trying to do.
|
|
427
|
+
*
|
|
428
|
+
* The id is the only thing a browser supplies. It selects among the
|
|
429
|
+
* caller's own conversations and nothing more: an id belonging to another
|
|
430
|
+
* user is a 404, and one belonging to another application the same, so a
|
|
431
|
+
* shared workspace's two products cannot read each other's.
|
|
432
|
+
*
|
|
433
|
+
* It travels as `?id=` rather than as a path segment, and the store routes
|
|
434
|
+
* are why. This table is keyed by an exact `METHOD /path` string; the only
|
|
435
|
+
* thing that matches a *prefix* is `isStoreRoute`, kept to a closed list
|
|
436
|
+
* precisely so the bridge cannot drift into a generic proxy. Widening that
|
|
437
|
+
* matcher for one more resource would be the first step of exactly that
|
|
438
|
+
* drift, so the id goes in the query and the route keys stay exact.
|
|
439
|
+
*
|
|
440
|
+
* `requireToken` rather than `requireWorkspace`: Connect resolves the
|
|
441
|
+
* workspace from the token itself and refuses a staff session there, so
|
|
442
|
+
* the extra identity round trip would buy a differently-worded 403 and
|
|
443
|
+
* nothing else.
|
|
444
|
+
*/
|
|
445
|
+
"GET /ai/conversations": async (request) => {
|
|
446
|
+
const url = new URL(request.url);
|
|
447
|
+
const limit = url.searchParams.get("limit");
|
|
448
|
+
const cursor = url.searchParams.get("cursor");
|
|
449
|
+
return json(await client.ai.listConversations({
|
|
450
|
+
asUser: await requireToken(request),
|
|
451
|
+
// Forwarded only when present, so Connect's own defaults apply
|
|
452
|
+
// rather than this layer inventing a second set of them.
|
|
453
|
+
...(limit !== null ? { limit: Number(limit) } : {}),
|
|
454
|
+
...(cursor ? { cursor } : {}),
|
|
455
|
+
}));
|
|
456
|
+
},
|
|
457
|
+
"GET /ai/conversation": async (request) => {
|
|
458
|
+
const conversationId = new URL(request.url).searchParams.get("id");
|
|
459
|
+
if (!conversationId) {
|
|
460
|
+
throw new errors_js_1.ConnectError({
|
|
461
|
+
status: 400,
|
|
462
|
+
code: "validation_error",
|
|
463
|
+
message: "id is required",
|
|
464
|
+
endpoint: "GET /ai/conversation",
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
return json(await client.ai.getConversation({
|
|
468
|
+
conversationId,
|
|
469
|
+
asUser: await requireToken(request),
|
|
470
|
+
}));
|
|
471
|
+
},
|
|
472
|
+
"DELETE /ai/conversation": async (request) => {
|
|
473
|
+
const conversationId = new URL(request.url).searchParams.get("id");
|
|
474
|
+
if (!conversationId) {
|
|
475
|
+
throw new errors_js_1.ConnectError({
|
|
476
|
+
status: 400,
|
|
477
|
+
code: "validation_error",
|
|
478
|
+
message: "id is required",
|
|
479
|
+
endpoint: "DELETE /ai/conversation",
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
return json(await client.ai.deleteConversation({
|
|
483
|
+
conversationId,
|
|
484
|
+
asUser: await requireToken(request),
|
|
485
|
+
}));
|
|
486
|
+
},
|
|
412
487
|
/**
|
|
413
488
|
* The store, forwarded.
|
|
414
489
|
*
|
|
@@ -33,6 +33,10 @@ class AiResource {
|
|
|
33
33
|
json: {
|
|
34
34
|
workspaceId: input.workspaceId,
|
|
35
35
|
messages: input.messages,
|
|
36
|
+
// Omitted when absent, which is how a caller opts out of history: no
|
|
37
|
+
// id, nothing stored. Connect also stores nothing for a call carrying
|
|
38
|
+
// no `asUser`, because a conversation belongs to a person.
|
|
39
|
+
...(input.conversationId ? { conversationId: input.conversationId } : {}),
|
|
36
40
|
// Omitted entirely when absent, rather than sent as `undefined` - an
|
|
37
41
|
// application that describes no screens should send no field.
|
|
38
42
|
...(input.screens ? { screens: input.screens } : {}),
|
|
@@ -43,6 +47,57 @@ class AiResource {
|
|
|
43
47
|
signal: options.signal,
|
|
44
48
|
});
|
|
45
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* The signed-in user's past conversations in your application, most recent
|
|
52
|
+
* first.
|
|
53
|
+
*
|
|
54
|
+
* `asUser` is required rather than optional here, unlike on `chat`: the rows
|
|
55
|
+
* are scoped to a person, and there is no application-wide view of them to
|
|
56
|
+
* fall back to. Connect reads the user and the workspace from the token.
|
|
57
|
+
*
|
|
58
|
+
* Cursor-paginated with no total - the list is ordered by last use, which
|
|
59
|
+
* moves while it is being read.
|
|
60
|
+
*/
|
|
61
|
+
listConversations(input) {
|
|
62
|
+
const query = new URLSearchParams();
|
|
63
|
+
if (input.limit !== undefined)
|
|
64
|
+
query.set("limit", String(input.limit));
|
|
65
|
+
if (input.cursor)
|
|
66
|
+
query.set("cursor", input.cursor);
|
|
67
|
+
const suffix = query.size > 0 ? `?${query.toString()}` : "";
|
|
68
|
+
return (0, http_js_1.request)(this.transport, {
|
|
69
|
+
method: "GET",
|
|
70
|
+
path: `/ai/conversations${suffix}`,
|
|
71
|
+
headers: (0, acting_as_js_1.actingAs)(input.asUser),
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* One stored transcript, oldest turn first.
|
|
76
|
+
*
|
|
77
|
+
* `turns[].parts` comes back exactly as the model produced it - prose,
|
|
78
|
+
* reasoning and tool calls in order - so it can be handed straight back to a
|
|
79
|
+
* chat UI. Not this user's, or not your application's, is a `404` either way.
|
|
80
|
+
*/
|
|
81
|
+
getConversation(input) {
|
|
82
|
+
return (0, http_js_1.request)(this.transport, {
|
|
83
|
+
method: "GET",
|
|
84
|
+
path: `/ai/conversations/${encodeURIComponent(input.conversationId)}`,
|
|
85
|
+
headers: (0, acting_as_js_1.actingAs)(input.asUser),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Deletes a conversation and every turn beneath it.
|
|
90
|
+
*
|
|
91
|
+
* Idempotent - one already gone answers `{ deleted: true }`, so a retry after
|
|
92
|
+
* a dropped response does not read as a failure.
|
|
93
|
+
*/
|
|
94
|
+
deleteConversation(input) {
|
|
95
|
+
return (0, http_js_1.request)(this.transport, {
|
|
96
|
+
method: "DELETE",
|
|
97
|
+
path: `/ai/conversations/${encodeURIComponent(input.conversationId)}`,
|
|
98
|
+
headers: (0, acting_as_js_1.actingAs)(input.asUser),
|
|
99
|
+
});
|
|
100
|
+
}
|
|
46
101
|
/** Extract structured JSON from a file or image URL, against a platform extraction schema referenced by id. */
|
|
47
102
|
async extract(input) {
|
|
48
103
|
const result = await (0, http_js_1.request)(this.transport, {
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useEffect, useState } from "react";
|
|
4
|
+
import { Button } from "@heroui/react";
|
|
5
|
+
import { MessageSquare, Trash2 } from "lucide-react";
|
|
6
|
+
import { useConnect } from "../provider.js";
|
|
7
|
+
/** Bridge paths, spelled once - the list is read and invalidated from three places. */
|
|
8
|
+
const LIST_PATH = "/ai/conversations";
|
|
9
|
+
const detailPath = (id) => `/ai/conversation?id=${encodeURIComponent(id)}`;
|
|
10
|
+
/**
|
|
11
|
+
* Past Ask AI conversations, for reopening or deleting.
|
|
12
|
+
*
|
|
13
|
+
* ## It fetches only while it is open
|
|
14
|
+
*
|
|
15
|
+
* `<ConnectAskAi>` is mounted for the whole application shell, so an
|
|
16
|
+
* unconditional read here would put a request on every page load to populate a
|
|
17
|
+
* list most people never open. It reads on open, and again whenever the panel
|
|
18
|
+
* has written a new conversation since - which is what `refreshKey` is for.
|
|
19
|
+
*
|
|
20
|
+
* ## Deletion confirms inline, not in a dialog
|
|
21
|
+
*
|
|
22
|
+
* Destructive actions confirm; this one does it at the weight it deserves.
|
|
23
|
+
* Losing a transcript is recoverable by asking again, not a cancelled
|
|
24
|
+
* subscription, and a modal over a 400px panel would be heavier than the thing
|
|
25
|
+
* it guards. The row swaps to "Delete? / Cancel" and stays there until
|
|
26
|
+
* answered.
|
|
27
|
+
*/
|
|
28
|
+
export function AskAiHistory({ refreshKey, activeConversationId, onOpenConversation, }) {
|
|
29
|
+
const { fetchResource, mutateResource, invalidateResource } = useConnect();
|
|
30
|
+
const [conversations, setConversations] = useState(null);
|
|
31
|
+
const [error, setError] = useState(null);
|
|
32
|
+
const [confirmingId, setConfirmingId] = useState(null);
|
|
33
|
+
const [busyId, setBusyId] = useState(null);
|
|
34
|
+
useEffect(() => {
|
|
35
|
+
let active = true;
|
|
36
|
+
// The cached entry is dropped first. This component mounts only when the
|
|
37
|
+
// user asks for the list, and the provider's cache would otherwise hand
|
|
38
|
+
// them the copy taken before the last three questions they asked.
|
|
39
|
+
invalidateResource(LIST_PATH);
|
|
40
|
+
fetchResource(LIST_PATH)
|
|
41
|
+
.then((page) => {
|
|
42
|
+
if (!active)
|
|
43
|
+
return;
|
|
44
|
+
setConversations(page.conversations);
|
|
45
|
+
setError(null);
|
|
46
|
+
})
|
|
47
|
+
.catch((cause) => {
|
|
48
|
+
if (!active)
|
|
49
|
+
return;
|
|
50
|
+
// An empty list rather than a permanent skeleton: the error is shown
|
|
51
|
+
// beside it, and a panel stuck loading says nothing at all.
|
|
52
|
+
setConversations([]);
|
|
53
|
+
setError(cause instanceof Error ? cause.message : "Could not load your conversations");
|
|
54
|
+
});
|
|
55
|
+
return () => {
|
|
56
|
+
active = false;
|
|
57
|
+
};
|
|
58
|
+
}, [fetchResource, invalidateResource, refreshKey]);
|
|
59
|
+
const open = async (id) => {
|
|
60
|
+
setBusyId(id);
|
|
61
|
+
try {
|
|
62
|
+
const detail = await fetchResource(detailPath(id));
|
|
63
|
+
onOpenConversation(id, detail);
|
|
64
|
+
}
|
|
65
|
+
catch (cause) {
|
|
66
|
+
setError(cause instanceof Error ? cause.message : "Could not open that conversation");
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
setBusyId(null);
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
const remove = async (id) => {
|
|
73
|
+
setBusyId(id);
|
|
74
|
+
// Removed from the list before the response lands. The confirmation was the
|
|
75
|
+
// decision point, and a row that lingers while the request flies reads as a
|
|
76
|
+
// press that did not take - so the list is patched and put back on failure.
|
|
77
|
+
const previous = conversations;
|
|
78
|
+
setConversations((current) => current?.filter((row) => row.id !== id) ?? null);
|
|
79
|
+
setConfirmingId(null);
|
|
80
|
+
try {
|
|
81
|
+
await mutateResource(detailPath(id), undefined, "DELETE");
|
|
82
|
+
invalidateResource(LIST_PATH);
|
|
83
|
+
}
|
|
84
|
+
catch (cause) {
|
|
85
|
+
setConversations(previous);
|
|
86
|
+
setError(cause instanceof Error ? cause.message : "Could not delete that conversation");
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
setBusyId(null);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
if (conversations === null) {
|
|
93
|
+
return (_jsx("div", { className: "space-y-2 p-4", "aria-busy": "true", children: [0, 1, 2].map((row) => (_jsx("div", { className: "h-9 animate-pulse rounded-md bg-surface-secondary" }, row))) }));
|
|
94
|
+
}
|
|
95
|
+
if (conversations.length === 0) {
|
|
96
|
+
return (_jsx("div", { className: "p-4", children: error ? (_jsx("p", { className: "text-xs text-danger", children: error })) : (_jsx("p", { className: "text-center text-xs text-muted", children: "Nothing here yet. Conversations you have are saved automatically." })) }));
|
|
97
|
+
}
|
|
98
|
+
return (_jsxs("div", { className: "p-2", children: [error && _jsx("p", { className: "px-2 pb-2 text-xs text-danger", children: error }), _jsx("ul", { className: "space-y-0.5", children: conversations.map((conversation) => {
|
|
99
|
+
const isConfirming = confirmingId === conversation.id;
|
|
100
|
+
const isActive = conversation.id === activeConversationId;
|
|
101
|
+
return (_jsx("li", { children: isConfirming ? (_jsxs("div", { className: "flex items-center gap-2 rounded-md border border-border px-2 py-1.5", children: [_jsx("span", { className: "flex-1 truncate text-xs text-muted", children: "Delete this conversation?" }), _jsx(Button, { size: "sm", variant: "danger", className: "h-7 px-2 text-xs", isDisabled: busyId === conversation.id, onPress: () => void remove(conversation.id), children: "Delete" }), _jsx(Button, { size: "sm", variant: "tertiary", className: "h-7 px-2 text-xs", onPress: () => setConfirmingId(null), children: "Cancel" })] })) : (_jsxs("div", { className: `group flex items-center gap-1 rounded-md ${isActive ? "bg-surface-secondary" : ""}`, children: [_jsxs(Button, { variant: "ghost", className: "h-auto min-w-0 flex-1 justify-start gap-2 px-2 py-1.5 text-start", isDisabled: busyId === conversation.id, onPress: () => void open(conversation.id), children: [_jsx(MessageSquare, { className: "size-3.5 shrink-0 text-muted" }), _jsx("span", { className: "min-w-0 flex-1 truncate text-xs font-normal", children: conversation.title })] }), _jsx(Button, { isIconOnly: true, size: "sm", variant: "ghost", className: "shrink-0", "aria-label": `Delete "${conversation.title}"`, onPress: () => setConfirmingId(conversation.id), children: _jsx(Trash2, { className: "size-3.5 text-muted" }) })] })) }, conversation.id));
|
|
102
|
+
}) })] }));
|
|
103
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Index of the final text block, or `-1`. A reverse loop rather than
|
|
3
|
+
* `findLastIndex`, which is ES2023 - this package targets ES2022 so its
|
|
4
|
+
* published output stays usable on the runtimes its `engines` field claims.
|
|
5
|
+
*/
|
|
6
|
+
export function lastTextBlockIndex(blocks) {
|
|
7
|
+
for (let index = blocks.length - 1; index >= 0; index--) {
|
|
8
|
+
if (blocks[index]?.kind === "text")
|
|
9
|
+
return index;
|
|
10
|
+
}
|
|
11
|
+
return -1;
|
|
12
|
+
}
|
|
13
|
+
/** Appends a text delta to the open text block, or opens one after a widget. */
|
|
14
|
+
export function appendText(blocks, text) {
|
|
15
|
+
const last = blocks.at(-1);
|
|
16
|
+
if (last?.kind === "text") {
|
|
17
|
+
return [...blocks.slice(0, -1), { kind: "text", text: last.text + text }];
|
|
18
|
+
}
|
|
19
|
+
return [...blocks, { kind: "text", text }];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Rebuilds the panel's turns from a stored transcript.
|
|
23
|
+
*
|
|
24
|
+
* The inverse of what the stream reader does live, and it has to agree with it
|
|
25
|
+
* or a reopened conversation renders differently from the one the user just
|
|
26
|
+
* had. Two shapes, one source: the stream delivers `text-delta`,
|
|
27
|
+
* `reasoning-delta` and `tool-input-available` frames, and storage keeps the
|
|
28
|
+
* settled `UIMessage` parts those frames built - `{ type: "text" }`,
|
|
29
|
+
* `{ type: "reasoning" }`, and `{ type: "tool-<name>" }` carrying the input the
|
|
30
|
+
* widget was drawn from.
|
|
31
|
+
*
|
|
32
|
+
* Three rules, each of which is a thing that would otherwise render wrong:
|
|
33
|
+
*
|
|
34
|
+
* - **A tool part with no input is dropped, not restored.** `input: null` means
|
|
35
|
+
* "still arriving" to the renderer, which draws a skeleton - correct live,
|
|
36
|
+
* and a shimmer that never resolves on a transcript that finished days ago.
|
|
37
|
+
* - **Reasoning is hoisted per turn**, not left in place. It is rendered above
|
|
38
|
+
* the answer in a disclosure, which is where it sat while streaming.
|
|
39
|
+
* - **A part this build cannot place is skipped rather than guessed at.**
|
|
40
|
+
* `parts` is the AI SDK's own shape and gains kinds over time; an unknown one
|
|
41
|
+
* costs a widget, and inventing a rendering for it costs the whole turn.
|
|
42
|
+
*/
|
|
43
|
+
export function turnsFromStored(turns) {
|
|
44
|
+
return turns.map((turn) => {
|
|
45
|
+
let blocks = [];
|
|
46
|
+
let reasoning = "";
|
|
47
|
+
for (const raw of turn.parts) {
|
|
48
|
+
const part = raw;
|
|
49
|
+
if (typeof part?.type !== "string")
|
|
50
|
+
continue;
|
|
51
|
+
if (part.type === "text") {
|
|
52
|
+
if (typeof part.text === "string" && part.text.length > 0) {
|
|
53
|
+
blocks = appendText(blocks, part.text);
|
|
54
|
+
}
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (part.type === "reasoning") {
|
|
58
|
+
if (typeof part.text === "string")
|
|
59
|
+
reasoning += part.text;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (part.type.startsWith("tool-")) {
|
|
63
|
+
// See the note above: an absent input is a skeleton forever.
|
|
64
|
+
if (part.input === undefined || part.input === null)
|
|
65
|
+
continue;
|
|
66
|
+
blocks = [
|
|
67
|
+
...blocks,
|
|
68
|
+
{
|
|
69
|
+
kind: "tool",
|
|
70
|
+
// The stored call id when there is one. Falling back to the block's
|
|
71
|
+
// position keeps React keys unique within the turn, which is all
|
|
72
|
+
// this id is used for once the turn is settled.
|
|
73
|
+
id: typeof part.toolCallId === "string" ? part.toolCallId : `${turn.id}-${blocks.length}`,
|
|
74
|
+
name: part.type.slice("tool-".length),
|
|
75
|
+
input: part.input,
|
|
76
|
+
},
|
|
77
|
+
];
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return { id: turn.id, role: turn.role, blocks, reasoning };
|
|
81
|
+
});
|
|
82
|
+
}
|
|
@@ -1,13 +1,37 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
3
|
-
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
4
4
|
import { Button, Input, Label, TextField } from "@heroui/react";
|
|
5
|
-
import { Brain, ChevronDown, Send, Sparkles, Square, X } from "lucide-react";
|
|
6
|
-
import { Streamdown } from "streamdown";
|
|
5
|
+
import { Brain, ChevronDown, History, Plus, Send, Sparkles, Square, X } from "lucide-react";
|
|
7
6
|
import { useConnect } from "../provider.js";
|
|
7
|
+
/**
|
|
8
|
+
* The markdown renderer, fetched the first time there is markdown to render.
|
|
9
|
+
*
|
|
10
|
+
* `streamdown` is **462 KB** of the host's client bundle, and a static import
|
|
11
|
+
* here put all of it on every page of every application platform that mounts
|
|
12
|
+
* `ConnectAppShell` - which is every page, because the shell owns the layout.
|
|
13
|
+
* It rendered nothing until somebody opened the assistant, which most page
|
|
14
|
+
* views never do. Measured on one partner app: 48 of 49 routes carrying it,
|
|
15
|
+
* about a quarter of each route's JavaScript.
|
|
16
|
+
*
|
|
17
|
+
* `lazy` rather than a conditional `import()` in an effect: React caches the
|
|
18
|
+
* module promise, so the chunk is requested once no matter how many messages
|
|
19
|
+
* render, and the boundary below is what covers the gap.
|
|
20
|
+
*
|
|
21
|
+
* The fallback is the **raw text**, not a spinner. An answer streams in token
|
|
22
|
+
* by token, and unformatted prose is readable - so the first words appear
|
|
23
|
+
* while the renderer is still arriving rather than behind it. Once it lands,
|
|
24
|
+
* the same text re-renders as markdown.
|
|
25
|
+
*/
|
|
26
|
+
const Streamdown = lazy(async () => {
|
|
27
|
+
const mod = await import("streamdown");
|
|
28
|
+
return { default: mod.Streamdown };
|
|
29
|
+
});
|
|
8
30
|
import { useActivePath } from "../use-active-path.js";
|
|
9
31
|
import { matchConnectScreen } from "./ai-screens.js";
|
|
10
32
|
import { AiActions, AiChart, AiDetails, AiMetrics, AiSources, AiSteps, AiTable, AiTimeline } from "./ai-widgets.js";
|
|
33
|
+
import { AskAiHistory } from "./ask-ai-history.js";
|
|
34
|
+
import { appendText, lastTextBlockIndex, turnsFromStored, } from "./ask-ai-turns.js";
|
|
11
35
|
/**
|
|
12
36
|
* The panel's open width. The *inner* pane always carries it, so the content
|
|
13
37
|
* keeps its layout while the outer shell's width animates to zero around it.
|
|
@@ -167,26 +191,6 @@ async function readStream(response, onChunk) {
|
|
|
167
191
|
}
|
|
168
192
|
}
|
|
169
193
|
}
|
|
170
|
-
/**
|
|
171
|
-
* Index of the final text block, or `-1`. A reverse loop rather than
|
|
172
|
-
* `findLastIndex`, which is ES2023 - this package targets ES2022 so its
|
|
173
|
-
* published output stays usable on the runtimes its `engines` field claims.
|
|
174
|
-
*/
|
|
175
|
-
function lastTextBlockIndex(blocks) {
|
|
176
|
-
for (let index = blocks.length - 1; index >= 0; index--) {
|
|
177
|
-
if (blocks[index]?.kind === "text")
|
|
178
|
-
return index;
|
|
179
|
-
}
|
|
180
|
-
return -1;
|
|
181
|
-
}
|
|
182
|
-
/** Appends a text delta to the open text block, or opens one after a widget. */
|
|
183
|
-
function appendText(blocks, text) {
|
|
184
|
-
const last = blocks.at(-1);
|
|
185
|
-
if (last?.kind === "text") {
|
|
186
|
-
return [...blocks.slice(0, -1), { kind: "text", text: last.text + text }];
|
|
187
|
-
}
|
|
188
|
-
return [...blocks, { kind: "text", text }];
|
|
189
|
-
}
|
|
190
194
|
/**
|
|
191
195
|
* Ask AI - a chat panel grounded in the signed-in workspace's Context Index,
|
|
192
196
|
* streamed through your own bridge.
|
|
@@ -235,6 +239,31 @@ export function ConnectAskAi({ title = "Ask AI", assistantName = "Assistant", pl
|
|
|
235
239
|
const [input, setInput] = useState("");
|
|
236
240
|
const [isBusy, setIsBusy] = useState(false);
|
|
237
241
|
const [error, setError] = useState(null);
|
|
242
|
+
const [showHistory, setShowHistory] = useState(false);
|
|
243
|
+
/**
|
|
244
|
+
* The conversation being written to.
|
|
245
|
+
*
|
|
246
|
+
* Generated here, before the first message, because the server cannot hand
|
|
247
|
+
* one back: it is streaming a response, and there is no point in that stream
|
|
248
|
+
* at which a new id could reach the browser ahead of the first token. So the
|
|
249
|
+
* client picks it and Connect upserts - safe because ownership is checked
|
|
250
|
+
* rather than assumed, and an id naming somebody else's conversation is
|
|
251
|
+
* refused.
|
|
252
|
+
*
|
|
253
|
+
* Lazily initialised rather than computed in a `useMemo`: this has to survive
|
|
254
|
+
* re-renders and change only when the user starts a new conversation, which
|
|
255
|
+
* is precisely what `useMemo` does not promise.
|
|
256
|
+
*/
|
|
257
|
+
const [conversationId, setConversationId] = useState(() => newConversationId());
|
|
258
|
+
/**
|
|
259
|
+
* Bumped whenever a turn has been written, so the history list re-reads the
|
|
260
|
+
* next time it is opened.
|
|
261
|
+
*
|
|
262
|
+
* A counter rather than a refetch call, because the list is unmounted while
|
|
263
|
+
* closed - there is nothing to tell. It is *why* the list re-reads, not the
|
|
264
|
+
* list itself.
|
|
265
|
+
*/
|
|
266
|
+
const [writeCount, setWriteCount] = useState(0);
|
|
238
267
|
const abortRef = useRef(null);
|
|
239
268
|
const bottomRef = useRef(null);
|
|
240
269
|
// Ids only have to be unique within one mounted conversation, so a counter is
|
|
@@ -257,11 +286,11 @@ export function ConnectAskAi({ title = "Ask AI", assistantName = "Assistant", pl
|
|
|
257
286
|
*/
|
|
258
287
|
const resolvedPath = useActivePath(activePath);
|
|
259
288
|
const currentScreen = useMemo(() => (resolvedPath ? matchConnectScreen(screens, resolvedPath) : null), [screens, resolvedPath]);
|
|
260
|
-
const renderMarkdown = useCallback((text, isStreaming = false) => (_jsx(Streamdown, { className: "connect-ai-body", mode: isStreaming ? "streaming" : "static", isAnimating: isStreaming, animated: ANIMATED, caret: isStreaming ? "block" : undefined, plugins: markdownPlugins,
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
289
|
+
const renderMarkdown = useCallback((text, isStreaming = false) => (_jsx(Suspense, { fallback: _jsx("div", { className: "connect-ai-body whitespace-pre-wrap", children: text }), children: _jsx(Streamdown, { className: "connect-ai-body", mode: isStreaming ? "streaming" : "static", isAnimating: isStreaming, animated: ANIMATED, caret: isStreaming ? "block" : undefined, plugins: markdownPlugins,
|
|
290
|
+
// Retrieved documents cite real URLs; an interstitial on every one of
|
|
291
|
+
// them turns a citation into a chore. The renderer still sanitises the
|
|
292
|
+
// markup itself, which is the part that matters.
|
|
293
|
+
linkSafety: LINK_SAFETY, children: text }) })), [markdownPlugins]);
|
|
265
294
|
const stop = useCallback(() => {
|
|
266
295
|
abortRef.current?.abort();
|
|
267
296
|
abortRef.current = null;
|
|
@@ -309,6 +338,11 @@ export function ConnectAskAi({ title = "Ask AI", assistantName = "Assistant", pl
|
|
|
309
338
|
// decide what anyone may do. See `ConnectScreen`.
|
|
310
339
|
...(resolvedPath ? { screenContext: { pathname: resolvedPath } } : {}),
|
|
311
340
|
...(screens.length > 0 ? { screens } : {}),
|
|
341
|
+
// What makes the conversation resumable. Connect stores the turn
|
|
342
|
+
// against it and `<AskAiHistory>` reads it back; a turn sent
|
|
343
|
+
// without one is answered exactly the same way and remembered by
|
|
344
|
+
// nobody.
|
|
345
|
+
conversationId,
|
|
312
346
|
}, { signal: controller.signal });
|
|
313
347
|
// The assistant's turn is appended only once the stream is live, so a
|
|
314
348
|
// failed request leaves an error under the question rather than an
|
|
@@ -345,8 +379,41 @@ export function ConnectAskAi({ title = "Ask AI", assistantName = "Assistant", pl
|
|
|
345
379
|
if (abortRef.current === controller)
|
|
346
380
|
abortRef.current = null;
|
|
347
381
|
setIsBusy(false);
|
|
382
|
+
// Even on an aborted or failed turn: the user's own question has
|
|
383
|
+
// already been persisted by the time anything can go wrong downstream
|
|
384
|
+
// of it, so the list is stale either way.
|
|
385
|
+
setWriteCount((count) => count + 1);
|
|
348
386
|
}
|
|
349
|
-
}, [streamResource, turns]);
|
|
387
|
+
}, [streamResource, turns, conversationId]);
|
|
388
|
+
/**
|
|
389
|
+
* Clears the transcript and starts writing into a fresh conversation.
|
|
390
|
+
*
|
|
391
|
+
* The old one is not deleted - it is in History, which is the whole point.
|
|
392
|
+
*/
|
|
393
|
+
const startNewConversation = useCallback(() => {
|
|
394
|
+
abortRef.current?.abort();
|
|
395
|
+
abortRef.current = null;
|
|
396
|
+
setIsBusy(false);
|
|
397
|
+
setTurns([]);
|
|
398
|
+
setError(null);
|
|
399
|
+
setShowHistory(false);
|
|
400
|
+
setConversationId(newConversationId());
|
|
401
|
+
}, []);
|
|
402
|
+
/**
|
|
403
|
+
* Replaces the transcript with a stored one, and continues writing into it.
|
|
404
|
+
*
|
|
405
|
+
* Writing continues into the conversation that was opened rather than forking
|
|
406
|
+
* a new one, which is what makes "come back to this tomorrow" work at all.
|
|
407
|
+
*/
|
|
408
|
+
const openConversation = useCallback((id, detail) => {
|
|
409
|
+
abortRef.current?.abort();
|
|
410
|
+
abortRef.current = null;
|
|
411
|
+
setIsBusy(false);
|
|
412
|
+
setError(null);
|
|
413
|
+
setTurns(turnsFromStored(detail.turns));
|
|
414
|
+
setConversationId(id);
|
|
415
|
+
setShowHistory(false);
|
|
416
|
+
}, []);
|
|
350
417
|
const lastTurn = turns.at(-1);
|
|
351
418
|
const isAnswering = isBusy && lastTurn?.role === "assistant";
|
|
352
419
|
const rendered = useMemo(() => turns.map((turn) => {
|
|
@@ -368,9 +435,34 @@ export function ConnectAskAi({ title = "Ask AI", assistantName = "Assistant", pl
|
|
|
368
435
|
if (!text || isBusy)
|
|
369
436
|
return;
|
|
370
437
|
setInput("");
|
|
438
|
+
// Typing sends you back to the conversation: staying on the history list
|
|
439
|
+
// while an answer streams behind it would hide the thing just asked for.
|
|
440
|
+
setShowHistory(false);
|
|
371
441
|
void send(text);
|
|
372
442
|
};
|
|
373
|
-
return (_jsxs(_Fragment, { children: [!isOpen && (_jsx(Button, { isIconOnly: true, variant: "primary", "aria-label": title, onPress: () => setIsOpen(true), className: "fixed bottom-4 end-4 z-30 size-12 rounded-full shadow-lg sm:bottom-6 sm:end-6", children: _jsx(Sparkles, { className: "size-5" }) })), _jsx("div", { className: `fixed inset-0 z-40 bg-backdrop transition-opacity lg:hidden ${isOpen ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"}`, onClick: () => setIsOpen(false), "aria-hidden": "true" }), _jsx("aside", { "aria-hidden": !isOpen, className: `fixed inset-y-0 end-0 z-50 flex flex-col border-s border-border bg-surface shadow-xl transition-transform duration-300 ease-in-out ${panelShellWidth(isOpen)} ${isOpen ? "translate-x-0" : "translate-x-full rtl:-translate-x-full"} lg:static lg:z-auto lg:translate-x-0 lg:shadow-none lg:transition-[width]`, children: _jsxs("div", { className: `flex h-full shrink-0 flex-col ${PANEL_WIDTH}`, children: [_jsxs("div", { className: "flex items-center gap-2 border-b border-border px-4 py-3", children: [_jsx(Sparkles, { className: "size-4 shrink-0 text-accent" }), _jsx("span", { className: "flex-1 text-sm font-semibold", children: title }), _jsx(Button, { isIconOnly: true, size: "sm", variant: "tertiary", "aria-label": "
|
|
443
|
+
return (_jsxs(_Fragment, { children: [!isOpen && (_jsx(Button, { isIconOnly: true, variant: "primary", "aria-label": title, onPress: () => setIsOpen(true), className: "fixed bottom-4 end-4 z-30 size-12 rounded-full shadow-lg sm:bottom-6 sm:end-6", children: _jsx(Sparkles, { className: "size-5" }) })), _jsx("div", { className: `fixed inset-0 z-40 bg-backdrop transition-opacity lg:hidden ${isOpen ? "pointer-events-auto opacity-100" : "pointer-events-none opacity-0"}`, onClick: () => setIsOpen(false), "aria-hidden": "true" }), _jsx("aside", { "aria-hidden": !isOpen, className: `fixed inset-y-0 end-0 z-50 flex flex-col border-s border-border bg-surface shadow-xl transition-transform duration-300 ease-in-out ${panelShellWidth(isOpen)} ${isOpen ? "translate-x-0" : "translate-x-full rtl:-translate-x-full"} lg:static lg:z-auto lg:translate-x-0 lg:shadow-none lg:transition-[width]`, children: _jsxs("div", { className: `flex h-full shrink-0 flex-col ${PANEL_WIDTH}`, children: [_jsxs("div", { className: "flex items-center gap-2 border-b border-border px-4 py-3", children: [_jsx(Sparkles, { className: "size-4 shrink-0 text-accent" }), _jsx("span", { className: "flex-1 text-sm font-semibold", children: title }), _jsx(Button, { isIconOnly: true, size: "sm", variant: "tertiary", "aria-label": "New conversation",
|
|
444
|
+
// Disabled on an empty one rather than hidden: a control that
|
|
445
|
+
// appears and disappears as you use the panel is harder to find
|
|
446
|
+
// than one that is always in the same place.
|
|
447
|
+
isDisabled: turns.length === 0, onPress: startNewConversation, children: _jsx(Plus, { className: "size-4" }) }), _jsx(Button, { isIconOnly: true, size: "sm", variant: "tertiary", "aria-label": showHistory ? "Hide past conversations" : "Past conversations", "aria-pressed": showHistory, onPress: () => setShowHistory((open) => !open), children: _jsx(History, { className: "size-4" }) }), _jsx(Button, { isIconOnly: true, size: "sm", variant: "tertiary", "aria-label": "Close", onPress: () => setIsOpen(false), children: _jsx(X, { className: "size-4" }) })] }), showHistory ? (_jsx("div", { className: "min-h-0 flex-1 overflow-y-auto", children: _jsx(AskAiHistory, { refreshKey: writeCount, activeConversationId: conversationId, onOpenConversation: openConversation }) })) : (_jsxs("div", { className: "flex-1 space-y-3 overflow-y-auto p-4", children: [turns.length === 0 && (_jsxs("div", { className: "space-y-3", children: [_jsx("p", { className: "text-sm text-muted", children: hint }), currentScreen?.suggestions?.length ? (_jsx("div", { className: "flex flex-wrap gap-1.5", children: currentScreen.suggestions.map((suggestion) => (_jsx(Button, { size: "sm", variant: "secondary", className: "h-auto rounded-full px-2.5 py-1 text-start text-xs whitespace-normal", isDisabled: isBusy, onPress: () => void send(suggestion), children: suggestion }, suggestion))) })) : null] })), rendered, isBusy && lastTurn?.role === "user" && (_jsxs("div", { className: "rounded-md border border-border bg-accent/5 p-2.5 text-sm", children: [_jsx("p", { className: "mb-1 text-[11px] font-semibold tracking-wide text-muted uppercase", children: assistantName }), _jsx(ThinkingShimmer, {})] })), error && _jsx("p", { className: "text-xs text-danger", children: error }), _jsx("div", { ref: bottomRef })] })), _jsxs("form", { onSubmit: handleSubmit, className: "flex gap-2 border-t border-border p-3", children: [_jsxs(TextField, { variant: "secondary", className: "flex-1", children: [_jsx(Label, { className: "sr-only", children: placeholder }), _jsx(Input, { placeholder: placeholder, value: input, onChange: (event) => setInput(event.currentTarget.value), disabled: isBusy })] }), isBusy ? (_jsx(Button, { type: "button", isIconOnly: true, variant: "secondary", "aria-label": "Stop generating", onPress: stop, children: _jsx(Square, { className: "size-3.5" }) })) : (_jsx(Button, { type: "submit", isIconOnly: true, variant: "primary", "aria-label": "Send", isDisabled: !input.trim(), children: _jsx(Send, { className: "size-3.5" }) }))] })] }) })] }));
|
|
374
448
|
}
|
|
375
449
|
/** Hoisted for the same reference-equality reason as `ANIMATED` - Streamdown compares it by identity. */
|
|
376
450
|
const LINK_SAFETY = { enabled: false };
|
|
451
|
+
/**
|
|
452
|
+
* A fresh conversation id.
|
|
453
|
+
*
|
|
454
|
+
* `crypto.randomUUID` where it exists, and it usually does - but it is gated on
|
|
455
|
+
* a *secure context*, so it is simply absent on an `http://` origin that is not
|
|
456
|
+
* localhost. That is somebody's LAN dev server or a staging box on a bare IP,
|
|
457
|
+
* and a panel that throws there rather than chatting would be a poor trade for
|
|
458
|
+
* four lines. The fallback is not cryptographically strong and does not need to
|
|
459
|
+
* be: the id selects among the caller's own conversations and grants nothing -
|
|
460
|
+
* Connect refuses one belonging to another user or another application - so its
|
|
461
|
+
* only real job is not to collide with itself.
|
|
462
|
+
*/
|
|
463
|
+
function newConversationId() {
|
|
464
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
465
|
+
return crypto.randomUUID();
|
|
466
|
+
}
|
|
467
|
+
return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
|
|
468
|
+
}
|
|
@@ -89,9 +89,9 @@ export function ConnectProvider({ clientId = "", basePath = "/api/connect", redi
|
|
|
89
89
|
cache.current.set(key, pending);
|
|
90
90
|
return pending;
|
|
91
91
|
}, [basePath, fetchImpl]);
|
|
92
|
-
const mutateResource = useCallback(async (path, body) => {
|
|
92
|
+
const mutateResource = useCallback(async (path, body, method = "POST") => {
|
|
93
93
|
const response = await (fetchImpl ?? globalThis.fetch)(`${basePath}${path}`, {
|
|
94
|
-
method
|
|
94
|
+
method,
|
|
95
95
|
credentials: "same-origin",
|
|
96
96
|
headers: {
|
|
97
97
|
accept: "application/json",
|