@robosystems/core 0.15.1 → 0.17.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.
@@ -9,6 +9,15 @@ import { useStreamingQuery } from '../../hooks';
9
9
  import { emitGraphWrites, readGraphWrites, } from '../../lib/graph-writes';
10
10
  import { ConsoleMarkdown } from './ConsoleMarkdown';
11
11
  import { ProgressiveText } from './ProgressiveText';
12
+ // A conversation's id, minted here and sent with every question in it; the
13
+ // server records each run under it. Any URL-safe token under 64 characters.
14
+ function mintThreadId() {
15
+ if (typeof crypto !== 'undefined' &&
16
+ typeof crypto.randomUUID === 'function') {
17
+ return crypto.randomUUID();
18
+ }
19
+ return `thr_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
20
+ }
12
21
  function generateMessageId() {
13
22
  return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
14
23
  }
@@ -94,6 +103,13 @@ export function ConsoleContent({ config, variant = 'page', }) {
94
103
  // Moves on at every graph switch, so a switch away and back (A → B → A)
95
104
  // still retires a request made before it.
96
105
  const graphEpochRef = useRef(0);
106
+ // The scope a request made now belongs to; true once the console has left it.
107
+ const leftScope = () => {
108
+ const requestGraphId = graphId;
109
+ const requestEpoch = graphEpochRef.current;
110
+ return () => currentGraphRef.current !== requestGraphId ||
111
+ graphEpochRef.current !== requestEpoch;
112
+ };
97
113
  // Terminal state
98
114
  const [terminalMessages, setTerminalMessages] = useState([]);
99
115
  const [commandInput, setCommandInput] = useState('');
@@ -101,10 +117,14 @@ export function ConsoleContent({ config, variant = 'page', }) {
101
117
  const [historyIndex, setHistoryIndex] = useState(-1);
102
118
  const terminalEndRef = useRef(null);
103
119
  const terminalScrollRef = useRef(null);
104
- // Prior operator exchanges, sent as `history` so a follow-up like "and for
105
- // June?" resolves against the previous answer. Bounded to the last three
106
- // exchanges — the backend seeds only its last five turns anyway.
107
- const conversationRef = useRef([]);
120
+ // The conversation the operator questions belong to. Minted on the first
121
+ // question, sent with every one after it, so a follow-up like "and for
122
+ // June?" resolves against the previous answers: the server seeds the run
123
+ // from the thread's own record. Null until a question is asked, and reset
124
+ // by /clear and by a graph switch.
125
+ const threadRef = useRef(null);
126
+ // The threads /history last listed, so /resume <n> can name one.
127
+ const listedThreadsRef = useRef([]);
108
128
  const [currentQueryStartTime, setCurrentQueryStartTime] = useState(null);
109
129
  const [apiVersion, setApiVersion] = useState(null);
110
130
  const [operatorProgress, setOperatorProgress] = useState({ isRunning: false, message: '' });
@@ -137,7 +157,9 @@ export function ConsoleContent({ config, variant = 'page', }) {
137
157
  ` /mcp - Connect an MCP client (sign in — no key)\n` +
138
158
  ` /mcp key - Mint a graph-scoped API key for header-only clients\n` +
139
159
  ` /help - Show this help message\n` +
140
- ` /clear - Clear console history\n` +
160
+ ` /history - List your recent conversations on this graph\n` +
161
+ ` /resume <n> - Continue a listed conversation\n` +
162
+ ` /clear - Clear the console and start a new conversation\n` +
141
163
  ` /examples - Show example queries`;
142
164
  const extraLines = ((_a = config.extraCommands) !== null && _a !== void 0 ? _a : [])
143
165
  .map((ec) => ` ${ec.command.padEnd(12)}- Custom command`)
@@ -243,7 +265,7 @@ export function ConsoleContent({ config, variant = 'page', }) {
243
265
  setTerminalMessages([]);
244
266
  // A follow-up on the new graph must not resolve against the previous
245
267
  // graph's answers.
246
- conversationRef.current = [];
268
+ threadRef.current = null;
247
269
  setCurrentQueryStartTime(null);
248
270
  addSystemMessage(`═══════════════════════════════════════════════════════════════\n` +
249
271
  `${config.welcome.contextLabel} context changed: ${fromGraphId} → ${graphId}\n` +
@@ -365,7 +387,7 @@ export function ConsoleContent({ config, variant = 'page', }) {
365
387
  // `operatorType` names an operator (`author` for /do); unset, the API
366
388
  // chooses one for a question.
367
389
  const executeOperatorQuery = async (userQuery, operatorType) => {
368
- var _a;
390
+ var _a, _b;
369
391
  if (!graphId) {
370
392
  addErrorMessage(config.noSelectionError);
371
393
  return;
@@ -383,11 +405,15 @@ export function ConsoleContent({ config, variant = 'page', }) {
383
405
  graphEpochRef.current !== requestEpoch;
384
406
  try {
385
407
  const { clients } = await import('@robosystems/client/clients');
386
- const history = conversationRef.current;
387
- const request = Object.assign({ message: userQuery,
408
+ const threadId = (_a = threadRef.current) !== null && _a !== void 0 ? _a : mintThreadId();
409
+ threadRef.current = threadId;
410
+ const request = {
411
+ message: userQuery,
388
412
  // `standard` gives the operator loop six tool turns; `quick` (three)
389
413
  // was exhausted by schema + examples before the first query ran.
390
- mode: 'standard' }, (history.length > 0 ? { history } : {}));
414
+ mode: 'standard',
415
+ threadId,
416
+ };
391
417
  const options = {
392
418
  mode: 'auto',
393
419
  onProgress: (message, percentage) => {
@@ -456,7 +482,7 @@ export function ConsoleContent({ config, variant = 'page', }) {
456
482
  narrative = narrative.replace(jsonBlockMatch[0], '').trim();
457
483
  }
458
484
  }
459
- catch (_b) {
485
+ catch (_c) {
460
486
  // Not valid JSON, keep as text
461
487
  }
462
488
  }
@@ -495,13 +521,6 @@ export function ConsoleContent({ config, variant = 'page', }) {
495
521
  footer,
496
522
  writes,
497
523
  });
498
- // Record the exchange for follow-ups. Only a narrative answer is
499
- // worth carrying; the answer is clipped so history stays cheap.
500
- conversationRef.current = [
501
- ...conversationRef.current,
502
- { role: 'user', content: userQuery },
503
- { role: 'assistant', content: narrative.slice(0, 2000) },
504
- ].slice(-6);
505
524
  }
506
525
  else {
507
526
  addResultMessage(footer, rows, cypher, { writes });
@@ -517,7 +536,7 @@ export function ConsoleContent({ config, variant = 'page', }) {
517
536
  }
518
537
  setOperatorProgress({ isRunning: false, message: '' });
519
538
  const errorMessage = error.message ||
520
- ((_a = error.data) === null || _a === void 0 ? void 0 : _a.detail) ||
539
+ ((_b = error.data) === null || _b === void 0 ? void 0 : _b.detail) ||
521
540
  'Failed to process natural language query';
522
541
  if (error.status === 402) {
523
542
  addErrorMessage(`Insufficient credits to process query.\n\nPlease upgrade your subscription or wait for credits to reset.`);
@@ -615,6 +634,102 @@ export function ConsoleContent({ config, variant = 'page', }) {
615
634
  ` Header: X-API-Key: <your key>`);
616
635
  }
617
636
  };
637
+ // `/history`: the user's own conversations on this graph, newest first.
638
+ const showThreads = async () => {
639
+ var _a, _b;
640
+ if (!graphId) {
641
+ addErrorMessage(config.noSelectionError);
642
+ return;
643
+ }
644
+ const stale = leftScope();
645
+ try {
646
+ const res = await SDK.listOperatorThreads({
647
+ path: { graph_id: graphId },
648
+ query: { limit: 10 },
649
+ });
650
+ if (stale())
651
+ return;
652
+ const threads = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.threads) !== null && _b !== void 0 ? _b : [];
653
+ listedThreadsRef.current = threads;
654
+ if (threads.length === 0) {
655
+ addSystemMessage('No conversations recorded on this graph yet. Ask a question to start one.', true);
656
+ return;
657
+ }
658
+ const lines = threads.map((t, idx) => {
659
+ const when = new Date(t.last_run_at).toLocaleString();
660
+ const runs = `${t.run_count} ${t.run_count === 1 ? 'question' : 'questions'}`;
661
+ const current = t.thread_id === threadRef.current ? ' (current)' : '';
662
+ return `${idx + 1}. ${t.title}\n ${runs} · last ${when}${current}`;
663
+ });
664
+ addSystemMessage(`Recent conversations:\n\n${lines.join('\n\n')}\n\nUse: /resume <n> to continue one`, true);
665
+ }
666
+ catch (err) {
667
+ if (stale())
668
+ return;
669
+ addErrorMessage((err === null || err === void 0 ? void 0 : err.message) || 'Could not load conversations.');
670
+ }
671
+ };
672
+ // `/resume <n>`: replay a listed conversation and continue it — the next
673
+ // question carries its thread id.
674
+ const resumeThread = async (arg) => {
675
+ var _a, _b;
676
+ if (!graphId) {
677
+ addErrorMessage(config.noSelectionError);
678
+ return;
679
+ }
680
+ const index = Number.parseInt(arg, 10);
681
+ const thread = listedThreadsRef.current[index - 1];
682
+ if (!arg || Number.isNaN(index) || !thread) {
683
+ addErrorMessage(listedThreadsRef.current.length === 0
684
+ ? 'Run /history first, then /resume <n> with a number from the list.'
685
+ : `Pick a number from 1 to ${listedThreadsRef.current.length}.`);
686
+ return;
687
+ }
688
+ const stale = leftScope();
689
+ try {
690
+ const res = await SDK.listOperatorRuns({
691
+ path: { graph_id: graphId },
692
+ query: { thread_id: thread.thread_id, limit: 50 },
693
+ });
694
+ if (stale())
695
+ return;
696
+ // Newest first on the wire; the console reads top to bottom.
697
+ const runs = [...((_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.runs) !== null && _b !== void 0 ? _b : [])].reverse();
698
+ setTerminalMessages([]);
699
+ threadRef.current = thread.thread_id;
700
+ addSystemMessage(`Resumed conversation from ${new Date(thread.first_run_at).toLocaleString()}. Follow-up questions continue it.`, true);
701
+ for (const run of runs) {
702
+ addUserMessage(run.question);
703
+ replayRun(run);
704
+ }
705
+ }
706
+ catch (err) {
707
+ if (stale())
708
+ return;
709
+ addErrorMessage((err === null || err === void 0 ? void 0 : err.message) || 'Could not load the conversation.');
710
+ }
711
+ };
712
+ // A recorded run, rendered the way its answer was first printed: the
713
+ // Cypher keeps its Run button, the receipt its writes. Rows are not kept.
714
+ const replayRun = (run) => {
715
+ if (run.status === 'failed') {
716
+ addErrorMessage(`Operator error: ${run.error || 'The run failed.'}`);
717
+ return;
718
+ }
719
+ if (run.status === 'cancelled' || !run.answer) {
720
+ addSystemMessage('Cancelled before an answer was reached.');
721
+ return;
722
+ }
723
+ const seconds = (run.duration_ms / 1000).toFixed(1);
724
+ let footer = `Answered by ${run.operator_type} in ${seconds}s · ${new Date(run.finished_at).toLocaleString()}`;
725
+ if (run.credits_consumed > 0) {
726
+ footer += `\nCredits used: ${run.credits_consumed.toFixed(1)}`;
727
+ }
728
+ addResultMessage(run.answer, undefined, undefined, {
729
+ markdown: true,
730
+ footer,
731
+ });
732
+ };
618
733
  const handleCommand = async (command) => {
619
734
  var _a, _b;
620
735
  if (!command.trim())
@@ -646,6 +761,7 @@ export function ConsoleContent({ config, variant = 'page', }) {
646
761
  return;
647
762
  }
648
763
  addSystemMessage(`Searching for "${searchQuery}"...`);
764
+ const stale = leftScope();
649
765
  try {
650
766
  const body = {
651
767
  query: searchQuery,
@@ -655,6 +771,8 @@ export function ConsoleContent({ config, variant = 'page', }) {
655
771
  path: { graph_id: graphId },
656
772
  body: body,
657
773
  });
774
+ if (stale())
775
+ return;
658
776
  if (res.data) {
659
777
  const data = res.data;
660
778
  if (data.hits.length === 0) {
@@ -681,6 +799,8 @@ export function ConsoleContent({ config, variant = 'page', }) {
681
799
  }
682
800
  }
683
801
  catch (_c) {
802
+ if (stale())
803
+ return;
684
804
  addErrorMessage('An error occurred while searching.');
685
805
  }
686
806
  return;
@@ -710,11 +830,14 @@ export function ConsoleContent({ config, variant = 'page', }) {
710
830
  return;
711
831
  }
712
832
  addSystemMessage(`Recalling memories for "${recallQuery}"...`);
833
+ const stale = leftScope();
713
834
  try {
714
835
  const res = await SDK.recallMemory({
715
836
  path: { graph_id: graphId },
716
837
  body: { query: recallQuery, k: 10 },
717
838
  });
839
+ if (stale())
840
+ return;
718
841
  if (res.data) {
719
842
  const data = res.data;
720
843
  if (data.hits.length === 0) {
@@ -746,6 +869,8 @@ export function ConsoleContent({ config, variant = 'page', }) {
746
869
  }
747
870
  }
748
871
  catch (_d) {
872
+ if (stale())
873
+ return;
749
874
  addErrorMessage('An error occurred while recalling memories.');
750
875
  }
751
876
  return;
@@ -765,9 +890,15 @@ export function ConsoleContent({ config, variant = 'page', }) {
765
890
  return;
766
891
  case '/clear':
767
892
  setTerminalMessages([]);
768
- conversationRef.current = [];
893
+ threadRef.current = null;
769
894
  addSystemMessage('Console cleared.', true);
770
895
  return;
896
+ case '/history':
897
+ await showThreads();
898
+ return;
899
+ case '/resume':
900
+ await resumeThread(command.slice(cmd.length).trim());
901
+ return;
771
902
  case '/examples': {
772
903
  const examples = config.sampleQueries
773
904
  .map((q, idx) => `${idx + 1}. ${q.name}\n/query ${q.query}`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@robosystems/core",
3
- "version": "0.15.1",
3
+ "version": "0.17.0",
4
4
  "description": "Shared RoboSystems frontend core library (auth, contexts, task monitoring, UI components) for the RoboSystems Next.js apps",
5
5
  "license": "MIT",
6
6
  "private": false,
@@ -27,7 +27,7 @@
27
27
  "tailwind-merge": "^3"
28
28
  },
29
29
  "peerDependencies": {
30
- "@robosystems/client": ">=2.7 <3",
30
+ "@robosystems/client": ">=2.34 <3",
31
31
  "flowbite-react": "^0.12.5",
32
32
  "next": ">=15 <17",
33
33
  "react": ">=18 <20",