@agent-native/core 0.229.0 → 0.230.0-nightly-20261117004313

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 (73) hide show
  1. package/dist/action.d.ts +23 -0
  2. package/dist/action.js +21 -0
  3. package/dist/agent/production-agent.d.ts +1 -0
  4. package/dist/agent/production-agent.js +28 -21
  5. package/dist/agent/types.d.ts +2 -0
  6. package/dist/app-config/deploy-cache.d.ts +2 -0
  7. package/dist/app-config/deploy-cache.js +8 -0
  8. package/dist/app-config/observability.d.ts +1 -0
  9. package/dist/app-config/observability.js +10 -0
  10. package/dist/app-config/schema.d.ts +3 -0
  11. package/dist/app-config/store.js +1 -0
  12. package/dist/cli/skills-content/design-remix-skill.d.ts +1 -1
  13. package/dist/cli/skills-content/design-remix-skill.js +193 -32
  14. package/dist/client/action-query-foreground.d.ts +4 -2
  15. package/dist/client/action-query-foreground.js +53 -6
  16. package/dist/client/hooks/index.d.ts +1 -0
  17. package/dist/client/hooks/index.js +1 -0
  18. package/dist/client/onboarding/first-run-status.js +4 -0
  19. package/dist/client/org/hooks.d.ts +12 -1
  20. package/dist/client/org/hooks.js +24 -2
  21. package/dist/client/sharing/useShareButtonController.d.ts +8 -1
  22. package/dist/client/sharing/useShareButtonController.js +20 -13
  23. package/dist/client/theme.d.ts +9 -1
  24. package/dist/client/theme.js +15 -2
  25. package/dist/client/ui/index.d.ts +1 -1
  26. package/dist/client/ui/index.js +1 -1
  27. package/dist/client/use-action.d.ts +8 -0
  28. package/dist/client/use-action.js +20 -3
  29. package/dist/collab/routes.d.ts +1 -1
  30. package/dist/db/create-get-db.d.ts +2 -1
  31. package/dist/db/create-get-db.js +99 -14
  32. package/dist/deploy/build-cache.js +10 -0
  33. package/dist/deploy/build.js +44 -5
  34. package/dist/deploy/workspace-deploy.js +46 -1
  35. package/dist/extensions/url-safety.d.ts +2 -0
  36. package/dist/extensions/url-safety.js +1 -0
  37. package/dist/framework-package-versions.json +7 -7
  38. package/dist/identity/offboard.d.ts +2 -0
  39. package/dist/identity/offboard.js +32 -0
  40. package/dist/org/auto-join-domain.js +11 -3
  41. package/dist/org/handlers.d.ts +16 -1
  42. package/dist/org/handlers.js +162 -42
  43. package/dist/org/index.d.ts +2 -1
  44. package/dist/org/index.js +1 -0
  45. package/dist/org/plugin.d.ts +2 -0
  46. package/dist/org/plugin.js +17 -1
  47. package/dist/org/types.d.ts +6 -0
  48. package/dist/provider-api/actions/custom-provider-registration.d.ts +16 -16
  49. package/dist/provider-api/actions/provider-api.d.ts +10 -10
  50. package/dist/resources/store.d.ts +5 -0
  51. package/dist/resources/store.js +54 -0
  52. package/dist/server/auth.js +3 -1
  53. package/dist/server/builder-browser.js +10 -1
  54. package/dist/server/document-build-id.d.ts +18 -0
  55. package/dist/server/document-build-id.js +43 -0
  56. package/dist/server/entry-server.js +3 -5
  57. package/dist/server/first-touch-route.d.ts +1 -1
  58. package/dist/server/onboarding-html.js +4 -3
  59. package/dist/server/workspace-provider-oauth.js +26 -6
  60. package/dist/sharing/actions/set-resource-visibility.js +36 -4
  61. package/dist/sharing/grant.js +10 -2
  62. package/dist/sharing/registry.d.ts +2 -0
  63. package/dist/templates/default/app/root.tsx +8 -2
  64. package/dist/triggers/dispatcher.d.ts +7 -0
  65. package/dist/triggers/dispatcher.js +13 -0
  66. package/dist/triggers/index.d.ts +1 -1
  67. package/dist/triggers/index.js +1 -1
  68. package/dist/user-profile/actions/update-user-profile.js +1 -1
  69. package/dist/vite/client.d.ts +2 -1
  70. package/dist/vite/client.js +5 -2
  71. package/dist/vitest-config.js +6 -0
  72. package/package.json +4 -4
  73. package/src/templates/default/app/root.tsx +8 -2
@@ -1,5 +1,11 @@
1
1
  import { addSurfaceVisibilityListener, isSurfaceHidden, } from "../shared/surface-visibility.js";
2
2
  const startedQueries = new WeakSet();
3
+ // A foreground read that failed is still the person's read: its retries stay
4
+ // foreground until its fetch answers, even when a previous result was cached.
5
+ const unansweredForeground = new WeakMap();
6
+ // An open tab whose read keeps failing must not stream foreground provider
7
+ // calls on every retry and refetch tick: past this many failures it is background.
8
+ const MAX_FOREGROUND_RETRIES = 3;
3
9
  const foregroundScopes = new WeakMap();
4
10
  const surfaceObservers = new Set();
5
11
  let surfaceWasHidden = false;
@@ -8,13 +14,32 @@ let removeVisibilityListener;
8
14
  export function claimActionQueryForeground(query) {
9
15
  if (!query)
10
16
  return false;
17
+ // Restored and projected cache rows have update counts, but no request in
18
+ // this document. Only a fetch claimed here can spend its first-read allowance.
11
19
  const initial = query.isActive() &&
12
20
  !startedQueries.has(query) &&
13
- query.state.data === undefined &&
14
21
  query.state.error === null &&
15
22
  query.state.fetchFailureCount === 0;
16
23
  startedQueries.add(query);
17
- return foregroundScopes.get(query) ?? initial;
24
+ const scoped = foregroundScopes.get(query);
25
+ const retry = unansweredForeground.get(query) === query.state.dataUpdateCount &&
26
+ query.isActive() &&
27
+ query.state.fetchFailureCount > 0 &&
28
+ query.state.fetchFailureCount <= MAX_FOREGROUND_RETRIES;
29
+ const foreground = scoped ?? (initial || retry);
30
+ if (foreground)
31
+ unansweredForeground.set(query, query.state.dataUpdateCount);
32
+ else
33
+ unansweredForeground.delete(query);
34
+ return foreground;
35
+ }
36
+ export function finishActionQueryOpening(query) {
37
+ // A fresh cache can answer the opening without a request. Its first later
38
+ // timer or reconnect fetch must not inherit the opening's allowance.
39
+ if (query?.isActive() &&
40
+ query.state.fetchStatus === "idle" &&
41
+ query.state.data !== undefined)
42
+ startedQueries.add(query);
18
43
  }
19
44
  function withQueryForeground(query, foreground, run) {
20
45
  foregroundScopes.set(query, foreground);
@@ -25,14 +50,36 @@ function withQueryForeground(query, foreground, run) {
25
50
  foregroundScopes.delete(query);
26
51
  }
27
52
  }
28
- export function invalidateForegroundActionQueries(client, filters, foreground) {
53
+ export function refetchActionQueryInForeground(query, run) {
54
+ if (!query || isSurfaceHidden())
55
+ return run();
56
+ return withQueryForeground(query, true, run);
57
+ }
58
+ export function invalidateForegroundActionQueries(client, filters, foreground, options) {
59
+ // Hydration supplies data before a hook supplies its reader. Keep those rows
60
+ // stale until the reader can fetch them, without creating a missing-queryFn error.
61
+ const dataOnly = new Set(client
62
+ .getQueryCache()
63
+ .findAll(filters)
64
+ .filter((query) => query.getObserversCount() === 0 &&
65
+ query.state.data !== undefined &&
66
+ query.options.queryFn === undefined));
67
+ for (const query of dataOnly)
68
+ query.invalidate();
69
+ const readableFilters = dataOnly.size
70
+ ? {
71
+ ...filters,
72
+ predicate: (query) => !dataOnly.has(query) &&
73
+ (!filters.predicate || filters.predicate(query)),
74
+ }
75
+ : filters;
29
76
  if (!foreground || isSurfaceHidden())
30
- return client.invalidateQueries(filters);
31
- const queries = client.getQueryCache().findAll(filters);
77
+ return client.invalidateQueries(readableFilters, options);
78
+ const queries = client.getQueryCache().findAll(readableFilters);
32
79
  for (const query of queries)
33
80
  foregroundScopes.set(query, true);
34
81
  try {
35
- return client.invalidateQueries(filters);
82
+ return client.invalidateQueries(readableFilters, options);
36
83
  }
37
84
  finally {
38
85
  for (const query of queries)
@@ -9,6 +9,7 @@ export { subscribeSessionInvalidation } from "../session-identity.js";
9
9
  export { registerSignOutCleanup, signOut, SignOutCleanupError, type SignOutCleanup, type SignOutOptions, } from "../sign-out.js";
10
10
  export { ACTION_KEEPALIVE_BODY_BUDGET_BYTES, actionErrorMessage, callAction, callActionBlob, callActionWithRetry, currentActionQueryCacheBinding, prepareUiActionCapability, recordActionQueryBrowserPersist, runActionQueryRead, tryCallActionKeepalive, useActionQuery, useActionQueryCanFetch, useActionMutation, type ActionRegistry, type PrivateActionMutationOptions, type PrivateActionMutationResult, type ClientActionCallOptions, type ClientActionMethod, type RetriedActionCallOptions, type KeepaliveActionCallRejectionReason, type KeepaliveActionCallResult, } from "../use-action.js";
11
11
  export { actionErrorCode, isTerminalActionError, } from "../action-failure-circuit.js";
12
+ export { invalidateForegroundActionQueries } from "../action-query-foreground.js";
12
13
  export { createAgentNativeQueryClient } from "../create-query-client.js";
13
14
  export { APP_CHAT_SIDEBAR_STATE_EVENT, APP_CHAT_SIDEBAR_STATE_MESSAGE, APP_CHAT_SIDEBAR_STATE_REQUEST_MESSAGE, buildAppChatSidebarStateMessage, buildAppChatSidebarStateRequest, isPerAppChatStorageKey, requestPerAppChatCommand, usePerAppChatState, usePerAppChatOpen, type AppChatSidebarCommand, type AppChatSidebarState, } from "../app-chat-sidebar.js";
14
15
  export { usePinchZoom, type UsePinchZoomOptions } from "../use-pinch-zoom.js";
@@ -9,6 +9,7 @@ export { subscribeSessionInvalidation } from "../session-identity.js";
9
9
  export { registerSignOutCleanup, signOut, SignOutCleanupError, } from "../sign-out.js";
10
10
  export { ACTION_KEEPALIVE_BODY_BUDGET_BYTES, actionErrorMessage, callAction, callActionBlob, callActionWithRetry, currentActionQueryCacheBinding, prepareUiActionCapability, recordActionQueryBrowserPersist, runActionQueryRead, tryCallActionKeepalive, useActionQuery, useActionQueryCanFetch, useActionMutation, } from "../use-action.js";
11
11
  export { actionErrorCode, isTerminalActionError, } from "../action-failure-circuit.js";
12
+ export { invalidateForegroundActionQueries } from "../action-query-foreground.js";
12
13
  export { createAgentNativeQueryClient } from "../create-query-client.js";
13
14
  export { APP_CHAT_SIDEBAR_STATE_EVENT, APP_CHAT_SIDEBAR_STATE_MESSAGE, APP_CHAT_SIDEBAR_STATE_REQUEST_MESSAGE, buildAppChatSidebarStateMessage, buildAppChatSidebarStateRequest, isPerAppChatStorageKey, requestPerAppChatCommand, usePerAppChatState, usePerAppChatOpen, } from "../app-chat-sidebar.js";
14
15
  export { usePinchZoom } from "../use-pinch-zoom.js";
@@ -1,6 +1,7 @@
1
1
  import { FIRST_RUN_ONBOARDING_COOKIE } from "../../shared/first-run-onboarding.js";
2
2
  import { getOrCreateAnalyticsSessionId } from "../analytics-session.js";
3
3
  import { agentNativePath } from "../api-path.js";
4
+ import { notifySessionInvalidated } from "../use-session.js";
4
5
  export const FIRST_RUN_ONBOARDING_STATUS_RESOLVED_EVENT = "agent-native:first-run-status-resolved";
5
6
  const FIRST_RUN_STATUS_TIMEOUT_MS = 5_000;
6
7
  let firstRunStatusRequest = null;
@@ -102,6 +103,9 @@ export async function completeFirstRunOnboarding(scope) {
102
103
  result.ok !== true) {
103
104
  throw new Error("First-run completion was not acknowledged.");
104
105
  }
106
+ // Setup can provision the workspace after the initial session read. Publish
107
+ // its current scope before releasing navigation that depends on that scope.
108
+ await notifySessionInvalidated();
105
109
  if (typeof window !== "undefined") {
106
110
  window.dispatchEvent(new CustomEvent("agent-native:first-run-completed"));
107
111
  }
@@ -1,5 +1,5 @@
1
1
  import type { IconValue } from "../../icons/index.js";
2
- import type { OrgInfo, OrgMember, OrgPendingInvitation, OrgRole } from "../../org/types.js";
2
+ import type { OrgDeactivatedMember, OrgInfo, OrgMember, OrgPendingInvitation, OrgRole } from "../../org/types.js";
3
3
  export declare function useOrg(options?: {
4
4
  enabled?: boolean;
5
5
  }): import("@tanstack/react-query").UseQueryResult<NoInfer<OrgInfo>, Error>;
@@ -58,9 +58,15 @@ export declare function useChangeMemberRole(): import("@tanstack/react-query").U
58
58
  role: InviteRole;
59
59
  }, unknown>;
60
60
  export declare function useAcceptInvitation(): import("@tanstack/react-query").UseMutationResult<any, Error, string, unknown>;
61
+ /** Members removed with `deactivate`, so a roster can badge them. */
62
+ export declare function useOrgDeactivatedMembers(): import("@tanstack/react-query").UseQueryResult<NoInfer<{
63
+ members: OrgDeactivatedMember[];
64
+ }>, Error>;
61
65
  export declare function useRemoveMember(): import("@tanstack/react-query").UseMutationResult<any, Error, {
62
66
  email: string;
63
67
  transferTo: string;
68
+ /** Keep a Deactivated record, listed by `useOrgDeactivatedMembers`. */
69
+ deactivate?: boolean;
64
70
  }, unknown>;
65
71
  /**
66
72
  * Withdraw a pending invitation. Without this an invite is final: a typo stays in the
@@ -96,6 +102,11 @@ export declare function useSetOrgVisualIdentity(): import("@tanstack/react-query
96
102
  export declare function useSwitchOrg(options?: {
97
103
  onPersisted?: (orgId: string | null) => void;
98
104
  }): import("@tanstack/react-query").UseMutationResult<any, Error, string | null, unknown>;
105
+ /** Leaves the active org; the server moves only the caller to another org they belong to. */
106
+ export declare function useLeaveOrg(): import("@tanstack/react-query").UseMutationResult<{
107
+ orgId: string;
108
+ nextOrgId: string | null;
109
+ }, Error, void, unknown>;
99
110
  export declare function useDeleteOrg(): import("@tanstack/react-query").UseMutationResult<any, Error, string, unknown>;
100
111
  export declare function useJoinByDomain(): import("@tanstack/react-query").UseMutationResult<any, Error, string, unknown>;
101
112
  export declare function useSetOrgDomain(): import("@tanstack/react-query").UseMutationResult<any, Error, string | null, unknown>;
@@ -176,12 +176,22 @@ export function useAcceptInvitation() {
176
176
  },
177
177
  });
178
178
  }
179
+ /** Members removed with `deactivate`, so a roster can badge them. */
180
+ export function useOrgDeactivatedMembers() {
181
+ const { data: org } = useOrg();
182
+ return useQuery({
183
+ queryKey: ["org-members", org?.orgId ?? null, "deactivated"],
184
+ queryFn: ({ signal }) => apiFetch(`${orgBasePath()}/members/deactivated`, { signal }),
185
+ enabled: () => Boolean(org?.orgId) && !agentNativeApiDisabledReason(),
186
+ staleTime: 30_000,
187
+ });
188
+ }
179
189
  export function useRemoveMember() {
180
190
  const qc = useQueryClient();
181
191
  return useMutation({
182
- mutationFn: ({ email, transferTo, }) => apiFetch(`${orgBasePath()}/members/${encodeURIComponent(email)}`, {
192
+ mutationFn: ({ email, transferTo, deactivate, }) => apiFetch(`${orgBasePath()}/members/${encodeURIComponent(email)}`, {
183
193
  method: "DELETE",
184
- body: JSON.stringify({ transferTo }),
194
+ body: JSON.stringify({ transferTo, deactivate }),
185
195
  }),
186
196
  onSuccess: async () => {
187
197
  await qc.invalidateQueries({ queryKey: ["org-members"] });
@@ -269,6 +279,18 @@ export function useSwitchOrg(options = {}) {
269
279
  },
270
280
  });
271
281
  }
282
+ /** Leaves the active org; the server moves only the caller to another org they belong to. */
283
+ export function useLeaveOrg() {
284
+ const qc = useQueryClient();
285
+ return useMutation({
286
+ mutationFn: () => apiFetch(`${orgBasePath()}/leave`, { method: "POST" }),
287
+ onSuccess: async () => {
288
+ const { notifySessionInvalidated } = await import("../use-session.js");
289
+ await notifySessionInvalidated();
290
+ await qc.invalidateQueries();
291
+ },
292
+ });
293
+ }
272
294
  export function useDeleteOrg() {
273
295
  const qc = useQueryClient();
274
296
  return useMutation({
@@ -156,7 +156,14 @@ export interface ShareButtonController {
156
156
  handleGeneralAccessRole: (role: ShareButtonRole) => void;
157
157
  handleVisibility: (visibility: ShareButtonVisibility) => void;
158
158
  handleHideInSearch: () => void;
159
- handleAdd: () => void;
159
+ /**
160
+ * Shares the typed field, or `email` as a person when given. A refused
161
+ * `email` goes to `onFailed` when it is passed, so several saves that fail
162
+ * together keep every address instead of overwriting one input.
163
+ */
164
+ handleAdd: (email?: string, options?: {
165
+ onFailed?: (email: string) => void;
166
+ }) => void;
160
167
  handleChangeRole: (share: ShareButtonShare, role: ShareButtonRole) => void;
161
168
  handleRemove: (share: ShareButtonShare) => void;
162
169
  }
@@ -340,23 +340,23 @@ export function useShareButtonController(options) {
340
340
  setShareError(extractShareErrorMessage(error));
341
341
  }
342
342
  }, [canManage, options.hideInSearchControl]);
343
- const handleAdd = useCallback(() => {
344
- const trimmed = inviteEmail.trim();
343
+ const handleAdd = useCallback((email, addOptions) => {
344
+ const trimmed = (email ?? inviteEmail).trim();
345
345
  if (!trimmed || !canManage)
346
346
  return;
347
+ const group = email === undefined ? selectedGroup : null;
348
+ const agent = email === undefined ? selectedAgent : null;
347
349
  const startedOnVisit = visitRef.current;
348
- const principalType = selectedGroup ? "group" : "user";
349
- const principalId = selectedGroup?.id ?? selectedAgent?.email ?? trimmed;
350
- const notify = principalType === "user" && !selectedAgent && notifyPeople;
350
+ const principalType = group ? "group" : "user";
351
+ const principalId = group?.id ?? agent?.email ?? trimmed;
352
+ const notify = principalType === "user" && !agent && notifyPeople;
351
353
  const message = notify ? shareMessage.trim() : "";
352
354
  const optimistic = {
353
355
  id: `pending-${principalType}-${principalId}`,
354
356
  principalType,
355
357
  principalId,
356
- ...(selectedGroup ? { displayName: selectedGroup.name } : {}),
357
- ...(selectedAgent
358
- ? { displayName: selectedAgent.name, agent: true }
359
- : {}),
358
+ ...(group ? { displayName: group.name } : {}),
359
+ ...(agent ? { displayName: agent.name, agent: true } : {}),
360
360
  role,
361
361
  };
362
362
  const key = keyOf(optimistic);
@@ -371,7 +371,9 @@ export function useShareButtonController(options) {
371
371
  setMessageOpen(false);
372
372
  setSuggestionsOpen(false);
373
373
  addInFlight(key);
374
- optimisticallyUpdateShareCache(queryClient, shareQueryKey, (cached) => cached ? { ...cached, shares: [...cached.shares, optimistic] } : cached);
374
+ optimisticallyUpdateShareCache(queryClient, shareQueryKey, (cached) => cached
375
+ ? { ...cached, shares: [...cached.shares, optimistic] }
376
+ : cached);
375
377
  void share
376
378
  .mutateAsync({
377
379
  resourceType: options.resourceType,
@@ -414,9 +416,14 @@ export function useShareButtonController(options) {
414
416
  : cached);
415
417
  setPendingAdds((previous) => previous.filter((item) => item.id !== optimistic.id));
416
418
  clearInFlight(key);
417
- setInviteEmail(trimmed);
418
- setSelectedGroup(selectedGroup);
419
- setSelectedAgent(selectedAgent);
419
+ if (email !== undefined && addOptions?.onFailed) {
420
+ addOptions.onFailed(trimmed);
421
+ }
422
+ else {
423
+ setInviteEmail(trimmed);
424
+ }
425
+ setSelectedGroup(group);
426
+ setSelectedAgent(agent);
420
427
  setShareMessage((current) => current || message);
421
428
  setMessageOpen((current) => current || Boolean(message));
422
429
  setShareError(extractShareErrorMessage(error));
@@ -1,4 +1,9 @@
1
1
  export type ThemePreference = "light" | "dark" | "system";
2
+ /**
3
+ * Apps served from one browser origin share localStorage, so each app keeps
4
+ * its preference under its own key.
5
+ */
6
+ export declare function themeStorageKeyForApp(appId?: string | null): string;
2
7
  export type ResolvedTheme = "light" | "dark";
3
8
  export declare const EMBEDDED_THEME_UPDATE_MESSAGE = "agent-native-theme-update";
4
9
  export declare const EMBEDDED_THEME_CHANGE_EVENT = "agent-native:theme-change";
@@ -15,5 +20,8 @@ export interface NormalizedEmbeddedThemeUpdate {
15
20
  export declare function parseEmbeddedThemeUpdate(value: unknown): NormalizedEmbeddedThemeUpdate | null;
16
21
  export declare function buildEmbeddedThemeUpdate(theme: ResolvedTheme, vars?: Record<string, string>): EmbeddedThemeUpdate;
17
22
  export declare function applyEmbeddedThemeUpdate(root: HTMLElement, update: NormalizedEmbeddedThemeUpdate): void;
18
- export declare function getThemeInitScript(defaultTheme?: ThemePreference, enableSystem?: boolean, appId?: string): string;
23
+ export declare function getThemeInitScript(defaultTheme?: ThemePreference, enableSystem?: boolean, appId?: string, storage?: {
24
+ storageKey?: string;
25
+ legacyStorageKey?: string;
26
+ }): string;
19
27
  export declare const themeInitScript: string;
@@ -2,6 +2,14 @@ import { getThemeFamilyInitScript } from "../appearance/theme-family.js";
2
2
  import { THEME_VAR_NAMES } from "../extensions/theme.js";
3
3
  import { injectedAgentNativeAppId, injectedAgentNativeConfig, } from "./app-config.js";
4
4
  import { getViteDevRecoveryScript, shouldInlineViteDevRecoveryScript, } from "./vite-dev-recovery-script.js";
5
+ /**
6
+ * Apps served from one browser origin share localStorage, so each app keeps
7
+ * its preference under its own key.
8
+ */
9
+ export function themeStorageKeyForApp(appId) {
10
+ const normalizedAppId = appId?.trim().toLowerCase();
11
+ return normalizedAppId ? `${normalizedAppId}:theme` : "theme";
12
+ }
5
13
  export const EMBEDDED_THEME_UPDATE_MESSAGE = "agent-native-theme-update";
6
14
  export const EMBEDDED_THEME_CHANGE_EVENT = "agent-native:theme-change";
7
15
  function isRecord(value) {
@@ -62,12 +70,17 @@ function normalizeDefaultTheme(theme) {
62
70
  }
63
71
  return "system";
64
72
  }
65
- export function getThemeInitScript(defaultTheme = "system", enableSystem = true, appId) {
73
+ export function getThemeInitScript(defaultTheme = "system", enableSystem = true, appId, storage = {}) {
66
74
  const safeDefaultTheme = normalizeDefaultTheme(defaultTheme);
67
75
  const systemEnabled = enableSystem ? "true" : "false";
68
76
  const themeFamilyAppId = appId ?? injectedAgentNativeAppId() ?? undefined;
69
77
  const themeFamilyConfig = injectedAgentNativeConfig().themeFamily;
70
- const themeScript = `${getThemeFamilyInitScript(themeFamilyAppId, themeFamilyConfig)}\n(function(){function m(){var d={};return{get length(){return Object.keys(d).length},key:function(i){return Object.keys(d)[i]||null},getItem:function(k){k=String(k);return Object.prototype.hasOwnProperty.call(d,k)?d[k]:null},setItem:function(k,v){d[String(k)]=String(v)},removeItem:function(k){delete d[k]},clear:function(){d={}}}}function s(n){try{var x=window[n],p='__an_storage_probe__';x.setItem(p,'1');x.removeItem(p)}catch(e){try{Object.defineProperty(window,n,{configurable:true,value:m()})}catch(_){}}}s('localStorage');s('sessionStorage');try{var defaultTheme=${JSON.stringify(safeDefaultTheme)};var enableSystem=${systemEnabled};var stored=window.localStorage.getItem('theme');var valid=stored==='light'||stored==='dark'||stored==='system'||stored==='auto';var mode=valid?stored:defaultTheme;if(mode==='auto')mode='system';if(!enableSystem&&mode==='system')mode=defaultTheme==='system'?'light':defaultTheme;if(!valid){window.localStorage.removeItem('theme')}else if(stored!==mode){window.localStorage.setItem('theme',mode)}var prefersDark=enableSystem&&mode==='system'&&window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches;var resolved=mode==='system'?(prefersDark?'dark':'light'):mode;var root=document.documentElement;root.classList.remove('light','dark');root.classList.add(resolved);root.setAttribute('data-theme',resolved);root.style.colorScheme=resolved;var appearance=window.localStorage.getItem('appearance');var appearanceValid=appearance==='warm'||appearance==='ocean'||appearance==='forest'||appearance==='rose'||appearance==='slate';if(appearanceValid){root.setAttribute('data-appearance',appearance)}else{root.removeAttribute('data-appearance');if(appearance!==null)window.localStorage.removeItem('appearance')}}catch(e){document.documentElement.setAttribute('data-theme-status','unreadable')}})();`;
78
+ const resolvedStorageKey = storage.storageKey ?? themeStorageKeyForApp(themeFamilyAppId);
79
+ const resolvedLegacyStorageKey = storage.legacyStorageKey ??
80
+ (resolvedStorageKey === "theme" ? null : "theme");
81
+ const storageKey = JSON.stringify(resolvedStorageKey);
82
+ const legacyStorageKey = JSON.stringify(resolvedLegacyStorageKey);
83
+ const themeScript = `${getThemeFamilyInitScript(themeFamilyAppId, themeFamilyConfig)}\n(function(){function m(){var d={};return{get length(){return Object.keys(d).length},key:function(i){return Object.keys(d)[i]||null},getItem:function(k){k=String(k);return Object.prototype.hasOwnProperty.call(d,k)?d[k]:null},setItem:function(k,v){d[String(k)]=String(v)},removeItem:function(k){delete d[k]},clear:function(){d={}}}}function s(n){try{var x=window[n],p='__an_storage_probe__';x.setItem(p,'1');x.removeItem(p)}catch(e){try{Object.defineProperty(window,n,{configurable:true,value:m()})}catch(_){}}}s('localStorage');s('sessionStorage');try{var defaultTheme=${JSON.stringify(safeDefaultTheme)};var enableSystem=${systemEnabled};var key=${storageKey},legacyKey=${legacyStorageKey};var stored=window.localStorage.getItem(key);var validStored=stored==='light'||stored==='dark'||stored==='system'||stored==='auto';if(legacyKey&&legacyKey!==key){var legacy=window.localStorage.getItem(legacyKey);if(legacy==='light'||legacy==='dark'||legacy==='system'||legacy==='auto'){stored=legacy;validStored=true}}var mode=validStored?stored:defaultTheme;if(mode==='auto')mode='system';if(!enableSystem&&mode==='system')mode=defaultTheme==='system'?'light':defaultTheme;if(!validStored){window.localStorage.removeItem(key)}else if(window.localStorage.getItem(key)!==mode){window.localStorage.setItem(key,mode)}if(legacyKey&&legacyKey!==key){window.localStorage.removeItem(legacyKey)}var prefersDark=enableSystem&&mode==='system'&&window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches;var resolved=mode==='system'?(prefersDark?'dark':'light'):mode;var root=document.documentElement;root.classList.remove('light','dark');root.classList.add(resolved);root.setAttribute('data-theme',resolved);root.style.colorScheme=resolved;var appearance=window.localStorage.getItem('appearance');var appearanceValid=appearance==='warm'||appearance==='ocean'||appearance==='forest'||appearance==='rose'||appearance==='slate';if(appearanceValid){root.setAttribute('data-appearance',appearance)}else{root.removeAttribute('data-appearance');if(appearance!==null)window.localStorage.removeItem('appearance')}}catch(e){document.documentElement.setAttribute('data-theme-status','unreadable')}})();`;
71
84
  // Keep this a direct `import.meta.env?.DEV` read (no alias): only then can the
72
85
  // bundler fold it and drop the dev recovery script from production client
73
86
  // bundles. `env` is optional because the production SSR build loads core
@@ -1,6 +1,6 @@
1
1
  export { buildErrorReportTemplate, buildGitHubIssueUrl, type ErrorReportDebugItem, type ErrorReportTemplateOptions, } from "../error-reporting.js";
2
2
  export { getClientSurface, type ClientSurface } from "../client-surface.js";
3
- export { applyEmbeddedThemeUpdate, buildEmbeddedThemeUpdate, EMBEDDED_THEME_CHANGE_EVENT, EMBEDDED_THEME_UPDATE_MESSAGE, getThemeInitScript, parseEmbeddedThemeUpdate, themeInitScript, type EmbeddedThemeUpdate, type NormalizedEmbeddedThemeUpdate, type ResolvedTheme, type ThemePreference, } from "../theme.js";
3
+ export { applyEmbeddedThemeUpdate, buildEmbeddedThemeUpdate, EMBEDDED_THEME_CHANGE_EVENT, EMBEDDED_THEME_UPDATE_MESSAGE, getThemeInitScript, parseEmbeddedThemeUpdate, themeInitScript, themeStorageKeyForApp, type EmbeddedThemeUpdate, type NormalizedEmbeddedThemeUpdate, type ResolvedTheme, type ThemePreference, } from "../theme.js";
4
4
  export { APPEARANCE_PRESETS, applyAppearance, getStoredAppearance, useAppearance, useAppearanceSync, type AppearancePresetId, } from "../appearance.js";
5
5
  export { resolveThemeFamilyConfig, resolveThemeFamilyPreference, type ResolvedThemeFamilyConfig, type ThemeFamilyConfig, } from "../../appearance/theme-family.js";
6
6
  export { applyThemeFamily, readStoredThemeFamily, THEME_FAMILY_CHANGE_EVENT, useThemeFamily, type StoredThemeFamily, type ThemeFamily, type ThemeFamilyApplyResult, type ThemeFamilyHook, type ThemeFamilyStorageStatus, } from "../theme-family.js";
@@ -1,6 +1,6 @@
1
1
  export { buildErrorReportTemplate, buildGitHubIssueUrl, } from "../error-reporting.js";
2
2
  export { getClientSurface } from "../client-surface.js";
3
- export { applyEmbeddedThemeUpdate, buildEmbeddedThemeUpdate, EMBEDDED_THEME_CHANGE_EVENT, EMBEDDED_THEME_UPDATE_MESSAGE, getThemeInitScript, parseEmbeddedThemeUpdate, themeInitScript, } from "../theme.js";
3
+ export { applyEmbeddedThemeUpdate, buildEmbeddedThemeUpdate, EMBEDDED_THEME_CHANGE_EVENT, EMBEDDED_THEME_UPDATE_MESSAGE, getThemeInitScript, parseEmbeddedThemeUpdate, themeInitScript, themeStorageKeyForApp, } from "../theme.js";
4
4
  export { APPEARANCE_PRESETS, applyAppearance, getStoredAppearance, useAppearance, useAppearanceSync, } from "../appearance.js";
5
5
  export { resolveThemeFamilyConfig, resolveThemeFamilyPreference, } from "../../appearance/theme-family.js";
6
6
  export { applyThemeFamily, readStoredThemeFamily, THEME_FAMILY_CHANGE_EVENT, useThemeFamily, } from "../theme-family.js";
@@ -193,6 +193,14 @@ export declare function useActionQuery<TResult = undefined, TName extends Action
193
193
  * polling and other automatic refetches never carry the interactive header.
194
194
  */
195
195
  interactive?: boolean;
196
+ /**
197
+ * With `interactive`, the returned `refetch()` is a foreground read when the
198
+ * surface is visible. Opt in only when every caller of `refetch()` is the
199
+ * person's own request (Try again, a readback after their write): a
200
+ * foreground-only provider pause refuses background refetches, so such a
201
+ * retry could otherwise never recover. Timers must not call it.
202
+ */
203
+ foregroundRefetch?: boolean;
196
204
  /**
197
205
  * Disable the transport's capability-recovery resend. All observers of a
198
206
  * shared query must use the same setting. Query retries are separate.
@@ -12,7 +12,7 @@ import { actionCircuitRemainingMs, actionErrorCode, actionErrorRetryAfterMs, act
12
12
  import { fetchActionGet } from "./action-get-batch.js";
13
13
  import { trustedActionQueryCacheBindingPendingContext } from "./action-query-cache-context.js";
14
14
  import { advanceMutationEpoch } from "./action-query-cache-mutation.js";
15
- import { claimActionQueryForeground, invalidateForegroundActionQueries, observeActionQuerySurface, } from "./action-query-foreground.js";
15
+ import { claimActionQueryForeground, finishActionQueryOpening, invalidateForegroundActionQueries, observeActionQuerySurface, refetchActionQueryInForeground, } from "./action-query-foreground.js";
16
16
  import { ACTION_RESOURCES_META_KEY, actionQueryAffectedByResources, } from "./action-query-scope.js";
17
17
  import { getAnalyticsClientPlatform } from "./analytics-platform.js";
18
18
  import { getOrCreateAnalyticsSessionId } from "./analytics-session.js";
@@ -1303,7 +1303,7 @@ function canBatchActionQueryFetch(query) {
1303
1303
  !query.observers.some((observer) => observer.options.meta?.[UNBATCHED_REFETCHES_META_KEY] === true));
1304
1304
  }
1305
1305
  export function useActionQuery(actionName, params, options) {
1306
- const { refetchInterval, interactive = false, retry: callerRetry, enabled: callerEnabled, queryKeyScope, resources, batchRefetches, onRequestStart, onServerResult, onServerError, method = "GET", beforeSend, uiOnly, retryUiCapability, ...restOptions } = options ?? {};
1306
+ const { refetchInterval, interactive = false, foregroundRefetch = false, retry: callerRetry, enabled: callerEnabled, queryKeyScope, resources, batchRefetches, onRequestStart, onServerResult, onServerError, method = "GET", beforeSend, uiOnly, retryUiCapability, ...restOptions } = options ?? {};
1307
1307
  const queryKey = ["action", actionName, params, ...(queryKeyScope ?? [])];
1308
1308
  const queryClient = useQueryClient();
1309
1309
  const canFetch = useActionQueryCanFetch(queryKey);
@@ -1336,7 +1336,7 @@ export function useActionQuery(actionName, params, options) {
1336
1336
  (policy !== false && query.isStaleByTime(staleTime))));
1337
1337
  }, interactive, () => surfaceOptions.current.restOptions.refetchOnWindowFocus !== undefined);
1338
1338
  }, [interactive, queryClient, queryHash]);
1339
- return useQuery({
1339
+ const result = useQuery({
1340
1340
  queryKey,
1341
1341
  queryFn: async ({ signal, client }) => {
1342
1342
  const key = circuitKey();
@@ -1435,6 +1435,23 @@ export function useActionQuery(actionName, params, options) {
1435
1435
  : {}),
1436
1436
  refetchOnWindowFocus: false,
1437
1437
  });
1438
+ // QueryObserver must apply enabled changes before closing a cached opening. The result is not
1439
+ // read here: React Query tracks the fields a render reads, and reading extra ones narrows what
1440
+ // re-renders a caller that reads `data` outside render.
1441
+ useEffect(() => {
1442
+ if (interactive)
1443
+ finishActionQueryOpening(queryClient.getQueryCache().get(queryHash));
1444
+ });
1445
+ // Held in a ref so the wrapper keeps one identity across renders and never reads a result field.
1446
+ const latestResult = useRef(result);
1447
+ latestResult.current = result;
1448
+ const foregroundRefetchFn = useCallback((refetchOptions) => refetchActionQueryInForeground(queryClient.getQueryCache().get(queryHash), () => latestResult.current.refetch(refetchOptions)), [queryClient, queryHash]);
1449
+ if (!interactive || !foregroundRefetch)
1450
+ return result;
1451
+ // Proxy, not spread: React Query tracks which result fields a component reads.
1452
+ return new Proxy(result, {
1453
+ get: (target, key) => key === "refetch" ? foregroundRefetchFn : Reflect.get(target, key),
1454
+ });
1438
1455
  }
1439
1456
  /**
1440
1457
  * A write that names its resources refreshes only the action queries tagged for
@@ -26,8 +26,8 @@ export declare const postCollabUpdate: import("h3").EventHandlerWithFetch<import
26
26
  ok: boolean;
27
27
  }>>;
28
28
  export declare const postCollabText: import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<{
29
- text?: undefined;
30
29
  ok?: undefined;
30
+ text?: undefined;
31
31
  error: string;
32
32
  } | {
33
33
  error?: undefined;
@@ -1,4 +1,5 @@
1
- import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core";
1
+ import { PgDatabase } from "drizzle-orm/pg-core";
2
+ import type { PgQueryResultHKT } from "drizzle-orm/pg-core";
2
3
  /**
3
4
  * Routes `getDb()` and `getDbExec()` calls made inside a root transaction of
4
5
  * `db` onto that transaction, and marks the transaction as holding `pool`'s
@@ -1,6 +1,6 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import { sql } from "drizzle-orm";
3
- import { QueryBuilder } from "drizzle-orm/pg-core";
2
+ import { is, sql, Subquery, WithSubquery } from "drizzle-orm";
3
+ import { PgDatabase, PgDialect, QueryBuilder } from "drizzle-orm/pg-core";
4
4
  import { annotateMissingTable, dbExecQueryBudget, getActivePgliteTransactionClient, getRuntimeDatabaseUrl, hasExplicitDbTimeout, isPgliteUrl, isConnectionError, getPgliteClient, loadPgliteDrizzle, pgliteDrizzleClient, pgPoolOptions, neonPoolOptions, guardNeonPool, withDbTimeout, retryOnConnectionError, hasRetryBudgetFor, dbOpTimeoutMs, sharedDbPool, resolveSharedDbPool, toPostgresParams, withDbExec, onSharedDbPoolsClosed, onSharedDbPoolReplaced, onDbClientsClosing, postgresStatementTimeoutMs, assertHostedRuntimeDatabase, } from "./client.js";
5
5
  import { noteSqlStatement } from "./note-sql-statement.js";
6
6
  import { assertPoolConnectionAvailable, runHoldingPoolConnection, } from "./pool-self-deadlock.js";
@@ -697,6 +697,9 @@ export function buildResilientPostgresJsClient(client, getActivePool = () => cli
697
697
  export function isNeonUrl(url) {
698
698
  return /\.neon\.tech([:/?]|$)/.test(url);
699
699
  }
700
+ const lazyQueryChains = new WeakMap();
701
+ // Chain steps are shared by derived proxies and by offline and connected replay.
702
+ const callbackResults = new WeakMap();
700
703
  export function createGetDb(schema) {
701
704
  let _db;
702
705
  let _dbReady;
@@ -809,17 +812,87 @@ export function createGetDb(schema) {
809
812
  }), client, getActivePool);
810
813
  });
811
814
  }
815
+ function isSelectChain(chain) {
816
+ const first = chain[0]?.prop;
817
+ const select = first === "with" ? chain[1]?.prop : first;
818
+ return (select === "select" ||
819
+ select === "selectDistinct" ||
820
+ select === "selectDistinctOn");
821
+ }
822
+ function resolveOfflineQuery(query) {
823
+ const lazyChain = (typeof query === "function" || (typeof query === "object" && query)) &&
824
+ lazyQueryChains.get(query);
825
+ if (!lazyChain)
826
+ return query;
827
+ const replayed = replayChainOffline(lazyChain);
828
+ if (replayed)
829
+ return replayed;
830
+ throw new Error("getDb(): accessed an unresolved query chain synchronously. " +
831
+ "Only select-style query chains can be embedded as a subquery " +
832
+ "before the database is ready; await the database handle " +
833
+ "(await getDb()) before constructing the query.");
834
+ }
835
+ function resolveChainArgs(chain, step) {
836
+ const args = step.args ?? [];
837
+ const select = isSelectChain(chain);
838
+ const cte = chain[0]?.prop === "$with" && step.prop === "as";
839
+ const setOperator = select &&
840
+ (step.prop === "union" ||
841
+ step.prop === "unionAll" ||
842
+ step.prop === "intersect" ||
843
+ step.prop === "intersectAll" ||
844
+ step.prop === "except" ||
845
+ step.prop === "exceptAll");
846
+ const callbackIndex = cte ||
847
+ setOperator ||
848
+ (select &&
849
+ (step.prop === "where" ||
850
+ step.prop === "having" ||
851
+ step.prop === "groupBy" ||
852
+ step.prop === "orderBy"))
853
+ ? 0
854
+ : select &&
855
+ typeof step.prop === "string" &&
856
+ /^(?:left|right|inner|full)Join(?:Lateral)?$/.test(step.prop)
857
+ ? 1
858
+ : -1;
859
+ return args.map((argument, index) => {
860
+ if (index !== callbackIndex)
861
+ return argument;
862
+ const queryArgument = cte || setOperator;
863
+ const resolved = queryArgument ? resolveOfflineQuery(argument) : argument;
864
+ if (typeof resolved !== "function")
865
+ return resolved;
866
+ return (...callbackArgs) => {
867
+ let results = callbackResults.get(step);
868
+ if (!results) {
869
+ results = new Map();
870
+ callbackResults.set(step, results);
871
+ }
872
+ const cached = results.get(index);
873
+ if (cached)
874
+ return cached.value;
875
+ const value = resolved(...callbackArgs);
876
+ const result = queryArgument ? resolveOfflineQuery(value) : value;
877
+ results.set(index, { value: result });
878
+ return result;
879
+ };
880
+ });
881
+ }
812
882
  // A select chain embedded as a subquery only needs its SQL, which a
813
883
  // connection-less QueryBuilder of the same dialect can build. Anything else
814
884
  // (inserts, relational queries, ...) cannot be answered offline.
815
885
  function replayChainOffline(chain) {
816
886
  const first = chain[0]?.prop;
817
- if (first !== "select" &&
818
- first !== "selectDistinct" &&
819
- first !== "selectDistinctOn") {
887
+ if (!isSelectChain(chain) &&
888
+ !(first === "$with" && chain.length === 2 && chain[1]?.prop === "as")) {
820
889
  return undefined;
821
890
  }
822
- let result = new QueryBuilder();
891
+ // QueryBuilder.with() drops the WITH list for distinct selects; PgDatabase's
892
+ // builders preserve it and remain connection-less until execution.
893
+ let result = first === "with"
894
+ ? new PgDatabase(new PgDialect(), undefined, undefined)
895
+ : new QueryBuilder();
823
896
  for (const step of chain) {
824
897
  if (step.prop === "execute")
825
898
  return undefined;
@@ -827,13 +900,13 @@ export function createGetDb(schema) {
827
900
  return undefined;
828
901
  const target = result;
829
902
  const val = target[step.prop];
830
- result =
831
- typeof val === "function" ? val.apply(target, step.args ?? []) : val;
903
+ const args = resolveChainArgs(chain, step);
904
+ result = typeof val === "function" ? val.apply(target, args) : val;
832
905
  }
833
906
  return result;
834
907
  }
835
908
  function createLazyProxy(ready, chain) {
836
- return new Proxy(function () { }, {
909
+ const proxy = new Proxy(function () { }, {
837
910
  get(_target, prop) {
838
911
  if (prop === "then" || prop === "catch" || prop === "finally") {
839
912
  const promise = ready.then((readyDb) => {
@@ -841,14 +914,18 @@ export function createGetDb(schema) {
841
914
  for (const step of chain) {
842
915
  const val = result[step.prop];
843
916
  result =
844
- typeof val === "function" ? val.apply(result, step.args) : val;
917
+ typeof val === "function"
918
+ ? val.apply(result, resolveChainArgs(chain, step))
919
+ : val;
845
920
  }
846
921
  return result;
847
922
  });
848
923
  promise.catch(() => { });
849
924
  return promise[prop].bind(promise);
850
925
  }
851
- if (prop === "getSQL" || prop === "shouldOmitSQLParens") {
926
+ if (prop === "getSQL" ||
927
+ prop === "getSelectedFields" ||
928
+ prop === "shouldOmitSQLParens") {
852
929
  const replayed = replayChainOffline(chain);
853
930
  const member = replayed?.[prop];
854
931
  if (typeof member === "function")
@@ -859,19 +936,27 @@ export function createGetDb(schema) {
859
936
  throw new Error("getDb(): accessed an unresolved query chain synchronously " +
860
937
  `(reading '${String(prop)}'). Only select-style query chains ` +
861
938
  "can be embedded as a subquery before the database is ready; " +
862
- "await this chain before using its result.");
939
+ "await the database handle (await getDb()) before constructing the query.");
863
940
  }
864
941
  return createLazyProxy(ready, [...chain, { prop }]);
865
942
  },
866
943
  apply(_target, _thisArg, args) {
867
- if (chain.length === 0)
944
+ const last = chain.at(-1);
945
+ if (last === undefined)
868
946
  return createLazyProxy(ready, []);
869
- const last = chain[chain.length - 1];
870
947
  const newChain = chain.slice(0, -1);
871
948
  newChain.push({ prop: last.prop, args });
949
+ if (last.prop === "as") {
950
+ const replayed = replayChainOffline(newChain);
951
+ if (is(replayed, Subquery) || is(replayed, WithSubquery)) {
952
+ return replayed;
953
+ }
954
+ }
872
955
  return createLazyProxy(ready, newChain);
873
956
  },
874
957
  });
958
+ lazyQueryChains.set(proxy, chain);
959
+ return proxy;
875
960
  }
876
961
  function getDb() {
877
962
  const dependencies = getDbDependencies(getDb);