rift-ds 1.30.0 → 1.32.0

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.
Files changed (162) hide show
  1. package/README.md +6 -4
  2. package/behaviors/chat-card.css +4 -1
  3. package/behaviors/deferComponent.d.ts +43 -0
  4. package/behaviors/deferComponent.js +35 -0
  5. package/behaviors/locale.d.ts +7 -0
  6. package/behaviors/locale.js +5 -0
  7. package/behaviors/shell.css +33 -0
  8. package/bin/rift-ds.mjs +35 -9
  9. package/bin/templates/blocks/app/planner/PlannerGrid.tsx +58 -0
  10. package/bin/templates/blocks/app/planner/Requests.tsx +42 -0
  11. package/bin/templates/blocks/app/planner/page.module.css +17 -0
  12. package/bin/templates/blocks/app/planner/page.tsx +32 -0
  13. package/bin/templates/blocks/components/blocks/AppShell.module.css +10 -1
  14. package/bin/templates/blocks/registry.json +14 -0
  15. package/bin/templates/chat/app/api/chat/route.actions.ts +108 -0
  16. package/bin/templates/chat/components/chat/ChatMount.actions.tsx +55 -0
  17. package/bin/templates/chat/components/chat/ChatMount.tsx +14 -1
  18. package/bin/templates/chat/components/chat/proposals/ProposalCard.tsx +81 -0
  19. package/bin/templates/chat/components/chat/proposals/actions.ts +60 -0
  20. package/bin/templates/chat/components/chat/proposals/confirmation.ts +9 -0
  21. package/bin/templates/chat/components/chat/proposals/renderers.tsx +9 -0
  22. package/chat/ChatLauncher.d.ts +13 -2
  23. package/chat/ChatLauncher.js +52 -29
  24. package/chat/ChatProvider.d.ts +19 -2
  25. package/chat/ChatProvider.js +26 -3
  26. package/chat/ChatWidget.css +23 -4
  27. package/chat/ChatWidget.d.ts +2 -1
  28. package/chat/ChatWidget.js +23 -21
  29. package/chat/actions.d.ts +52 -6
  30. package/chat/actions.js +53 -5
  31. package/chat/contextSchema.d.ts +76 -0
  32. package/chat/contextSchema.js +58 -0
  33. package/chat/deferredChatWidget.d.ts +10 -0
  34. package/chat/deferredChatWidget.js +10 -0
  35. package/chat/index.d.ts +3 -2
  36. package/chat/index.js +7 -1
  37. package/chat/registry.json.d.ts +4 -3
  38. package/chat/registry.json.js +1 -1
  39. package/chat/server.d.ts +18 -2
  40. package/chat/server.js +10 -1
  41. package/chat/suggestions.d.ts +7 -0
  42. package/chat/suggestions.js +13 -1
  43. package/chat/types.d.ts +23 -0
  44. package/chat/useChat.d.ts +2 -2
  45. package/chat/useChat.js +15 -1
  46. package/components/Accordion/Accordion.css +8 -0
  47. package/components/AgentPlan/AgentPlan.css +8 -0
  48. package/components/AgentRail/AgentRail.css +3 -3
  49. package/components/AiButton/AiButton.css +19 -0
  50. package/components/AiButton/AiButton.d.ts +10 -1
  51. package/components/AiButton/AiButton.js +6 -1
  52. package/components/AppSidebar/AppSidebar.css +12 -0
  53. package/components/ArtifactPanel/ArtifactPanel.js +5 -5
  54. package/components/Attachment/AttachmentViewer.js +7 -7
  55. package/components/BentoTile/BentoTile.css +1 -1
  56. package/components/BentoTile/BentoTile.js +5 -5
  57. package/components/Button/Button.css +28 -1
  58. package/components/Button/Button.d.ts +7 -2
  59. package/components/Button/Button.js +7 -3
  60. package/components/ButtonGroup/ButtonGroup.css +10 -1
  61. package/components/Chart/RadarChart.js +24 -10
  62. package/components/ChatHeader/ChatHeader.d.ts +1 -1
  63. package/components/ChatThread/ChatThread.css +1 -1
  64. package/components/Chip/Chip.css +26 -0
  65. package/components/CircularButton/CircularButton.d.ts +16 -96
  66. package/components/CircularButton/CircularButton.js +11 -94
  67. package/components/Combobox/Combobox.css +12 -0
  68. package/components/CommandPalette/CommandPalette.css +1 -1
  69. package/components/CommandPalette/CommandPalette.js +3 -3
  70. package/components/CommandPaletteTrigger/CommandPaletteTrigger.css +9 -0
  71. package/components/CommandPaletteTrigger/CommandPaletteTrigger.d.ts +10 -2
  72. package/components/CommandPaletteTrigger/CommandPaletteTrigger.js +7 -2
  73. package/components/Composer/Composer.css +3 -3
  74. package/components/Composer/Composer.js +9 -9
  75. package/components/ContextMenu/ContextMenu.css +24 -0
  76. package/components/DataTable/DataTable.css +19 -4
  77. package/components/DataTable/DataTable.d.ts +14 -2
  78. package/components/DataTable/DataTable.js +28 -17
  79. package/components/DataTable/periodColumns.d.ts +37 -0
  80. package/components/DataTable/periodColumns.js +48 -0
  81. package/components/DateInput/DateInput.css +20 -0
  82. package/components/DatePicker/DatePicker.css +22 -6
  83. package/components/DatePicker/DatePicker.d.ts +2 -1
  84. package/components/DatePicker/DatePicker.js +2 -2
  85. package/components/DateRangePicker/DateRangePicker.js +2 -2
  86. package/components/DecisionRow/DecisionRow.css +46 -0
  87. package/components/DecisionRow/DecisionRow.d.ts +62 -0
  88. package/components/DecisionRow/DecisionRow.js +93 -0
  89. package/components/DescriptionList/DescriptionListCopy.d.ts +1 -1
  90. package/components/DescriptionList/DescriptionListCopy.js +3 -3
  91. package/components/Dialog/Dialog.css +1 -1
  92. package/components/Dialog/Dialog.js +3 -3
  93. package/components/DocumentChip/DocumentChip.css +12 -0
  94. package/components/DocumentViewer/DocumentViewer.js +10 -10
  95. package/components/Drawer/Drawer.css +1 -1
  96. package/components/Drawer/Drawer.js +3 -3
  97. package/components/Dropdown/Dropdown.css +30 -0
  98. package/components/DropdownMenu/DropdownMenu.css +24 -0
  99. package/components/EventCalendar/EventCalendar.css +54 -0
  100. package/components/EventCalendar/EventCalendar.d.ts +27 -5
  101. package/components/EventCalendar/EventCalendar.js +50 -15
  102. package/components/FileInput/FileInput.css +9 -0
  103. package/components/FilterBar/FilterBar.css +12 -0
  104. package/components/FunnelChart/FunnelChart.js +33 -22
  105. package/components/Globe/Globe.css +7 -0
  106. package/components/Globe/Globe.js +1 -1
  107. package/components/{CircularButton/CircularButton.css → IconButton/IconButton.css} +91 -81
  108. package/components/IconButton/IconButton.d.ts +108 -0
  109. package/components/IconButton/IconButton.js +101 -0
  110. package/components/Input/Input.css +53 -0
  111. package/components/Input/Input.js +3 -3
  112. package/components/MaskedInput/MaskedInput.js +3 -3
  113. package/components/ModelPicker/ModelPicker.css +12 -1
  114. package/components/NavList/NavList.css +1 -1
  115. package/components/Pagination/Pagination.css +1 -1
  116. package/components/QuestionCard/QuestionCard.js +3 -3
  117. package/components/RadioButton/RadioButton.css +14 -12
  118. package/components/RichDropdown/RichDropdown.css +7 -0
  119. package/components/SegmentedControl/SegmentedControl.css +16 -5
  120. package/components/SegmentedControl/SegmentedControl.js +7 -4
  121. package/components/SiteHeader/SiteHeader.css +12 -5
  122. package/components/SiteHeader/SiteHeader.js +3 -3
  123. package/components/SourceTrail/SourceTrail.css +8 -0
  124. package/components/SplitButton/SplitButton.css +14 -14
  125. package/components/SplitButton/SplitButton.js +3 -3
  126. package/components/Table/Table.css +7 -0
  127. package/components/Table/Table.js +1 -1
  128. package/components/TableToolbar/TableToolbar.css +2 -2
  129. package/components/TableToolbar/TableToolbar.js +36 -37
  130. package/components/Tabs/Tabs.css +21 -3
  131. package/components/ThreadPanel/ThreadPanel.css +8 -0
  132. package/components/ThreadTabs/ThreadTabs.css +7 -0
  133. package/components/TimePicker/TimePicker.css +12 -0
  134. package/components/Timeline/Timeline.css +8 -0
  135. package/components/ToolCall/ToolCall.css +8 -0
  136. package/components/Tooltip/Tooltip.js +3 -2
  137. package/components/Widget/Widget.css +2 -0
  138. package/components/WorldMap/WorldMap.css +15 -0
  139. package/components/WorldMap/WorldMap.js +61 -6
  140. package/components/registry.d.ts +3 -1
  141. package/components/registry.json +39 -13
  142. package/components/registry.json.d.ts +39 -13
  143. package/components/registry.json.js +1 -1
  144. package/index.d.ts +2 -0
  145. package/index.js +8 -0
  146. package/package.json +6 -2
  147. package/tokens/presets/blueprint.css +9 -0
  148. package/tokens/presets/bubblegum.css +9 -0
  149. package/tokens/presets/contrast.css +3 -3
  150. package/tokens/presets/coral.css +3 -3
  151. package/tokens/presets/ember.css +9 -0
  152. package/tokens/presets/getaway.css +9 -0
  153. package/tokens/presets/gold.css +3 -3
  154. package/tokens/presets/mono.css +3 -3
  155. package/tokens/presets/pink.css +3 -3
  156. package/tokens/presets/plum.css +3 -3
  157. package/tokens/presets/signal.css +9 -0
  158. package/tokens/presets/smoke.css +9 -0
  159. package/tokens/presets/velvet.css +9 -0
  160. package/tokens/presets/violet.css +3 -3
  161. package/tokens/presets/volt.css +9 -0
  162. package/tokens/presets/warm.css +3 -3
@@ -8,7 +8,7 @@ import { ChatHeader } from "../components/ChatHeader/ChatHeader.js";
8
8
  import { DocumentChip } from "../components/DocumentChip/DocumentChip.js";
9
9
  import { ChatMessage } from "../components/ChatMessage/ChatMessage.js";
10
10
  import { ChatThread } from "../components/ChatThread/ChatThread.js";
11
- import { CircularButton } from "../components/CircularButton/CircularButton.js";
11
+ import { IconButton } from "../components/IconButton/IconButton.js";
12
12
  import { PixelAvatar } from "../components/PixelAvatar/PixelAvatar.js";
13
13
  import { Composer } from "../components/Composer/Composer.js";
14
14
  import { DropdownMenu } from "../components/DropdownMenu/DropdownMenu.js";
@@ -27,7 +27,7 @@ import { useChatWidget, ArtifactSeatContext } from "./context.js";
27
27
  import { DEFAULT_GREETING_COPY, subscribeClock, greetingFor, serverGreeting } from "./greeting.js";
28
28
  import { CHAT_PLACEMENTS, chatPlacement } from "./placement.js";
29
29
  import { ASIDE_WITH_THREADS_MIN_WIDTH, THREADS_RAIL_MIN_WIDTH, ARTIFACT_MIN_COLUMN_WIDTH, ASIDE_RAIL_MIN_WIDTH } from "./queries.js";
30
- import { fitsChip } from "./suggestions.js";
30
+ import { keepFittingSuggestions } from "./suggestions.js";
31
31
  import { TurnCard } from "./TurnContent.js";
32
32
  import { isBlockingQuestion } from "./questions.js";
33
33
  import { ReplyBody } from "./TurnQuestion.js";
@@ -199,7 +199,7 @@ function ChatWidget({
199
199
  () => greetingFor((/* @__PURE__ */ new Date()).getHours(), greetingCopy),
200
200
  serverGreeting
201
201
  );
202
- const starters = (startersInput ?? []).filter((starter) => fitsChip(starter.label));
202
+ const starters = keepFittingSuggestions(startersInput ?? [], (starter) => starter.label, "ChatWidget starters");
203
203
  const composerRef = useRef(null);
204
204
  const focusComposer = () => composerRef.current?.focus({ preventScroll: true });
205
205
  useEffect(() => {
@@ -279,6 +279,7 @@ function ChatWidget({
279
279
  const [artifactEmptyOpen, setArtifactEmptyOpen] = useState(false);
280
280
  const [artifactExpandedWanted, setArtifactExpanded] = useState(false);
281
281
  const wasAsideWideRef = useRef(true);
282
+ const [seatMeasured, setSeatMeasured] = useState(false);
282
283
  useEffect(() => {
283
284
  if (!hasRails) return;
284
285
  const host = railsHostRef.current;
@@ -298,6 +299,7 @@ function ChatWidget({
298
299
  closeArtifact();
299
300
  }
300
301
  wasAsideWideRef.current = asideRoom;
302
+ setSeatMeasured(true);
301
303
  };
302
304
  measure();
303
305
  const observer = new ResizeObserver(measure);
@@ -454,11 +456,11 @@ function ChatWidget({
454
456
  const actionCount = Number(showNewChat) + Number(Boolean(renderAside)) + Number(artifacts) + Number(placementEnabled) + Number(fullscreenEnabled) + Number(closeEnabled);
455
457
  const headerActions = /* @__PURE__ */ jsxs(Fragment, { children: [
456
458
  showNewChat && /* @__PURE__ */ jsx(
457
- CircularButton,
459
+ IconButton,
458
460
  {
459
461
  icon: "edit_square",
460
462
  variant: "tertiary",
461
- ariaLabel: newChatLabel,
463
+ label: newChatLabel,
462
464
  tooltipPosition: "bottom",
463
465
  onClick: () => {
464
466
  reset();
@@ -468,12 +470,12 @@ function ChatWidget({
468
470
  }
469
471
  ),
470
472
  renderAside && /* @__PURE__ */ jsx(
471
- CircularButton,
473
+ IconButton,
472
474
  {
473
475
  icon: /* @__PURE__ */ jsx(PixelAvatar, { name: title, size: "sm" }),
474
476
  variant: "tertiary",
475
477
  className: asideShown ? "ds-chat-widget__agent-toggle--on" : void 0,
476
- ariaLabel: asideShown ? hideAgentLabel : showAgentLabel,
478
+ label: asideShown ? hideAgentLabel : showAgentLabel,
477
479
  tooltipPosition: "bottom",
478
480
  "aria-expanded": asideShown,
479
481
  "aria-controls": asideShown ? asideId : void 0,
@@ -481,12 +483,12 @@ function ChatWidget({
481
483
  }
482
484
  ),
483
485
  artifacts && /* @__PURE__ */ jsx(
484
- CircularButton,
486
+ IconButton,
485
487
  {
486
488
  icon: artifactShown ? "right_panel_close" : "right_panel_open",
487
489
  variant: "tertiary",
488
490
  className: artifactShown ? "ds-chat-widget__agent-toggle--on" : void 0,
489
- ariaLabel: artifactShown ? hideArtifactLabel : showArtifactLabel,
491
+ label: artifactShown ? hideArtifactLabel : showArtifactLabel,
490
492
  tooltipPosition: "bottom",
491
493
  "aria-expanded": artifactShown,
492
494
  "aria-controls": artifactShown ? artifactId : void 0,
@@ -502,11 +504,11 @@ function ChatWidget({
502
504
  {
503
505
  align: "end",
504
506
  trigger: /* @__PURE__ */ jsx(
505
- CircularButton,
507
+ IconButton,
506
508
  {
507
509
  icon: chatPlacement(placement).icon,
508
510
  variant: "tertiary",
509
- ariaLabel: placementLabel,
511
+ label: placementLabel,
510
512
  tooltipPosition: "bottom",
511
513
  disabled: isFull
512
514
  }
@@ -526,21 +528,21 @@ function ChatWidget({
526
528
  }
527
529
  ) }),
528
530
  fullscreenEnabled && /* @__PURE__ */ jsx(
529
- CircularButton,
531
+ IconButton,
530
532
  {
531
533
  icon: isFull ? "close_fullscreen" : "open_in_full",
532
534
  variant: "tertiary",
533
- ariaLabel: isFull ? exitFullscreenLabel : enterFullscreenLabel,
535
+ label: isFull ? exitFullscreenLabel : enterFullscreenLabel,
534
536
  tooltipPosition: "bottom",
535
537
  onClick: () => setView(isFull ? "panel" : "full")
536
538
  }
537
539
  ),
538
540
  closeEnabled && /* @__PURE__ */ jsx(
539
- CircularButton,
541
+ IconButton,
540
542
  {
541
543
  icon: "close",
542
544
  variant: "tertiary",
543
- ariaLabel: closeLabel,
545
+ label: closeLabel,
544
546
  tooltipPosition: "bottom",
545
547
  onClick: () => setOpen(false)
546
548
  }
@@ -601,11 +603,11 @@ function ChatWidget({
601
603
  {
602
604
  title: /* @__PURE__ */ jsxs("span", { className: "ds-chat-widget__brand", children: [
603
605
  renderThreads && !threadsInline && /* @__PURE__ */ jsx(
604
- CircularButton,
606
+ IconButton,
605
607
  {
606
608
  icon: "menu",
607
609
  variant: "tertiary",
608
- ariaLabel: openThreadsLabel,
610
+ label: openThreadsLabel,
609
611
  tooltipPosition: "bottom",
610
612
  onClick: () => setThreadsOpen(true)
611
613
  }
@@ -806,7 +808,7 @@ function ChatWidget({
806
808
  artifacts && !asideWide && /* @__PURE__ */ jsxs(
807
809
  "div",
808
810
  {
809
- className: `ds-chat-widget__aside-overlay ${artifactShown ? "ds-chat-widget__aside-overlay--open" : ""}`,
811
+ className: `ds-chat-widget__aside-overlay ${artifactShown && seatMeasured ? "ds-chat-widget__aside-overlay--open" : ""}`,
810
812
  children: [
811
813
  /* @__PURE__ */ jsx(
812
814
  "button",
@@ -814,7 +816,7 @@ function ChatWidget({
814
816
  type: "button",
815
817
  className: "ds-chat-widget__rail-scrim",
816
818
  "aria-label": closeArtifactLabel,
817
- tabIndex: artifactShown ? 0 : -1,
819
+ tabIndex: artifactShown && seatMeasured ? 0 : -1,
818
820
  onClick: closeArtifactPanel
819
821
  }
820
822
  ),
@@ -864,7 +866,7 @@ function ChatWidget({
864
866
  renderAside && !asideWide && /* @__PURE__ */ jsxs(
865
867
  "div",
866
868
  {
867
- className: `ds-chat-widget__aside-overlay ${asideShown ? "ds-chat-widget__aside-overlay--open" : ""}`,
869
+ className: `ds-chat-widget__aside-overlay ${asideShown && seatMeasured ? "ds-chat-widget__aside-overlay--open" : ""}`,
868
870
  children: [
869
871
  /* @__PURE__ */ jsx(
870
872
  "button",
@@ -872,7 +874,7 @@ function ChatWidget({
872
874
  type: "button",
873
875
  className: "ds-chat-widget__rail-scrim",
874
876
  "aria-label": closeAgentLabel,
875
- tabIndex: asideShown ? 0 : -1,
877
+ tabIndex: asideShown && seatMeasured ? 0 : -1,
876
878
  onClick: closeAside
877
879
  }
878
880
  ),
package/chat/actions.d.ts CHANGED
@@ -25,7 +25,16 @@
25
25
  * the route rebuilds the mark from the request (`sanitiseConfirmation`), and
26
26
  * the model is told whether this message was confirmed on its card
27
27
  * (`confirmationLine`). A typed "yes, cancel them" carries no mark.
28
+ *
29
+ * A change can also be a sequence: several different actions in order, where
30
+ * each one acts on the records as the ones before it left them ("close the
31
+ * open items, then archive the closed ones"). `planSequence` dry-runs the
32
+ * steps in turn over one set of records, and the reader confirms the whole
33
+ * sequence once; its confirmation carries each step (`confirmSequence`), and
34
+ * `confirmationLine` tells the model all of them, in order. A single action
35
+ * is a sequence of one.
28
36
  */
37
+ export { defineContext, type ContextField, type ContextShape, type ContextValues, type ContextSchema } from './contextSchema';
29
38
  export interface ChatAction<Values, Edit = Partial<Values>> {
30
39
  /** A stable id the server and the page share. */
31
40
  id: string;
@@ -61,12 +70,42 @@ export declare function planAction<Values>(action: ChatAction<Values, unknown>,
61
70
  id: string;
62
71
  values: Values;
63
72
  }[]): ActionPlan;
64
- /** A change the reader confirmed on its card: which action, how many records it changed, and their ids. */
65
- export interface ActionConfirmation<Id extends string = string> {
73
+ /** One step of a sequence: an action, and the records it is meant for. */
74
+ export interface SequenceStep<Values> {
75
+ action: ChatAction<Values, unknown>;
76
+ /** The records this step means, by id. A record the sequence was not handed is ignored. */
77
+ ids: readonly string[];
78
+ }
79
+ /** What a sequence would do: each step's plan, in order, worked out over the records as the steps before it left them. */
80
+ export interface SequencePlan {
81
+ steps: ActionPlan[];
82
+ }
83
+ /**
84
+ * The dry run of a sequence. Each step is planned over the records as the
85
+ * earlier steps would leave them, so a step that depends on the one before
86
+ * it (archive what the first step closed) counts the right records. Changes
87
+ * nothing: the writes are simulated on copies.
88
+ */
89
+ export declare function planSequence<Values extends object>(steps: readonly SequenceStep<Values>[], records: {
90
+ id: string;
91
+ values: Values;
92
+ }[]): SequencePlan;
93
+ /** One confirmed step: which action, how many records it changed, and their ids. */
94
+ export interface ConfirmedStep<Id extends string = string> {
66
95
  action: Id;
67
96
  count: number;
68
97
  ids: string[];
69
98
  }
99
+ /**
100
+ * A change the reader confirmed on its card: which action, how many records it
101
+ * changed, and their ids. A confirmed sequence carries every step in `steps`,
102
+ * in order, with the first step's action and the total count at the top.
103
+ */
104
+ export interface ActionConfirmation<Id extends string = string> extends ConfirmedStep<Id> {
105
+ steps?: ConfirmedStep<Id>[];
106
+ }
107
+ /** The confirmation for a sequence plan, ready to mark: its steps, the first step's action, the total count. Steps that change nothing are left out; null when none change anything. */
108
+ export declare function confirmSequence<Id extends string = string>(plan: SequencePlan, maxIds?: number): ActionConfirmation<Id> | null;
70
109
  /** The page's one-shot mark: set on Confirm, read once by the next request, then gone. */
71
110
  export interface ConfirmationMark<Id extends string = string> {
72
111
  /** Marks the request about to carry the reader's confirmation. */
@@ -85,14 +124,21 @@ export interface SanitiseConfirmationOptions {
85
124
  maxCount: number;
86
125
  /** The most ids kept. Defaults to 50. */
87
126
  maxIds?: number;
127
+ /** The most steps a confirmed sequence may carry. Defaults to 10. */
128
+ maxSteps?: number;
88
129
  }
89
- /** The confirmation a request claims, rebuilt as untrusted input: a known action, a count in range, real ids only. Null for none. */
90
- export declare function sanitiseConfirmation(value: unknown, { actions, isId, maxCount, maxIds }: SanitiseConfirmationOptions): ActionConfirmation | null;
130
+ /**
131
+ * The confirmation a request claims, rebuilt as untrusted input: a known
132
+ * action, a count in range, real ids only. A sequence's steps are each held
133
+ * to the same rules, and one bad step drops the whole claim, so the model is
134
+ * never told part of a sequence was confirmed. Null for none.
135
+ */
136
+ export declare function sanitiseConfirmation(value: unknown, { actions, isId, maxCount, maxIds, maxSteps }: SanitiseConfirmationOptions): ActionConfirmation | null;
91
137
  export interface ConfirmationLineOptions {
92
138
  /** The actions a confirmation may name, by id, for the words that say what was done. */
93
139
  actions: Record<string, Pick<ChatAction<never, unknown>, 'done'>>;
94
- /** The records' noun for a count: "order" for one, "orders" for more. */
95
- noun: (count: number) => string;
140
+ /** The records' noun for a count: "order" for one, "orders" for more. Handed the step's action id too, for a sequence whose steps act on different records. */
141
+ noun: (count: number, action: string) => string;
96
142
  /** The locale the count is written in. */
97
143
  locale?: string;
98
144
  }
package/chat/actions.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { DEFAULT_LOCALE } from "../behaviors/locale.js";
2
+ import { defineContext } from "./contextSchema.js";
2
3
  const defineAction = (action) => action;
3
4
  function planAction(action, records) {
4
5
  const ids = [];
@@ -10,6 +11,33 @@ function planAction(action, records) {
10
11
  }
11
12
  return { action: action.id, ids, skipped };
12
13
  }
14
+ function planSequence(steps, records) {
15
+ const current = new Map(records.map((record) => [record.id, record.values]));
16
+ return {
17
+ steps: steps.map(({ action, ids }) => {
18
+ const meant = ids.flatMap((id) => {
19
+ const values = current.get(id);
20
+ return values ? [{ id, values }] : [];
21
+ });
22
+ const plan = planAction(action, meant);
23
+ for (const id of plan.ids) {
24
+ const values = current.get(id);
25
+ current.set(id, { ...values, ...action.apply(values) });
26
+ }
27
+ return plan;
28
+ })
29
+ };
30
+ }
31
+ function confirmSequence(plan, maxIds = 50) {
32
+ const steps = plan.steps.filter((step) => step.ids.length > 0).map((step) => ({ action: step.action, count: step.ids.length, ids: step.ids.slice(0, maxIds) }));
33
+ if (!steps.length) return null;
34
+ return {
35
+ action: steps[0].action,
36
+ count: steps.reduce((total, step) => total + step.count, 0),
37
+ ids: [...new Set(steps.flatMap((step) => step.ids))].slice(0, maxIds),
38
+ steps
39
+ };
40
+ }
13
41
  function createConfirmationMark() {
14
42
  let pending = null;
15
43
  return {
@@ -23,25 +51,45 @@ function createConfirmationMark() {
23
51
  }
24
52
  };
25
53
  }
26
- function sanitiseConfirmation(value, { actions, isId, maxCount, maxIds = 50 }) {
54
+ function sanitiseStep(value, known, isId, maxCount, maxIds) {
27
55
  const { action, count, ids } = value ?? {};
28
- const known = Array.isArray(actions) ? actions : Object.keys(actions);
29
56
  if (typeof action !== "string" || !known.includes(action)) return null;
30
57
  if (typeof count !== "number" || !Number.isFinite(count) || count < 1 || count > maxCount) return null;
31
58
  const kept = Array.isArray(ids) ? ids.filter((id) => typeof id === "string" && isId(id)) : [];
32
59
  return { action, count: Math.floor(count), ids: [...new Set(kept)].slice(0, maxIds) };
33
60
  }
61
+ function sanitiseConfirmation(value, { actions, isId, maxCount, maxIds = 50, maxSteps = 10 }) {
62
+ const known = Array.isArray(actions) ? actions : Object.keys(actions);
63
+ const top = sanitiseStep(value, known, isId, maxCount, maxIds);
64
+ if (!top) return null;
65
+ const rawSteps = value.steps;
66
+ if (rawSteps === void 0) return top;
67
+ if (!Array.isArray(rawSteps) || rawSteps.length < 1 || rawSteps.length > maxSteps) return null;
68
+ const steps = rawSteps.map((step) => sanitiseStep(step, known, isId, maxCount, maxIds));
69
+ if (steps.some((step) => step === null)) return null;
70
+ return { ...top, steps };
71
+ }
34
72
  function confirmationLine(confirmation, { actions, noun, locale = DEFAULT_LOCALE }) {
35
- const action = confirmation ? actions[confirmation.action] : void 0;
36
- if (!confirmation || !action) return "This message was not confirmed on a card. Nothing it says has changed anything.";
37
- return `This message was confirmed on its card: ${confirmation.count.toLocaleString(locale)} ${noun(confirmation.count)} ${action.done}. The change is made.`;
73
+ const none = "This message was not confirmed on a card. Nothing it says has changed anything.";
74
+ if (!confirmation) return none;
75
+ const steps = confirmation.steps ?? [confirmation];
76
+ const said = steps.map((step) => {
77
+ const action = actions[step.action];
78
+ return action ? `${step.count.toLocaleString(locale)} ${noun(step.count, step.action)} ${action.done}` : null;
79
+ });
80
+ if (said.some((line) => line === null)) return none;
81
+ if (steps.length === 1) return `This message was confirmed on its card: ${said[0]}. The change is made.`;
82
+ return `This message was confirmed on its card, a sequence of ${steps.length} steps, made in this order: ${said.join("; then ")}. Every step is made.`;
38
83
  }
39
84
  const skippedText = (skipped, locale = DEFAULT_LOCALE) => Object.entries(skipped).map(([reason, count]) => `${count.toLocaleString(locale)} ${reason}`).join(", ");
40
85
  export {
86
+ confirmSequence,
41
87
  confirmationLine,
42
88
  createConfirmationMark,
43
89
  defineAction,
90
+ defineContext,
44
91
  planAction,
92
+ planSequence,
45
93
  sanitiseConfirmation,
46
94
  skippedText
47
95
  };
@@ -0,0 +1,76 @@
1
+ /**
2
+ * A chat's context as a small, declared shape, shared by the page that writes
3
+ * it and the route that reads it.
4
+ *
5
+ * The default context is the page path alone, because the context lands in a
6
+ * system block and anything the browser sends is untrusted. A host whose
7
+ * state lives in the browser (the tab that is open, the record in view, the
8
+ * filter a table holds) needs to say more than a path, and the safe way to
9
+ * say more is to say only things that cannot carry an instruction: ids that
10
+ * match a pattern, words from a fixed list, numbers in a range, flags.
11
+ *
12
+ * `defineContext` takes that shape once. The page builds its context with
13
+ * `write` (handed to `getContext`), and the route passes `sanitise` as the
14
+ * handler's `sanitiseContext`. Whatever arrives, `sanitise` keeps only the
15
+ * fields the shape names and only the values each one allows, drops the
16
+ * rest without rejecting the request, and returns the kept fields as a JSON
17
+ * string, or null when nothing survives. `read` parses that string back for
18
+ * a tool. No dependencies, so a page and its route can both import it.
19
+ */
20
+ /** What one field of a context may hold. */
21
+ export type ContextField =
22
+ /** A same-site path: lowercase slug segments only. */
23
+ {
24
+ kind: 'path';
25
+ }
26
+ /** One word from a fixed list. */
27
+ | {
28
+ kind: 'oneOf';
29
+ values: readonly string[];
30
+ }
31
+ /** One id matching `pattern`. */
32
+ | {
33
+ kind: 'id';
34
+ pattern: RegExp;
35
+ }
36
+ /** Ids matching `pattern`, at most `max` of them (default 50). */
37
+ | {
38
+ kind: 'ids';
39
+ pattern: RegExp;
40
+ max?: number;
41
+ }
42
+ /** A finite number between `min` and `max`. */
43
+ | {
44
+ kind: 'number';
45
+ min?: number;
46
+ max?: number;
47
+ }
48
+ /** True or false. */
49
+ | {
50
+ kind: 'flag';
51
+ };
52
+ export type ContextShape = Record<string, ContextField>;
53
+ type FieldValue<F extends ContextField> = F extends {
54
+ kind: 'ids';
55
+ } ? string[] : F extends {
56
+ kind: 'number';
57
+ } ? number : F extends {
58
+ kind: 'flag';
59
+ } ? boolean : string;
60
+ /** The values a shape allows, every field optional. */
61
+ export type ContextValues<S extends ContextShape> = {
62
+ [K in keyof S]?: FieldValue<S[K]>;
63
+ };
64
+ export interface ContextSchema<S extends ContextShape> {
65
+ /** The shape, as given. */
66
+ shape: S;
67
+ /** The context string for these values, or null when there are none. What a page returns from `getContext`. */
68
+ write: (values: ContextValues<S>) => string | null;
69
+ /** The handler's `sanitiseContext`: only the fields and values the shape allows, as a JSON string, or null. */
70
+ sanitise: (raw: unknown) => string | null;
71
+ /** The sanitised string parsed back into values, for a tool or a system block. */
72
+ read: (context: string | null) => ContextValues<S>;
73
+ }
74
+ /** Declares a context shape once, for the page that writes it and the route that sanitises it. */
75
+ export declare function defineContext<S extends ContextShape>(shape: S): ContextSchema<S>;
76
+ export {};
@@ -0,0 +1,58 @@
1
+ const MAX_CONTEXT_CHARS = 4e3;
2
+ const MAX_ID_CHARS = 128;
3
+ const PATH = /^\/(?:[a-z0-9-]+(?:\/[a-z0-9-]+){0,7})?$/;
4
+ const isId = (pattern, value) => typeof value === "string" && value.length <= MAX_ID_CHARS && new RegExp(`^(?:${pattern.source})$`, pattern.flags.replace("g", "")).test(value);
5
+ function cleanField(field, value) {
6
+ switch (field.kind) {
7
+ case "path":
8
+ return typeof value === "string" && value.length <= 128 && PATH.test(value) ? value : void 0;
9
+ case "oneOf":
10
+ return typeof value === "string" && field.values.includes(value) ? value : void 0;
11
+ case "id":
12
+ return isId(field.pattern, value) ? value : void 0;
13
+ case "ids": {
14
+ if (!Array.isArray(value)) return void 0;
15
+ const kept = [...new Set(value.filter((item) => isId(field.pattern, item)))].slice(0, field.max ?? 50);
16
+ return kept.length ? kept : void 0;
17
+ }
18
+ case "number":
19
+ return typeof value === "number" && Number.isFinite(value) && (field.min === void 0 || value >= field.min) && (field.max === void 0 || value <= field.max) ? value : void 0;
20
+ case "flag":
21
+ return typeof value === "boolean" ? value : void 0;
22
+ }
23
+ }
24
+ function clean(shape, values) {
25
+ const kept = {};
26
+ if (typeof values !== "object" || values === null || Array.isArray(values)) return kept;
27
+ for (const [key, field] of Object.entries(shape)) {
28
+ const value = cleanField(field, values[key]);
29
+ if (value !== void 0) kept[key] = value;
30
+ }
31
+ return kept;
32
+ }
33
+ const encode = (values) => Object.keys(values).length ? JSON.stringify(values) : null;
34
+ function defineContext(shape) {
35
+ return {
36
+ shape,
37
+ write: (values) => encode(clean(shape, values)),
38
+ sanitise: (raw) => {
39
+ if (typeof raw !== "string" || raw.length > MAX_CONTEXT_CHARS) return null;
40
+ try {
41
+ return encode(clean(shape, JSON.parse(raw)));
42
+ } catch {
43
+ return null;
44
+ }
45
+ },
46
+ read: (context) => {
47
+ if (!context) return {};
48
+ try {
49
+ return clean(shape, JSON.parse(context));
50
+ } catch {
51
+ return {};
52
+ }
53
+ }
54
+ };
55
+ }
56
+ export {
57
+ defineContext
58
+ };
@@ -0,0 +1,10 @@
1
+ import { ChatWidgetProps } from './ChatWidget';
2
+ export declare const DeferredChatWidget: import('../behaviors/deferComponent').DeferredComponent<ChatWidgetProps>;
3
+ /**
4
+ * Start loading the chat widget's code now. The launcher's own button calls
5
+ * it on hover and focus; a host that opens the chat from a control of its
6
+ * own (`fab={false}`) calls it from that control's `onPointerEnter` and
7
+ * `onFocus`, so its press finds the code already there. Safe to call any
8
+ * number of times.
9
+ */
10
+ export declare const preloadChatWidget: () => void;
@@ -0,0 +1,10 @@
1
+ "use client";
2
+ import { deferComponent } from "../behaviors/deferComponent.js";
3
+ const DeferredChatWidget = deferComponent(
4
+ () => import("./ChatWidget.js").then((module) => module.ChatWidget)
5
+ );
6
+ const preloadChatWidget = DeferredChatWidget.preload;
7
+ export {
8
+ DeferredChatWidget,
9
+ preloadChatWidget
10
+ };
package/chat/index.d.ts CHANGED
@@ -18,8 +18,9 @@ export { ChatWidget, type ChatWidgetProps, type ChatAgentOptions, type ChatBackd
18
18
  export { useSelectionFocus, useHeldHighlight, readSelection, describeSelection, CHAT_SOURCE_ATTRIBUTE, HELD_HIGHLIGHT_NAME, type SelectedText, type DescribeSelectionOptions } from './selection';
19
19
  export { sanitiseSelection, selectionLines, DEFAULT_SELECTION_LIMITS, type ChatSelection, type SelectionKind, type SelectionLimits, type SelectionLinesOptions } from './selectionContext';
20
20
  export { useGeneratedStarters, type GeneratedStarters, type GeneratedStartersOptions } from './generatedStarters';
21
- export { defineAction, planAction, skippedText, createConfirmationMark, sanitiseConfirmation, confirmationLine, type ChatAction, type ActionPlan, type ActionConfirmation, type ConfirmationMark, type SanitiseConfirmationOptions, type ConfirmationLineOptions, } from './actions';
21
+ export { defineAction, planAction, skippedText, createConfirmationMark, sanitiseConfirmation, confirmationLine, planSequence, confirmSequence, defineContext, type ChatAction, type ActionPlan, type ActionConfirmation, type ConfirmationMark, type SanitiseConfirmationOptions, type ConfirmationLineOptions, type SequenceStep, type SequencePlan, type ConfirmedStep, type ContextField, type ContextShape, type ContextValues, type ContextSchema, } from './actions';
22
22
  export { ChatLauncher, CHAT_PANEL_ID, type ChatLauncherProps } from './ChatLauncher';
23
+ export { preloadChatWidget } from './deferredChatWidget';
23
24
  export { useChatAgentState } from './agentState';
24
25
  export { ChatThreads, type ChatThreadsProps } from './ChatThreads';
25
26
  export { ChatTabs, type ChatTabsProps } from './ChatTabs';
@@ -39,5 +40,5 @@ export { STARTER_COUNT, pickStarters, namedStarter, hashString, mulberry32, } fr
39
40
  export { greetingFor, readGreeting, serverGreeting, subscribeClock, DEFAULT_GREETING_COPY, type GreetingCopy, } from './greeting';
40
41
  export { CHAT_PLACEMENTS, chatPlacement, DOCK_MIN_WIDTH, DOCK_MAX_WIDTH, DOCK_PAGE_MIN_WIDTH, dockFits, FLOAT_MAX_SCALE, FLOAT_EDGE_GAP, dockWidthFromDrag, isFloatDragStart, clampFloatPosition, type ChatPlacement, type ChatSide, } from './placement';
41
42
  export { artifactCard, cardArtifact } from './artifacts';
42
- export { ARTIFACT_CARD_KIND, CHAT_EVENT_KINDS, type ChatArtifact, type ChatCard, type ChatEvent, type ChatQuestion, type ChatQuestionAnswer, type ChatQuestionSet, type ChatReply, type ChatTransport, type ChatTransportMessage, type ChatTurn, type ChatModelOption, type ChatFeedbackVerdict, type LivePhase, type LiveResponse, type Starter, } from './types';
43
+ export { ARTIFACT_CARD_KIND, CHAT_EVENT_KINDS, type ChatArtifact, type ChatCard, type ChatEvent, type ChatQuestion, type ChatQuestionAnswer, type ChatQuestionSet, type ChatPageAction, type ChatReply, type ChatTransport, type ChatTransportMessage, type ChatTurn, type ChatModelOption, type ChatFeedbackVerdict, type LivePhase, type LiveResponse, type Starter, } from './types';
43
44
  export { chatWidget, chatWidgetRegistry, WIDGET_COUNT, type ChatWidgetMeta } from './registry';
package/chat/index.js CHANGED
@@ -3,8 +3,9 @@ import { ChatWidget } from "./ChatWidget.js";
3
3
  import { CHAT_SOURCE_ATTRIBUTE, HELD_HIGHLIGHT_NAME, describeSelection, readSelection, useHeldHighlight, useSelectionFocus } from "./selection.js";
4
4
  import { DEFAULT_SELECTION_LIMITS, sanitiseSelection, selectionLines } from "./selectionContext.js";
5
5
  import { useGeneratedStarters } from "./generatedStarters.js";
6
- import { confirmationLine, createConfirmationMark, defineAction, planAction, sanitiseConfirmation, skippedText } from "./actions.js";
6
+ import { confirmSequence, confirmationLine, createConfirmationMark, defineAction, planAction, planSequence, sanitiseConfirmation, skippedText } from "./actions.js";
7
7
  import { CHAT_PANEL_ID, ChatLauncher } from "./ChatLauncher.js";
8
+ import { preloadChatWidget } from "./deferredChatWidget.js";
8
9
  import { useChatAgentState } from "./agentState.js";
9
10
  import { ChatThreads } from "./ChatThreads.js";
10
11
  import { ChatTabs } from "./ChatTabs.js";
@@ -26,6 +27,7 @@ import { CHAT_PLACEMENTS, DOCK_MAX_WIDTH, DOCK_MIN_WIDTH, DOCK_PAGE_MIN_WIDTH, F
26
27
  import { artifactCard, cardArtifact } from "./artifacts.js";
27
28
  import { ARTIFACT_CARD_KIND, CHAT_EVENT_KINDS } from "./types.js";
28
29
  import { WIDGET_COUNT, chatWidget, chatWidgetRegistry } from "./registry.js";
30
+ import { defineContext } from "./contextSchema.js";
29
31
  export {
30
32
  ARTIFACT_CARD_KIND,
31
33
  ARTIFACT_MIN_COLUMN_WIDTH,
@@ -79,6 +81,7 @@ export {
79
81
  chatWidget,
80
82
  chatWidgetRegistry,
81
83
  clampFloatPosition,
84
+ confirmSequence,
82
85
  confirmationLine,
83
86
  createConfirmationMark,
84
87
  createFeedbackPoster,
@@ -87,6 +90,7 @@ export {
87
90
  createSimTransport,
88
91
  defaultFilesReply,
89
92
  defineAction,
93
+ defineContext,
90
94
  describeAnswers,
91
95
  describeSelection,
92
96
  dockFits,
@@ -103,6 +107,8 @@ export {
103
107
  pickFallbackFollowups,
104
108
  pickStarters,
105
109
  planAction,
110
+ planSequence,
111
+ preloadChatWidget,
106
112
  readGreeting,
107
113
  readSelection,
108
114
  sanitiseConfirmation,
@@ -10,8 +10,8 @@ declare const _default: {
10
10
  "command": "init chat",
11
11
  "subpaths": {
12
12
  "./chat": "The widget, the provider, the launcher and the engine under them, with the hooks that let it follow the reader and write starters for what they picked.",
13
- "./chat/server": "The streaming chat handler, with an opt-in tool for asking the visitor questions, its follow-ups, starters and feedback siblings, and the checks for what a reader highlighted, for any web-standard route.",
14
- "./chat/actions": "The action definitions a page and its route share, their dry run and the mark that says a change was confirmed on its card, with no dependencies.",
13
+ "./chat/server": "The streaming chat handler, with an opt-in tool for asking the visitor questions, the cards a reply opens with, the page actions a tool returns, its follow-ups, starters and feedback siblings, and the checks for what a reader highlighted, for any web-standard route.",
14
+ "./chat/actions": "The action definitions a page and its route share, their dry run alone or in a sequence, the mark that says a change was confirmed on its card, and the declared shape of a page's context, with no dependencies.",
15
15
  "./chat/upstash": "Rate limits, a daily budget and the exchange log over Upstash Redis, as the handlers' guardrails.",
16
16
  "./chat/demo": "A scripted conversation with rich cards and fixtures, for a preview that needs no key.",
17
17
  "./chat/chat.css": "The widget's stylesheet."
@@ -43,7 +43,7 @@ declare const _default: {
43
43
  "ChatHeader",
44
44
  "ChatMessage",
45
45
  "ChatThread",
46
- "CircularButton",
46
+ "IconButton",
47
47
  "CodeBlock",
48
48
  "Composer",
49
49
  "DocumentChip",
@@ -56,6 +56,7 @@ declare const _default: {
56
56
  "Prose",
57
57
  "QuestionCard",
58
58
  "Reasoning",
59
+ "Spinner",
59
60
  "ThreadPanel",
60
61
  "ThreadTabs"
61
62
  ],
@@ -1,5 +1,5 @@
1
1
  const $comment = "The widget registry: the fourth kind of thing the package ships, between the components and the templates. One member by design. `parts` names the library components the widget composes (held to src/components/registry.json by scripts/validate-chat-widget.mjs), `subpaths` the package exports it occupies (held to scripts/package-manifest.mjs), `category` the component category whose section and sidebar group its page joins (held to src/components/registry.json), `peers` the optional peer dependencies each subpath needs (held to package.json). The widget's page under /components, the /docs/chat page, the chat corpus and the MCP tools read this file; never type its facts elsewhere.";
2
- const widgets = [{ "name": "ChatWidget", "slug": "ai-chat", "label": "AI chat", "category": "ai", "description": "The whole AI chat: the panel, or the page itself in an app shell mode, the streaming replies, the history, the cards and questions a reply can carry and the server handlers, set up with props.", "command": "init chat", "subpaths": { "./chat": "The widget, the provider, the launcher and the engine under them, with the hooks that let it follow the reader and write starters for what they picked.", "./chat/server": "The streaming chat handler, with an opt-in tool for asking the visitor questions, its follow-ups, starters and feedback siblings, and the checks for what a reader highlighted, for any web-standard route.", "./chat/actions": "The action definitions a page and its route share, their dry run and the mark that says a change was confirmed on its card, with no dependencies.", "./chat/upstash": "Rate limits, a daily budget and the exchange log over Upstash Redis, as the handlers' guardrails.", "./chat/demo": "A scripted conversation with rich cards and fixtures, for a preview that needs no key.", "./chat/chat.css": "The widget's stylesheet." }, "peers": { "./chat": ["react-markdown", "remark-gfm"], "./chat/server": ["@anthropic-ai/sdk"], "./chat/upstash": ["@upstash/ratelimit", "@upstash/redis"], "./chat/demo": ["recharts"] }, "parts": ["AgentRail", "AgentStatus", "AiButton", "ArtifactCard", "ArtifactPanel", "AttachmentDropZone", "AttachmentGroup", "ChatHeader", "ChatMessage", "ChatThread", "CircularButton", "CodeBlock", "Composer", "DocumentChip", "DropdownMenu", "EmptyState", "Mention", "ModelPicker", "PixelAvatar", "PromptSuggestions", "Prose", "QuestionCard", "Reasoning", "ThreadPanel", "ThreadTabs"], "documented": ["ChatWidget", "ChatProvider", "ChatLauncher", "ChatThreads", "ChatTabs", "ChatAgentPane", "ChatArtifactPane", "ChatArtifactCard"] }];
2
+ const widgets = [{ "name": "ChatWidget", "slug": "ai-chat", "label": "AI chat", "category": "ai", "description": "The whole AI chat: the panel, or the page itself in an app shell mode, the streaming replies, the history, the cards and questions a reply can carry and the server handlers, set up with props.", "command": "init chat", "subpaths": { "./chat": "The widget, the provider, the launcher and the engine under them, with the hooks that let it follow the reader and write starters for what they picked.", "./chat/server": "The streaming chat handler, with an opt-in tool for asking the visitor questions, the cards a reply opens with, the page actions a tool returns, its follow-ups, starters and feedback siblings, and the checks for what a reader highlighted, for any web-standard route.", "./chat/actions": "The action definitions a page and its route share, their dry run alone or in a sequence, the mark that says a change was confirmed on its card, and the declared shape of a page's context, with no dependencies.", "./chat/upstash": "Rate limits, a daily budget and the exchange log over Upstash Redis, as the handlers' guardrails.", "./chat/demo": "A scripted conversation with rich cards and fixtures, for a preview that needs no key.", "./chat/chat.css": "The widget's stylesheet." }, "peers": { "./chat": ["react-markdown", "remark-gfm"], "./chat/server": ["@anthropic-ai/sdk"], "./chat/upstash": ["@upstash/ratelimit", "@upstash/redis"], "./chat/demo": ["recharts"] }, "parts": ["AgentRail", "AgentStatus", "AiButton", "ArtifactCard", "ArtifactPanel", "AttachmentDropZone", "AttachmentGroup", "ChatHeader", "ChatMessage", "ChatThread", "IconButton", "CodeBlock", "Composer", "DocumentChip", "DropdownMenu", "EmptyState", "Mention", "ModelPicker", "PixelAvatar", "PromptSuggestions", "Prose", "QuestionCard", "Reasoning", "Spinner", "ThreadPanel", "ThreadTabs"], "documented": ["ChatWidget", "ChatProvider", "ChatLauncher", "ChatThreads", "ChatTabs", "ChatAgentPane", "ChatArtifactPane", "ChatArtifactCard"] }];
3
3
  const registry = {
4
4
  $comment,
5
5
  widgets