@robosystems/core 0.16.0 → 0.17.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.
@@ -3,7 +3,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { useEffect, useRef, useState } from 'react';
4
4
  import { CURRENT_APP, isLoginHome } from '../auth-core/config';
5
5
  import { buildLoginHomeUrl, buildReturnTo, isSafeRelativePath, } from '../auth-core/login-home';
6
- import { useSSO } from '../auth-core/sso';
6
+ import { hasPendingBridge, mintBrowserNonce, useSSO } from '../auth-core/sso';
7
7
  import { BrandSpinner } from '../ui-components';
8
8
  /**
9
9
  * Product-app stand-in for the login/register pages under centralized login.
@@ -23,7 +23,7 @@ export function LoginRedirector({ mode = 'login', apiUrl, homePath = '/home', })
23
23
  const [misconfigured, setMisconfigured] = useState(false);
24
24
  const startedRef = useRef(false);
25
25
  useEffect(() => {
26
- var _a;
26
+ var _a, _b;
27
27
  // Guard against StrictMode double-mount: the first run consumes
28
28
  // session_id and strips it from the URL, so a second run would
29
29
  // misread the state as a failed bridge.
@@ -33,7 +33,9 @@ export function LoginRedirector({ mode = 'login', apiUrl, homePath = '/home', })
33
33
  startedRef.current = true;
34
34
  const params = new URLSearchParams(window.location.search);
35
35
  const sessionId = params.get('session_id');
36
- if (sessionId) {
36
+ // A session_id this browser never asked for (a reused or foreign link)
37
+ // is not consumed; the bridge below starts fresh, bound to this browser.
38
+ if (sessionId && hasPendingBridge()) {
37
39
  const returnUrl = params.get('returnUrl');
38
40
  void handleSSOLogin().then((user) => {
39
41
  if (user) {
@@ -58,18 +60,28 @@ export function LoginRedirector({ mode = 'login', apiUrl, homePath = '/home', })
58
60
  setMisconfigured(true);
59
61
  return;
60
62
  }
61
- const localReturnTo = params.get('return_to');
63
+ const localReturnTo = (_a = params.get('return_to')) !== null && _a !== void 0 ? _a : (sessionId ? params.get('returnUrl') : null);
62
64
  const path = localReturnTo && isSafeRelativePath(localReturnTo)
63
65
  ? localReturnTo
64
66
  : undefined;
65
- const reason = (_a = params.get('reason')) !== null && _a !== void 0 ? _a : undefined;
66
- // replace() keeps the redirector page out of history so Back returns
67
- // to the page the user actually came from.
68
- window.location.replace(buildLoginHomeUrl(mode, {
69
- returnTo: buildReturnTo(CURRENT_APP, path),
70
- reason,
71
- forwardParams: params,
72
- }));
67
+ const reason = (_b = params.get('reason')) !== null && _b !== void 0 ? _b : undefined;
68
+ // The nonce binds the handoff to this browser; its hash rides to the
69
+ // login home. replace() keeps the redirector page out of history so Back
70
+ // returns to the page the user actually came from.
71
+ void mintBrowserNonce().then((nonceHash) => {
72
+ // A browser that cannot hold a nonce cannot take a handoff; one that
73
+ // has just come back with a session_id would only go round again.
74
+ if (!nonceHash && sessionId) {
75
+ setBridgeFailed(true);
76
+ return;
77
+ }
78
+ window.location.replace(buildLoginHomeUrl(mode, {
79
+ returnTo: buildReturnTo(CURRENT_APP, path),
80
+ reason,
81
+ forwardParams: params,
82
+ nonceHash: nonceHash !== null && nonceHash !== void 0 ? nonceHash : undefined,
83
+ }));
84
+ });
73
85
  }, [handleSSOLogin, mode, homePath]);
74
86
  if (misconfigured) {
75
87
  return (_jsxs("div", { className: "flex min-h-screen flex-col items-center justify-center gap-4 px-6 text-center", children: [_jsx("p", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: "Sign-in is temporarily unavailable" }), _jsx("p", { className: "max-w-md text-sm text-gray-600 dark:text-gray-400", children: "This page is misconfigured. Please contact support if the problem persists." })] }));
@@ -69,10 +69,10 @@ export declare class RoboSystemsAuthClient {
69
69
  getAPIKeys(): Promise<APIKey[]>;
70
70
  revokeAPIKey(keyId: string): Promise<void>;
71
71
  generateSSOToken(): Promise<SSOTokenResponse>;
72
- ssoExchange(token: string, targetApp: string): Promise<{
72
+ ssoExchange(token: string, targetApp: string, browserNonceHash?: string): Promise<{
73
73
  session_id: string;
74
74
  }>;
75
- ssoComplete(sessionId: string): Promise<AuthResponse>;
75
+ ssoComplete(sessionId: string, browserNonce?: string): Promise<AuthResponse>;
76
76
  checkAuthentication(): Promise<AuthUser | null>;
77
77
  /**
78
78
  * Fetch the deployment's auth posture (which sign-in methods to render).
@@ -503,20 +503,20 @@ export class RoboSystemsAuthClient {
503
503
  });
504
504
  return unwrapSdk(response);
505
505
  }
506
- async ssoExchange(token, targetApp) {
506
+ async ssoExchange(token, targetApp, browserNonceHash) {
507
507
  const response = await ssoTokenExchange({
508
508
  client: this.client,
509
- body: { token, target_app: targetApp },
509
+ body: Object.assign({ token, target_app: targetApp }, (browserNonceHash ? { browser_nonce_hash: browserNonceHash } : {})),
510
510
  });
511
511
  const data = unwrapSdk(response);
512
512
  return {
513
513
  session_id: data.session_id,
514
514
  };
515
515
  }
516
- async ssoComplete(sessionId) {
516
+ async ssoComplete(sessionId, browserNonce) {
517
517
  const response = await completeSsoAuth({
518
518
  client: this.client,
519
- body: { session_id: sessionId },
519
+ body: Object.assign({ session_id: sessionId }, (browserNonce ? { browser_nonce: browserNonce } : {})),
520
520
  });
521
521
  const sdkResponse = this.validateSDKAuthResponse(unwrapSdk(response));
522
522
  // Store JWT token with expiry information if present in response
@@ -41,6 +41,12 @@ export interface LoginHomeUrlOptions {
41
41
  * Params owned by the redirect/bridge flow are dropped.
42
42
  */
43
43
  forwardParams?: URLSearchParams;
44
+ /**
45
+ * SHA-256 of the nonce this browser minted for the bridge it is starting
46
+ * (see `mintBrowserNonce`). The login home passes it into the exchange so
47
+ * the handoff completes only here.
48
+ */
49
+ nonceHash?: string;
44
50
  }
45
51
  /** Build an absolute URL on the login home for the given auth surface. */
46
52
  export declare function buildLoginHomeUrl(mode: 'login' | 'register' | 'logout', options?: LoginHomeUrlOptions): string;
@@ -31,7 +31,7 @@ export function parseReturnTo(raw) {
31
31
  const separator = raw.indexOf(':');
32
32
  const app = separator === -1 ? raw : raw.slice(0, separator);
33
33
  const path = separator === -1 ? null : raw.slice(separator + 1);
34
- if (!APP_CONFIGS[app]) {
34
+ if (!Object.hasOwn(APP_CONFIGS, app)) {
35
35
  return null;
36
36
  }
37
37
  if (path !== null && !isSafeRelativePath(path)) {
@@ -40,7 +40,13 @@ export function parseReturnTo(raw) {
40
40
  return { app, path };
41
41
  }
42
42
  /** Params the redirect/bridge flow owns; never forwarded verbatim. */
43
- const OWNED_PARAMS = new Set(['session_id', 'returnUrl', 'return_to', 'reason']);
43
+ const OWNED_PARAMS = new Set([
44
+ 'session_id',
45
+ 'returnUrl',
46
+ 'return_to',
47
+ 'reason',
48
+ 'nonce_hash',
49
+ ]);
44
50
  /** Build an absolute URL on the login home for the given auth surface. */
45
51
  export function buildLoginHomeUrl(mode, options = {}) {
46
52
  const url = new URL(`/${mode}`, getLoginHomeUrl());
@@ -57,5 +63,8 @@ export function buildLoginHomeUrl(mode, options = {}) {
57
63
  if (options.reason) {
58
64
  url.searchParams.set('reason', options.reason);
59
65
  }
66
+ if (options.nonceHash) {
67
+ url.searchParams.set('nonce_hash', options.nonceHash);
68
+ }
60
69
  return url.toString();
61
70
  }
@@ -1,4 +1,15 @@
1
1
  import type { AppConfig, AuthUser } from './types';
2
+ /**
3
+ * Mint the nonce that binds a bridge to this browser and return its SHA-256.
4
+ *
5
+ * The nonce stays in this origin's sessionStorage; only the hash travels to
6
+ * the login home and into the exchange. Completion presents the nonce, so a
7
+ * handoff minted elsewhere cannot be redeemed here. Returns null where the
8
+ * platform cannot mint one; such a browser cannot complete a handoff.
9
+ */
10
+ export declare function mintBrowserNonce(): Promise<string | null>;
11
+ /** True when this browser started a bridge it has not completed yet. */
12
+ export declare function hasPendingBridge(): boolean;
2
13
  export interface SSORedirectUrlOptions {
3
14
  /**
4
15
  * @deprecated No effect. The return path travels only in the handoff URL;
@@ -6,6 +17,14 @@ export interface SSORedirectUrlOptions {
6
17
  * its own origin) and misrouted later handoffs into the *source* app.
7
18
  */
8
19
  persistSessionHints?: boolean;
20
+ /**
21
+ * SHA-256 of the nonce the target app minted when it started this bridge
22
+ * (`?nonce_hash=` on the login home). With it, the handoff is bound to
23
+ * that browser. Without it, the handoff is unbound: an app on an older
24
+ * core completes it, and an app on this one ignores it and starts a bound
25
+ * bridge of its own.
26
+ */
27
+ nonceHash?: string;
9
28
  }
10
29
  export declare class SSOManager {
11
30
  private authClient;
@@ -21,7 +40,7 @@ export declare class SSOManager {
21
40
  /**
22
41
  * Get SSO redirect URL using secure POST-based flow
23
42
  */
24
- getSSORedirectUrl(targetApp: string, returnUrl?: string, _options?: SSORedirectUrlOptions): Promise<string>;
43
+ getSSORedirectUrl(targetApp: string, returnUrl?: string, options?: SSORedirectUrlOptions): Promise<string>;
25
44
  /**
26
45
  * Handle SSO login using secure POST-based flow
27
46
  */
@@ -35,9 +54,14 @@ export declare class SSOManager {
35
54
  */
36
55
  private sanitizeErrorForLogging;
37
56
  /**
38
- * Navigate to another app with secure SSO
57
+ * Navigate to another app with secure SSO.
58
+ *
59
+ * With the target's `nonceHash` (the login home's case), the handoff is
60
+ * bound to that browser; see `SSORedirectUrlOptions.nonceHash` for the
61
+ * case without one. If the handoff cannot be minted, the browser goes to
62
+ * the target's login page to start a bridge of its own.
39
63
  */
40
- navigateToApp(targetApp: string, returnUrl?: string): Promise<void>;
64
+ navigateToApp(targetApp: string, returnUrl?: string, options?: SSORedirectUrlOptions): Promise<void>;
41
65
  }
42
66
  /**
43
67
  * Hook for SSO functionality
@@ -46,6 +70,6 @@ export declare function useSSO(apiUrl: string): {
46
70
  checkSSOAuthentication: () => Promise<AuthUser>;
47
71
  handleSSOLogin: () => Promise<AuthUser>;
48
72
  getSSORedirectUrl: (targetApp: string, returnUrl?: string, options?: SSORedirectUrlOptions) => Promise<string>;
49
- navigateToApp: (targetApp: string, returnUrl?: string) => Promise<void>;
73
+ navigateToApp: (targetApp: string, returnUrl?: string, options?: SSORedirectUrlOptions) => Promise<void>;
50
74
  getAvailableApps: () => AppConfig[];
51
75
  };
package/auth-core/sso.js CHANGED
@@ -2,6 +2,71 @@ import { useMemo } from 'react';
2
2
  import { RoboSystemsAuthClient } from './client';
3
3
  import { APP_CONFIGS } from './config';
4
4
  import { isSafeRelativePath } from './login-home';
5
+ /** Where the browser that starts a bridge keeps the nonce it minted. */
6
+ const BROWSER_NONCE_KEY = 'sso_browser_nonce';
7
+ const toHex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
8
+ /**
9
+ * Mint the nonce that binds a bridge to this browser and return its SHA-256.
10
+ *
11
+ * The nonce stays in this origin's sessionStorage; only the hash travels to
12
+ * the login home and into the exchange. Completion presents the nonce, so a
13
+ * handoff minted elsewhere cannot be redeemed here. Returns null where the
14
+ * platform cannot mint one; such a browser cannot complete a handoff.
15
+ */
16
+ export async function mintBrowserNonce() {
17
+ try {
18
+ const nonce = toHex(crypto.getRandomValues(new Uint8Array(32)));
19
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(nonce));
20
+ sessionStorage.setItem(BROWSER_NONCE_KEY, nonce);
21
+ return toHex(new Uint8Array(digest));
22
+ }
23
+ catch (error) {
24
+ debugLog('browser nonce unavailable', error);
25
+ return null;
26
+ }
27
+ }
28
+ /** True when this browser started a bridge it has not completed yet. */
29
+ export function hasPendingBridge() {
30
+ try {
31
+ return Boolean(sessionStorage.getItem(BROWSER_NONCE_KEY));
32
+ }
33
+ catch (_a) {
34
+ return false;
35
+ }
36
+ }
37
+ function takeBrowserNonce() {
38
+ let nonce;
39
+ try {
40
+ nonce = sessionStorage.getItem(BROWSER_NONCE_KEY);
41
+ }
42
+ catch (_a) {
43
+ return null;
44
+ }
45
+ try {
46
+ sessionStorage.removeItem(BROWSER_NONCE_KEY);
47
+ }
48
+ catch (error) {
49
+ debugLog('browser nonce could not be cleared', error);
50
+ }
51
+ return nonce;
52
+ }
53
+ function appConfigFor(targetApp) {
54
+ if (!Object.hasOwn(APP_CONFIGS, targetApp)) {
55
+ throw new Error(`Unknown app: ${targetApp}`);
56
+ }
57
+ return APP_CONFIGS[targetApp];
58
+ }
59
+ /**
60
+ * The target's login page, which starts a bound bridge of its own (through
61
+ * the login home) for `returnUrl`.
62
+ */
63
+ function boundBridgeEntryUrl(appConfig, returnUrl) {
64
+ const url = new URL('/login', appConfig.url);
65
+ if (returnUrl && isSafeRelativePath(returnUrl)) {
66
+ url.searchParams.set('return_to', returnUrl);
67
+ }
68
+ return url.toString();
69
+ }
5
70
  // Configuration constants
6
71
  const NAVIGATION_DELAY_MS = 100; // 100ms delay for navigation
7
72
  // Debug logging helper
@@ -56,14 +121,12 @@ export class SSOManager {
56
121
  /**
57
122
  * Get SSO redirect URL using secure POST-based flow
58
123
  */
59
- async getSSORedirectUrl(targetApp, returnUrl, _options = {}) {
124
+ async getSSORedirectUrl(targetApp, returnUrl, options = {}) {
125
+ const appConfig = appConfigFor(targetApp);
60
126
  const ssoData = await this.generateSSOToken();
61
- const appConfig = APP_CONFIGS[targetApp];
62
- if (!appConfig) {
63
- throw new Error(`Unknown app: ${targetApp}`);
64
- }
65
- // Step 1: Exchange SSO token for secure session ID
66
- const exchangeResult = await this.authClient.ssoExchange(ssoData.token, targetApp);
127
+ // Step 1: Exchange SSO token for secure session ID, bound to the browser
128
+ // that minted the nonce when there is one
129
+ const exchangeResult = await this.authClient.ssoExchange(ssoData.token, targetApp, options.nonceHash);
67
130
  // Step 2: Create URL that will trigger the POST-based flow
68
131
  const url = new URL('/login', appConfig.url);
69
132
  // Pass session ID via URL parameters for cross-domain compatibility
@@ -88,9 +151,21 @@ export class SSOManager {
88
151
  if (!finalSessionId) {
89
152
  return null;
90
153
  }
154
+ // Only a bridge this browser started is completed here: the nonce it
155
+ // minted proves it. A session_id arriving without one came from a link,
156
+ // not from this browser's bridge, and is left alone.
157
+ const nonce = takeBrowserNonce();
158
+ if (!nonce) {
159
+ debugLog('session_id present without a pending bridge; ignoring it');
160
+ const newUrl = new URL(window.location.href);
161
+ newUrl.searchParams.delete('session_id');
162
+ newUrl.searchParams.delete('returnUrl');
163
+ window.history.replaceState({}, '', newUrl.toString());
164
+ return null;
165
+ }
91
166
  try {
92
167
  // Complete SSO authentication using session ID
93
- const authResponse = await this.authClient.ssoComplete(finalSessionId);
168
+ const authResponse = await this.authClient.ssoComplete(finalSessionId, nonce);
94
169
  // Clean up both URL parameters and session storage
95
170
  if (sessionId) {
96
171
  // Clean up URL parameters
@@ -164,56 +239,17 @@ export class SSOManager {
164
239
  return String(error);
165
240
  }
166
241
  /**
167
- * Navigate to another app with secure SSO
242
+ * Navigate to another app with secure SSO.
243
+ *
244
+ * With the target's `nonceHash` (the login home's case), the handoff is
245
+ * bound to that browser; see `SSORedirectUrlOptions.nonceHash` for the
246
+ * case without one. If the handoff cannot be minted, the browser goes to
247
+ * the target's login page to start a bridge of its own.
168
248
  */
169
- async navigateToApp(targetApp, returnUrl) {
170
- const appConfig = APP_CONFIGS[targetApp];
171
- if (!appConfig) {
172
- throw new Error(`Unknown app: ${targetApp}`);
173
- }
174
- // Check local auth cache first to avoid unnecessary SSO token generation
175
- if (typeof window !== 'undefined') {
176
- let cachedUser = null;
177
- try {
178
- cachedUser = sessionStorage.getItem('auth_user_cache');
179
- }
180
- catch (error) {
181
- // Storage access error - proceed with SSO flow
182
- debugLog('sessionStorage read failed during navigation cache check', error);
183
- }
184
- if (cachedUser) {
185
- try {
186
- JSON.parse(cachedUser);
187
- // REMOVED: Cache bypass logic that was skipping SSO flow
188
- // Always use proper SSO flow for cross-app authentication
189
- debugLog('Proceeding with full SSO flow for secure cross-app auth');
190
- }
191
- catch (error) {
192
- // Invalid cache, proceed with SSO flow
193
- debugLog('Invalid cache found, proceeding with SSO flow', error);
194
- try {
195
- sessionStorage.removeItem('auth_user_cache');
196
- }
197
- catch (_a) {
198
- // Storage error - continue silently
199
- }
200
- }
201
- }
202
- }
249
+ async navigateToApp(targetApp, returnUrl, options = {}) {
250
+ const appConfig = appConfigFor(targetApp);
203
251
  try {
204
- // Fallback to full SSO flow for stale/missing cache
205
- const ssoData = await this.generateSSOToken();
206
- // Step 2: Exchange token for secure session ID
207
- const exchangeResult = await this.authClient.ssoExchange(ssoData.token, targetApp);
208
- // Step 3: Navigate to target app with secure session handoff
209
- const targetUrl = new URL('/login', appConfig.url);
210
- // Pass session ID via URL parameters for cross-domain compatibility
211
- targetUrl.searchParams.set('session_id', exchangeResult.session_id);
212
- if (returnUrl) {
213
- targetUrl.searchParams.set('returnUrl', returnUrl);
214
- }
215
- // Navigate to target app
216
- window.location.href = targetUrl.toString();
252
+ window.location.href = await this.getSSORedirectUrl(targetApp, returnUrl, options);
217
253
  }
218
254
  catch (error) {
219
255
  if (process.env.NODE_ENV === 'development') {
@@ -222,11 +258,7 @@ export class SSOManager {
222
258
  debugLog('SSO navigation failed, attempting fallback', error);
223
259
  // Fallback to direct navigation
224
260
  try {
225
- const targetUrl = new URL(appConfig.url);
226
- if (returnUrl) {
227
- targetUrl.searchParams.set('returnUrl', returnUrl);
228
- }
229
- window.location.href = targetUrl.toString();
261
+ window.location.href = boundBridgeEntryUrl(appConfig, returnUrl);
230
262
  }
231
263
  catch (locationError) {
232
264
  if (process.env.NODE_ENV === 'development') {
@@ -248,7 +280,7 @@ export function useSSO(apiUrl) {
248
280
  checkSSOAuthentication: () => ssoManager.checkSSOAuthentication(),
249
281
  handleSSOLogin: () => ssoManager.handleSSOLogin(),
250
282
  getSSORedirectUrl: (targetApp, returnUrl, options) => ssoManager.getSSORedirectUrl(targetApp, returnUrl, options),
251
- navigateToApp: (targetApp, returnUrl) => ssoManager.navigateToApp(targetApp, returnUrl),
283
+ navigateToApp: (targetApp, returnUrl, options) => ssoManager.navigateToApp(targetApp, returnUrl, options),
252
284
  getAvailableApps: () => ssoManager.getAvailableApps(),
253
285
  }), [ssoManager]);
254
286
  }
@@ -1,4 +1,5 @@
1
1
  import type { ConsoleConfig } from './types';
2
+ export declare function rowsToCsv(rows: any[]): string;
2
3
  export declare function ConsoleContent({ config, variant, }: {
3
4
  config: ConsoleConfig;
4
5
  /** `panel` drops the page header and fills its container (the drawer). */
@@ -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
  }
@@ -30,7 +39,8 @@ function formatCell(value) {
30
39
  return JSON.stringify(value);
31
40
  return String(value);
32
41
  }
33
- function rowsToCsv(rows) {
42
+ const NUMERIC_TEXT = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
43
+ export function rowsToCsv(rows) {
34
44
  const cols = Object.keys(rows[0]);
35
45
  const escape = (v) => {
36
46
  const s = v === null || v === undefined
@@ -38,10 +48,18 @@ function rowsToCsv(rows) {
38
48
  : typeof v === 'object'
39
49
  ? JSON.stringify(v)
40
50
  : String(v);
41
- return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
51
+ // Text that starts like a formula is neutralised: these values come from
52
+ // the graph, and a spreadsheet would run them. Numbers stay numbers,
53
+ // including the decimals the graph returns as strings.
54
+ const guarded = typeof v === 'number' || NUMERIC_TEXT.test(s) || !/^[=+\-@\t\r]/.test(s)
55
+ ? s
56
+ : `'${s}`;
57
+ return /[",\n\r]/.test(guarded)
58
+ ? `"${guarded.replace(/"/g, '""')}"`
59
+ : guarded;
42
60
  };
43
61
  return [
44
- cols.join(','),
62
+ cols.map(escape).join(','),
45
63
  ...rows.map((row) => cols.map((c) => escape(row[c])).join(',')),
46
64
  ].join('\n');
47
65
  }
@@ -108,10 +126,14 @@ export function ConsoleContent({ config, variant = 'page', }) {
108
126
  const [historyIndex, setHistoryIndex] = useState(-1);
109
127
  const terminalEndRef = useRef(null);
110
128
  const terminalScrollRef = useRef(null);
111
- // Prior operator exchanges, sent as `history` so a follow-up like "and for
112
- // June?" resolves against the previous answer. Bounded to the last three
113
- // exchanges — the backend seeds only its last five turns anyway.
114
- const conversationRef = useRef([]);
129
+ // The conversation the operator questions belong to. Minted on the first
130
+ // question, sent with every one after it, so a follow-up like "and for
131
+ // June?" resolves against the previous answers: the server seeds the run
132
+ // from the thread's own record. Null until a question is asked, and reset
133
+ // by /clear and by a graph switch.
134
+ const threadRef = useRef(null);
135
+ // The threads /history last listed, so /resume <n> can name one.
136
+ const listedThreadsRef = useRef([]);
115
137
  const [currentQueryStartTime, setCurrentQueryStartTime] = useState(null);
116
138
  const [apiVersion, setApiVersion] = useState(null);
117
139
  const [operatorProgress, setOperatorProgress] = useState({ isRunning: false, message: '' });
@@ -144,7 +166,9 @@ export function ConsoleContent({ config, variant = 'page', }) {
144
166
  ` /mcp - Connect an MCP client (sign in — no key)\n` +
145
167
  ` /mcp key - Mint a graph-scoped API key for header-only clients\n` +
146
168
  ` /help - Show this help message\n` +
147
- ` /clear - Clear console history\n` +
169
+ ` /history - List your recent conversations on this graph\n` +
170
+ ` /resume <n> - Continue a listed conversation\n` +
171
+ ` /clear - Clear the console and start a new conversation\n` +
148
172
  ` /examples - Show example queries`;
149
173
  const extraLines = ((_a = config.extraCommands) !== null && _a !== void 0 ? _a : [])
150
174
  .map((ec) => ` ${ec.command.padEnd(12)}- Custom command`)
@@ -250,7 +274,7 @@ export function ConsoleContent({ config, variant = 'page', }) {
250
274
  setTerminalMessages([]);
251
275
  // A follow-up on the new graph must not resolve against the previous
252
276
  // graph's answers.
253
- conversationRef.current = [];
277
+ threadRef.current = null;
254
278
  setCurrentQueryStartTime(null);
255
279
  addSystemMessage(`═══════════════════════════════════════════════════════════════\n` +
256
280
  `${config.welcome.contextLabel} context changed: ${fromGraphId} → ${graphId}\n` +
@@ -372,7 +396,7 @@ export function ConsoleContent({ config, variant = 'page', }) {
372
396
  // `operatorType` names an operator (`author` for /do); unset, the API
373
397
  // chooses one for a question.
374
398
  const executeOperatorQuery = async (userQuery, operatorType) => {
375
- var _a;
399
+ var _a, _b;
376
400
  if (!graphId) {
377
401
  addErrorMessage(config.noSelectionError);
378
402
  return;
@@ -390,11 +414,15 @@ export function ConsoleContent({ config, variant = 'page', }) {
390
414
  graphEpochRef.current !== requestEpoch;
391
415
  try {
392
416
  const { clients } = await import('@robosystems/client/clients');
393
- const history = conversationRef.current;
394
- const request = Object.assign({ message: userQuery,
417
+ const threadId = (_a = threadRef.current) !== null && _a !== void 0 ? _a : mintThreadId();
418
+ threadRef.current = threadId;
419
+ const request = {
420
+ message: userQuery,
395
421
  // `standard` gives the operator loop six tool turns; `quick` (three)
396
422
  // was exhausted by schema + examples before the first query ran.
397
- mode: 'standard' }, (history.length > 0 ? { history } : {}));
423
+ mode: 'standard',
424
+ threadId,
425
+ };
398
426
  const options = {
399
427
  mode: 'auto',
400
428
  onProgress: (message, percentage) => {
@@ -463,7 +491,7 @@ export function ConsoleContent({ config, variant = 'page', }) {
463
491
  narrative = narrative.replace(jsonBlockMatch[0], '').trim();
464
492
  }
465
493
  }
466
- catch (_b) {
494
+ catch (_c) {
467
495
  // Not valid JSON, keep as text
468
496
  }
469
497
  }
@@ -502,13 +530,6 @@ export function ConsoleContent({ config, variant = 'page', }) {
502
530
  footer,
503
531
  writes,
504
532
  });
505
- // Record the exchange for follow-ups. Only a narrative answer is
506
- // worth carrying; the answer is clipped so history stays cheap.
507
- conversationRef.current = [
508
- ...conversationRef.current,
509
- { role: 'user', content: userQuery },
510
- { role: 'assistant', content: narrative.slice(0, 2000) },
511
- ].slice(-6);
512
533
  }
513
534
  else {
514
535
  addResultMessage(footer, rows, cypher, { writes });
@@ -524,7 +545,7 @@ export function ConsoleContent({ config, variant = 'page', }) {
524
545
  }
525
546
  setOperatorProgress({ isRunning: false, message: '' });
526
547
  const errorMessage = error.message ||
527
- ((_a = error.data) === null || _a === void 0 ? void 0 : _a.detail) ||
548
+ ((_b = error.data) === null || _b === void 0 ? void 0 : _b.detail) ||
528
549
  'Failed to process natural language query';
529
550
  if (error.status === 402) {
530
551
  addErrorMessage(`Insufficient credits to process query.\n\nPlease upgrade your subscription or wait for credits to reset.`);
@@ -622,6 +643,102 @@ export function ConsoleContent({ config, variant = 'page', }) {
622
643
  ` Header: X-API-Key: <your key>`);
623
644
  }
624
645
  };
646
+ // `/history`: the user's own conversations on this graph, newest first.
647
+ const showThreads = async () => {
648
+ var _a, _b;
649
+ if (!graphId) {
650
+ addErrorMessage(config.noSelectionError);
651
+ return;
652
+ }
653
+ const stale = leftScope();
654
+ try {
655
+ const res = await SDK.listOperatorThreads({
656
+ path: { graph_id: graphId },
657
+ query: { limit: 10 },
658
+ });
659
+ if (stale())
660
+ return;
661
+ const threads = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.threads) !== null && _b !== void 0 ? _b : [];
662
+ listedThreadsRef.current = threads;
663
+ if (threads.length === 0) {
664
+ addSystemMessage('No conversations recorded on this graph yet. Ask a question to start one.', true);
665
+ return;
666
+ }
667
+ const lines = threads.map((t, idx) => {
668
+ const when = new Date(t.last_run_at).toLocaleString();
669
+ const runs = `${t.run_count} ${t.run_count === 1 ? 'question' : 'questions'}`;
670
+ const current = t.thread_id === threadRef.current ? ' (current)' : '';
671
+ return `${idx + 1}. ${t.title}\n ${runs} · last ${when}${current}`;
672
+ });
673
+ addSystemMessage(`Recent conversations:\n\n${lines.join('\n\n')}\n\nUse: /resume <n> to continue one`, true);
674
+ }
675
+ catch (err) {
676
+ if (stale())
677
+ return;
678
+ addErrorMessage((err === null || err === void 0 ? void 0 : err.message) || 'Could not load conversations.');
679
+ }
680
+ };
681
+ // `/resume <n>`: replay a listed conversation and continue it — the next
682
+ // question carries its thread id.
683
+ const resumeThread = async (arg) => {
684
+ var _a, _b;
685
+ if (!graphId) {
686
+ addErrorMessage(config.noSelectionError);
687
+ return;
688
+ }
689
+ const index = Number.parseInt(arg, 10);
690
+ const thread = listedThreadsRef.current[index - 1];
691
+ if (!arg || Number.isNaN(index) || !thread) {
692
+ addErrorMessage(listedThreadsRef.current.length === 0
693
+ ? 'Run /history first, then /resume <n> with a number from the list.'
694
+ : `Pick a number from 1 to ${listedThreadsRef.current.length}.`);
695
+ return;
696
+ }
697
+ const stale = leftScope();
698
+ try {
699
+ const res = await SDK.listOperatorRuns({
700
+ path: { graph_id: graphId },
701
+ query: { thread_id: thread.thread_id, limit: 50 },
702
+ });
703
+ if (stale())
704
+ return;
705
+ // Newest first on the wire; the console reads top to bottom.
706
+ const runs = [...((_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.runs) !== null && _b !== void 0 ? _b : [])].reverse();
707
+ setTerminalMessages([]);
708
+ threadRef.current = thread.thread_id;
709
+ addSystemMessage(`Resumed conversation from ${new Date(thread.first_run_at).toLocaleString()}. Follow-up questions continue it.`, true);
710
+ for (const run of runs) {
711
+ addUserMessage(run.question);
712
+ replayRun(run);
713
+ }
714
+ }
715
+ catch (err) {
716
+ if (stale())
717
+ return;
718
+ addErrorMessage((err === null || err === void 0 ? void 0 : err.message) || 'Could not load the conversation.');
719
+ }
720
+ };
721
+ // A recorded run, rendered the way its answer was first printed: the
722
+ // Cypher keeps its Run button, the receipt its writes. Rows are not kept.
723
+ const replayRun = (run) => {
724
+ if (run.status === 'failed') {
725
+ addErrorMessage(`Operator error: ${run.error || 'The run failed.'}`);
726
+ return;
727
+ }
728
+ if (run.status === 'cancelled' || !run.answer) {
729
+ addSystemMessage('Cancelled before an answer was reached.');
730
+ return;
731
+ }
732
+ const seconds = (run.duration_ms / 1000).toFixed(1);
733
+ let footer = `Answered by ${run.operator_type} in ${seconds}s · ${new Date(run.finished_at).toLocaleString()}`;
734
+ if (run.credits_consumed > 0) {
735
+ footer += `\nCredits used: ${run.credits_consumed.toFixed(1)}`;
736
+ }
737
+ addResultMessage(run.answer, undefined, undefined, {
738
+ markdown: true,
739
+ footer,
740
+ });
741
+ };
625
742
  const handleCommand = async (command) => {
626
743
  var _a, _b;
627
744
  if (!command.trim())
@@ -782,9 +899,15 @@ export function ConsoleContent({ config, variant = 'page', }) {
782
899
  return;
783
900
  case '/clear':
784
901
  setTerminalMessages([]);
785
- conversationRef.current = [];
902
+ threadRef.current = null;
786
903
  addSystemMessage('Console cleared.', true);
787
904
  return;
905
+ case '/history':
906
+ await showThreads();
907
+ return;
908
+ case '/resume':
909
+ await resumeThread(command.slice(cmd.length).trim());
910
+ return;
788
911
  case '/examples': {
789
912
  const examples = config.sampleQueries
790
913
  .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.16.0",
3
+ "version": "0.17.1",
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",