moi-computer 0.13.1-next.2 → 0.13.1-next.4

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 (109) hide show
  1. package/client/app/app-provider.tsx +14 -20
  2. package/client/app/app-router.tsx +5 -8
  3. package/client/app/routes/workspace-route.tsx +28 -11
  4. package/client/app/shell/sidebar-layout.tsx +5 -10
  5. package/client/features/app-settings/api.ts +3 -3
  6. package/client/features/applets/applet-cache.ts +1 -2
  7. package/client/features/applets/use-applet.ts +18 -20
  8. package/client/features/chat/chat-store.ts +1 -1
  9. package/client/features/chat/connection/chat-connection.ts +25 -68
  10. package/client/features/chat/connection/chat-frames.ts +20 -32
  11. package/client/features/chat/sessions/api.ts +2 -2
  12. package/client/features/chat/sessions/use-selected-session.ts +0 -13
  13. package/client/features/collab/presence/client.ts +63 -83
  14. package/client/features/collab/presence/provider.tsx +8 -2
  15. package/client/features/dev/chat-states-page.tsx +1 -1
  16. package/client/features/dev/harness-debug-page.tsx +2 -2
  17. package/client/features/scratchpad/scratchpad.tsx +29 -20
  18. package/client/features/views/api.ts +38 -14
  19. package/client/features/views/use-view-actions.ts +2 -23
  20. package/client/features/workspace/api.ts +6 -11
  21. package/client/features/workspace/harness-transition.ts +3 -5
  22. package/client/features/workspace/remote.ts +9 -0
  23. package/client/features/workspace/settings/use-env-vars.ts +4 -4
  24. package/client/features/workspace/tab-resolution.ts +1 -8
  25. package/client/features/workspace/use-workspace-navigation.ts +5 -4
  26. package/client/features/workspace/use-workspace-socket.ts +51 -0
  27. package/client/features/workspace/workspace-content.tsx +5 -18
  28. package/client/features/workspace/workspace-layout-context.tsx +6 -13
  29. package/client/features/workspace/workspace-preferences.ts +67 -10
  30. package/client/features/workspace/workspace-state.ts +57 -21
  31. package/client/runtime/app-context.ts +2 -2
  32. package/client/runtime/app-events.ts +75 -0
  33. package/client/runtime/reconnecting-socket.ts +115 -0
  34. package/client/runtime/{use-workspace-events.ts → use-client-events.ts} +9 -10
  35. package/client/store/ui.ts +1 -6
  36. package/client/store/workspace-session.ts +30 -0
  37. package/dist/chunk-0t8m1ehd.js +2 -0
  38. package/dist/chunk-851bx8ss.js +72 -0
  39. package/dist/{chunk-n0fawy9x.js → chunk-c8g5x288.js} +1 -1
  40. package/dist/chunk-cty37f3v.js +1 -0
  41. package/dist/chunk-dy6f6h3e.js +5 -0
  42. package/dist/chunk-j6928pwm.js +1 -0
  43. package/dist/{chunk-rmd0ctfx.js → chunk-k32585ne.js} +73 -73
  44. package/dist/chunk-qtkv7hp8.js +2 -0
  45. package/dist/chunk-rh58dc0y.js +2 -0
  46. package/dist/{chunk-ec5ennpv.js → chunk-wjbejzek.js} +1 -1
  47. package/dist/index.html +1 -1
  48. package/lib/events.ts +61 -0
  49. package/lib/ids.ts +2 -8
  50. package/lib/moi-context.ts +19 -5
  51. package/lib/types.ts +16 -20
  52. package/lib/workspace-layout.ts +3 -20
  53. package/package.json +2 -1
  54. package/server/AGENTS.md +4 -4
  55. package/server/README.md +50 -33
  56. package/server/api/index.ts +175 -152
  57. package/server/applets/views.ts +15 -14
  58. package/server/applets/widgets.ts +4 -3
  59. package/server/cli/commands/init.ts +7 -2
  60. package/server/cli/commands/refresh.ts +2 -5
  61. package/server/cli/commands/remote.ts +128 -26
  62. package/server/cli/remote-control.ts +12 -9
  63. package/server/cli/remote-operations.ts +47 -44
  64. package/server/control.ts +33 -34
  65. package/server/events.ts +14 -13
  66. package/server/harness/README.md +7 -7
  67. package/server/harness/acp/session.ts +9 -5
  68. package/server/harness/auth.ts +7 -30
  69. package/server/harness/claude-code/session.ts +8 -4
  70. package/server/harness/codex/NOTES.md +1 -1
  71. package/server/harness/codex/session.ts +18 -10
  72. package/server/harness/hermes/NOTES.md +3 -3
  73. package/server/harness/openclaw/session.ts +9 -5
  74. package/server/onboarding/jobs.ts +8 -8
  75. package/server/operations/commands.ts +1 -1
  76. package/server/remote/broker-client.ts +76 -0
  77. package/server/remote/broker.ts +81 -0
  78. package/server/remote/client.ts +212 -152
  79. package/server/remote/errors.ts +2 -0
  80. package/server/remote/routes.ts +121 -0
  81. package/server/scratchpad/document.ts +3 -2
  82. package/server/scratchpad/executor.ts +2 -2
  83. package/server/scratchpad/relay.ts +3 -3
  84. package/server/sessions/archive.ts +1 -1
  85. package/server/sessions/lifecycle.ts +1 -1
  86. package/server/sessions/pending-views.ts +19 -12
  87. package/server/sessions/send-message.ts +102 -0
  88. package/server/sessions/view-sessions.ts +4 -94
  89. package/server/web.ts +42 -31
  90. package/server/workspace-state/file.ts +2 -0
  91. package/server/workspace-state/index.ts +15 -4
  92. package/server/workspaces/api.ts +4 -8
  93. package/server/workspaces/config.ts +14 -13
  94. package/server/workspaces/env-apply.ts +1 -1
  95. package/server/workspaces/layout.ts +40 -7
  96. package/server/workspaces/shared.ts +1 -1
  97. package/server/workspaces/tabs.ts +1 -2
  98. package/skill/SKILL.md +75 -34
  99. package/skill/references/SCRATCHPAD.md +4 -0
  100. package/skill/references/UI-COMPONENTS.md +1 -1
  101. package/client/features/scratchpad/scratch-executor.ts +0 -20
  102. package/client/runtime/workspace-events.ts +0 -168
  103. package/dist/chunk-44khk4sp.js +0 -2
  104. package/dist/chunk-ba6mz56s.js +0 -72
  105. package/dist/chunk-ectsnw81.js +0 -2
  106. package/dist/chunk-en7w5ypg.js +0 -1
  107. package/dist/chunk-f695wcx5.js +0 -5
  108. package/dist/chunk-pdt9hxfw.js +0 -2
  109. package/dist/chunk-zv22wv0g.js +0 -1
@@ -16,5 +16,5 @@ export function applyEnvChanged(workspace: { id: string; path: string }): void {
16
16
  // Env can carry credentials (ANTHROPIC_API_KEY, provider config) — drop the
17
17
  // cached availability so the next agent snapshot re-probes.
18
18
  harnessStore.invalidate(workspace)
19
- publishEvent({ type: 'env:updated', workspaceId: workspace.id })
19
+ publishEvent({ type: 'env:changed', workspaceId: workspace.id })
20
20
  }
@@ -1,4 +1,4 @@
1
- import { mkdir, writeFile } from 'node:fs/promises'
1
+ import { mkdir, rename, rm, writeFile } from 'node:fs/promises'
2
2
  import {
3
3
  parseRemoteWorkspaceConfig,
4
4
  parseRemoteWorkspaceTarget,
@@ -7,7 +7,12 @@ import {
7
7
  } from '@/lib/workspace-config'
8
8
  import { join } from 'path'
9
9
 
10
- import type { AppletKind, WorkspaceLayout, WorkspacePreview } from '@/lib/types'
10
+ import type {
11
+ AppletKind,
12
+ WorkspaceLayout,
13
+ WorkspaceLayoutPatch,
14
+ WorkspacePreview
15
+ } from '@/lib/types'
11
16
  import { createDefaultWorkspaceLayout } from '@/lib/workspace-layout'
12
17
  import { isWorkspaceIcon } from '@/lib/workspace-icon'
13
18
 
@@ -49,17 +54,45 @@ export async function loadLayout(workspacePath: string): Promise<WorkspaceLayout
49
54
  return config
50
55
  }
51
56
 
57
+ const pendingWrites = new Map<string, Promise<unknown>>()
58
+
59
+ export async function updateLayout(
60
+ workspacePath: string,
61
+ update: (current: WorkspaceLayout) => WorkspaceLayout
62
+ ) {
63
+ const path = getLayoutPath(workspacePath)
64
+ const write = async () => {
65
+ const current = await loadWorkspaceFileConfig(workspacePath)
66
+ if (current.remote)
67
+ throw new Error('Cannot replace a remote workspace reference with a local layout')
68
+ const layout = update(current)
69
+ const temporary = `${path}.${crypto.randomUUID()}.tmp`
70
+ try {
71
+ await Bun.write(temporary, JSON.stringify(layout, null, 2))
72
+ await rename(temporary, path)
73
+ } finally {
74
+ await rm(temporary, { force: true })
75
+ }
76
+ return { layout, changed: JSON.stringify(current) !== JSON.stringify(layout) }
77
+ }
78
+ const previous = pendingWrites.get(path) ?? Promise.resolve()
79
+ const run = previous.then(write, write)
80
+ pendingWrites.set(path, run)
81
+ try {
82
+ return await run
83
+ } finally {
84
+ if (pendingWrites.get(path) === run) pendingWrites.delete(path)
85
+ }
86
+ }
87
+
52
88
  export async function saveLayout(layout: WorkspaceLayout, workspacePath: string): Promise<void> {
53
- const existing = await loadWorkspaceFileConfig(workspacePath)
54
- if (existing.remote)
55
- throw new Error('Cannot replace a remote workspace reference with a local layout')
56
- await Bun.write(getLayoutPath(workspacePath), JSON.stringify(layout, null, 2))
89
+ await updateLayout(workspacePath, () => layout)
57
90
  }
58
91
 
59
92
  // The editor owns widgets and theme; identity changes use the config API.
60
93
  export function mergeLayoutForSave(
61
94
  existing: WorkspaceLayout,
62
- body: WorkspaceLayout
95
+ body: WorkspaceLayoutPatch
63
96
  ): WorkspaceLayout {
64
97
  return normalizeLayout({
65
98
  ...existing,
@@ -46,7 +46,7 @@ export async function openSharedWorkspace(remote: RemoteWorkspaceTarget, harness
46
46
  await rm(path, { recursive: true, force: true })
47
47
  throw error
48
48
  }
49
- publishEvent({ type: 'workspaces-list:updated' })
49
+ publishEvent({ type: 'workspaces-list:changed' })
50
50
  return entry
51
51
  })
52
52
  }
@@ -2,8 +2,7 @@
2
2
  import type { ViewInfo, WorkspaceTabId } from '@/lib/types'
3
3
  import { viewTabId } from '@/lib/workspace-tabs'
4
4
 
5
- // One row of `moi tabs`. Open tabs are a per-browser preference, so the server
6
- // lists destinations only.
5
+ // `moi tabs` lists all destinations, regardless of which tabs are open.
7
6
  export type TabRow = {
8
7
  id: WorkspaceTabId
9
8
  title: string
package/skill/SKILL.md CHANGED
@@ -10,9 +10,10 @@ description: The Moi workspace — the web UI the user chats from, extended with
10
10
  "Workspace" or "Moi Workspace" — the web UI that the user works in, talks/collaborates with you,
11
11
  sees and interacts with "Applets".
12
12
 
13
- "Project" - the primary working folder _you_ (as an agent) work in. Managed by your harness; Moi
14
- does not have a clear definition, but assumes this is the root folder in which it stores its state
15
- files.
13
+ "Workspace dir" — the primary working folder _you_ (as an agent) work in. Workspace files are stored here;
14
+ it also contains `.moi/`, which holds configuration, applets, applet, dependencies and other workspace extensions.
15
+
16
+ "Remote workspace" - Moi Workspace running on a different machine that someone else shared with the user and you.
16
17
 
17
18
  "Chat" — a conversation between the user and an agent in the workspace.
18
19
 
@@ -50,25 +51,31 @@ User can switch between these, but can access the chat (this conversation and ot
50
51
 
51
52
  ## Working in the workspace
52
53
 
53
- ### Local or remote workspace
54
+ ### Local or Remote workspaces
55
+
56
+ Workspace can be either:
57
+
58
+ **Local** workspace dir is stored on this computer. You have full control over it. You
59
+ interact with it using filesystem operations and by calling moi cli.
60
+
61
+ **Remote**. Workspace is running on someone else's ("owner") computer and it is shared with the user.
62
+ In this case, there are two dirs and two computers:
54
63
 
55
- Before working, read `remote` in `.moi/.workspace.json` (read only; never edit the file). A missing
56
- file or absent `remote` means local, and the rest of this section does not apply.
64
+ _Owner dir_ for the owner, looks like a regular local workspace. Has the file structure described in
65
+ "Files and Folders" section. Owner's agent runs there and it interact with it by using regular file ops.
66
+ Source of truth for shared workspace files and content, including applets, extensions, and shared data.
67
+ Everything in the dir is shared with all members. Each visitor’s chats, pending views, and agent settings
68
+ remain personal and are managed by their own Moi instance.
57
69
 
58
- `remote: { user_id, workspace_id }` means the workspace lives on its owner's machine. This folder
59
- holds only the reference and skills.
70
+ _Linked dir_ is on this computer. It's your local working folder, no other user sees it. `.moi` folder is
71
+ stripped down, only contains meta that this folder is linked to remote workspace. All files here are for
72
+ private and intermediate work. You can also interact with the remote workspace and owner dir using
73
+ subset of regular `moi` commands and also `moi remote` commands. Do not create local applet copies and
74
+ prefer not to store workspace state here (it gets out of sync quickly). Full command reference is in
75
+ "Using the Moi CLI"
60
76
 
61
- - Edit shared files with `moi remote read`, `write`, `patch`, `file-upload`, and `file-download`;
62
- paths are relative to the owner's workspace root. `moi remote exec '<command>'` runs there.
63
- - Use the ordinary commands from this folder as usual. `moi check`, `bundle`, `views`, `theme`,
64
- `config`, `tabs`, `call-server-fn`, `debug logs`, and scratchpad reads/edits act on the owner.
65
- - `moi refresh`, `navigate`, and `scratch view` act on your user's running Moi and browser. Refresh
66
- after remote changes.
67
- - Image input and output paths refer to the machine running the CLI. `config icon` and
68
- `scratch add image` upload local files to the owner; `scratch read-image` saves the owner's
69
- image locally, and `scratch view --out` saves the visitor browser's canvas screenshot locally.
70
- - Never create local applet copies or fall back to local content when the owner is unavailable.
71
- Remote chat and the settings UI are unavailable.
77
+ The newest `<moi-context>` identifies whether the workspace is local or remote. If it does not,
78
+ run `moi remote` to check.
72
79
 
73
80
  ### Boundaries
74
81
 
@@ -79,11 +86,11 @@ holds only the reference and skills.
79
86
 
80
87
  ### Files and folders
81
88
 
82
- For local workspaces, the source of truth is the `.moi` folder in the root of "Project" folder. Contains source code of all
89
+ For local workspaces, the source of truth is the `.moi` folder inside the workspace dir. Contains source code of all
83
90
  Applets, bundled code, settings, etc. Can be committed to version control. Folder is partially
84
91
  initialised when Workspace starts, you have full ownership of it.
85
92
 
86
- You _do have_ access to the files in the root of Project — you can reference and load them from the
93
+ You _do have_ access to the files in the workspace dir — you can reference and load them from the
87
94
  "Applets" and elsewhere.
88
95
 
89
96
  Folder structure:
@@ -103,17 +110,17 @@ my-agent-folder/
103
110
  users-api.server.ts <- Server-side async functions the view can call (optional)
104
111
  ...
105
112
  package.json <- Applet dependencies that you manage
106
- .workspace.json <- Internal config. Only read `remote` for the check above; do not edit.
113
+ .workspace.json <- Internal config. Do not edit.
107
114
  .scratchpad.json <- Scratchpad canvas snapshot. Internal — inspect only via `moi scratch read`, never open it.
108
115
  .scratchpad/ <- Scratchpad image files. Internal — pull pixels via `moi scratch read-image`, never open it.
109
116
  ```
110
117
 
111
118
  Every dot-prefixed file or folder inside `.moi/` (`.build/`, `.cache/`, `.workspace.json`,
112
119
  `.scratchpad*`, `.gitignore`, …) is a Moi internal: auto-generated and liable to change format
113
- without notice. Except for the read-only `remote` check above, do not read, edit, or delete them, and never point
120
+ without notice. Do not read, edit, or delete them, and never point
114
121
  tooling at them; go through the `moi` CLI instead. Version control needs no special handling: the
115
- scaffolded `.moi/.gitignore` already excludes the machine-local entries (`.build/`, `.cache/`,
116
- `node_modules/`), while `.workspace.json` and `.scratchpad.json` are workspace state that ships
122
+ scaffolded `.moi/.gitignore` already excludes the machine-local entries (e.g. `.build/`), while
123
+ `.workspace.json` and `.scratchpad.json` are workspace state that ships
117
124
  with the repo — commit them as-is, just never hand-edit them. Your surface is the non-dot files:
118
125
  `widgets/`, `views/`, `package.json`, and code you place under `.moi/` yourself.
119
126
 
@@ -121,7 +128,7 @@ with the repo — commit them as-is, just never hand-edit them. Your surface is
121
128
 
122
129
  Treat `moi` as an external command — you cannot inspect or modify its sources. Use only the
123
130
  documented subcommands (`moi bundle`, `moi bundle --force`, etc.). Call `moi --help` for
124
- documentation. Run all `moi` commands from the **project root** — the folder that contains `.moi/`,
131
+ documentation. Run all `moi` commands from the **workspace dir** — the folder that contains `.moi/`,
125
132
  never from inside `.moi/` itself. You don't pass paths; Moi resolves the workspace from where it's run.
126
133
 
127
134
  Use the task-specific sections below for workflow guidance. The CLI will grow over time, so run
@@ -135,6 +142,32 @@ Use the task-specific sections below for workflow guidance. The CLI will grow ov
135
142
  - **Use workspace env:** `moi env` and `moi env exec` (see Environment and secrets).
136
143
  - **Maintain workspace guidance:** `moi skill` (see Keeping this skill current).
137
144
 
145
+ #### How CLI works in a linked to remote workspace dir
146
+
147
+ These commands only work in linked dir of the Remote workspace. They allow you to manage the host
148
+ workspace, write applets, work with files etc. Remote file paths are relative to the owner dir.
149
+ Upload sources, download destinations, and `--patch-file` paths refer to your machine.
150
+ For full reference, run `moi remote --help`
151
+
152
+ ```sh
153
+ moi remote # Show identity, link, help
154
+ moi remote exec 'ls .moi/views' # List files on the host
155
+ moi remote read .moi/views/dashboard.tsx # Read a host file
156
+ moi remote write .moi/notes.txt "Hello" # Create or overwrite a host file
157
+ moi remote patch .moi/views/dashboard.tsx --patch-file ./change.diff # Apply a local diff
158
+ moi remote file-upload ./chart.png .moi/chart.png # local → host
159
+ moi remote file-download .moi/chart.png ./chart.png # host → local
160
+ ```
161
+
162
+ These regular commands work and get forwared to remote: `check`, `bundle`, `call-server-fn`, `debug`,
163
+ `theme`, `ui-components`, `config`, `tabs`, `scratch`. Scratchpad reads and writes on owner's behalf,
164
+ except for `moi scratch view`.
165
+
166
+ These commands run on **your local Moi**: `refresh`, `navigate`, `views create`, `views set`, `env`.
167
+ `moi tabs` lists the remote workspace’s tabs and views. E.g. `navigate` switches the tab ONLY for current user.
168
+
169
+ Managing env vars on the remote machine is not yet supported. Tell the user to ask the workspace owner.
170
+
138
171
  ### Workspace navigation
139
172
 
140
173
  Use `moi:/` addresses in chat, CLI commands, and applets. They refer to the current workspace,
@@ -192,7 +225,11 @@ use `moi theme --help` if its options change.
192
225
 
193
226
  ### Environment and secrets
194
227
 
195
- Each workspace has an effective env: keys from the project's `.env` / `.env.local` (when
228
+ In remote workspaces, `moi env` commands manage your local environment, and `moi env exec`
229
+ runs locally. Applet server functions use the owner's environment; setting a key locally does
230
+ not make it available to the owner's applets.
231
+
232
+ Each workspace has an effective env: keys from `.env` / `.env.local` in the workspace dir (when
196
233
  inheritance is enabled in settings) plus **custom secrets** the user manages in the workspace env
197
234
  settings. Moi injects this env into:
198
235
 
@@ -371,8 +408,8 @@ replaces the pending screen in the same tab.
371
408
  - Use `style={{}}` only for computed data such as chart geometry, progress, per-item delays, or
372
409
  per-frame transforms.
373
410
  - Use icons from `@tabler/icons-react`. Do not add raw SVG icons or another icon pack. When the
374
- project provides `.agents/rules/icons.md`, follow its size and stroke policy.
375
- - Applets cannot import the host project's `cn`. If `.moi/ui/utils.ts` exists, import `cn` from
411
+ workspace dir contains `.agents/rules/icons.md`, follow its size and stroke policy.
412
+ - Applets cannot import the Moi host application's `cn`. If `.moi/ui/utils.ts` exists, import `cn` from
376
413
  `../ui/utils`; otherwise use a local `cx()` when classes are conditional. Never build class
377
414
  names with template-literal ternaries.
378
415
 
@@ -507,11 +544,15 @@ surfaces on its own.
507
544
  ## Chats and messages
508
545
 
509
546
  A workspace is driven through agent conversations (this chat is one). Depending on your
510
- harness (Claude Code, openclaw, others differ in the details) there can be **multiple chats**, but
511
- they all share **one** workspace **and one Project folder** — the same filesystem, the same `.moi`
512
- folder, applets, config, and theme. Anything you build is visible to every chat, and another chat
513
- may have changed the workspace or the Project files since you last looked. Treat `.moi` and the
514
- Project folder as shared state, not yours alone. Internally, "chats" are sometimes aliased as
547
+ harness (Claude Code, openclaw, others differ in the details) there can be **multiple chats**,
548
+ all working with the same shared applets, config, and theme.
549
+
550
+ You always run on your local machine, not on the remote owner's machine; other visitors have
551
+ their own agents running in their own linked dirs, while the owner's agents run in the owner dir.
552
+
553
+ Anything you build in the shared workspace is visible to other members, and another agent may
554
+ have changed its files since you last looked. Treat shared workspace files as shared state,
555
+ not yours alone. Internally, "chats" are sometimes aliased as
515
556
  "threads" — "chat" is product language, while "thread" is reserved for internal SDK, session, and
516
557
  persistence concepts.
517
558
 
@@ -4,6 +4,10 @@ The Scratchpad is the workspace's **shared whiteboard** — one freeform tldraw
4
4
  draws on by hand and you drive through `moi scratch`. Same canvas, two authors; disk is the
5
5
  source of truth. Use it to sketch, diagram, annotate the user's drawing, or lay out boxes.
6
6
 
7
+ In a remote workspace, run commands from the linked dir: reads and edits use the owner's canvas,
8
+ while `moi scratch view` uses your local Moi and browser. Image input and output paths stay local:
9
+ `add image` uploads to the owner; `read-image` and `view --out` save locally.
10
+
7
11
  ## Seeing
8
12
 
9
13
  **Always inspect the canvas through the commands below — never open, `cat`, `read`, or parse the
@@ -5,7 +5,7 @@ theme tokens. Follow [DESIGN.md](DESIGN.md) for visual decisions.
5
5
 
6
6
  ## Workflow
7
7
 
8
- Run commands from the project root. Check what's available and installed, read the docs
8
+ Run commands from the workspace dir. Check what's available and installed, read the docs
9
9
  before using or changing a component, then add all missing components in one call.
10
10
 
11
11
  ```sh
@@ -1,20 +0,0 @@
1
- import type { ScratchOp, ScratchOpResult } from '@/lib/types'
2
-
3
- // A live Scratchpad editor registers an executor here while it's mounted, keyed
4
- // by workspace id. The chat-socket frame handler (connection.ts) looks one up
5
- // when a `scratchpad:op` arrives and runs it against the tab's tldraw editor.
6
- // Only the tab actually showing a workspace's canvas has an entry, so ops from
7
- // `moi scratch` reach the right editor (and no-op everywhere else).
8
-
9
- type ScratchExecutor = (op: ScratchOp) => Promise<ScratchOpResult>
10
-
11
- const executors = new Map<string, ScratchExecutor>()
12
-
13
- export function setScratchExecutor(workspaceId: string, fn: ScratchExecutor | null) {
14
- if (fn) executors.set(workspaceId, fn)
15
- else executors.delete(workspaceId)
16
- }
17
-
18
- export function getScratchExecutor(workspaceId: string): ScratchExecutor | undefined {
19
- return executors.get(workspaceId)
20
- }
@@ -1,168 +0,0 @@
1
- import type { NavigationRequest } from '@/lib/navigation'
2
- import type {
3
- AppSettings,
4
- CompiledView,
5
- HarnessAvailability,
6
- HarnessStatus,
7
- WidgetInfo,
8
- HarnessType,
9
- WorkspaceState
10
- } from '@/lib/types'
11
-
12
- export type WorkspaceEvent =
13
- | { type: 'connection:opened' }
14
- | {
15
- type: 'harness-status:changed'
16
- harness: HarnessType
17
- status: HarnessStatus
18
- }
19
- | { type: 'workspace-harness:switched'; workspaceId: string; harness: HarnessType }
20
- | { type: 'widget:updated'; workspaceId?: string; name: string }
21
- | { type: 'widget-layout:updated'; workspaceId: string; widgets: WidgetInfo[] }
22
- // `moi refresh` — cache-bust and re-fetch applets without a rebuild. `only`
23
- // narrows to one kind; absent means both widgets and views.
24
- | { type: 'applets:refresh'; workspaceId?: string; only?: 'widgets' | 'views' }
25
- | { type: 'view:updated'; workspaceId?: string; name: string }
26
- | { type: 'view-layout:updated'; workspaceId: string; views: CompiledView[] }
27
- | { type: 'view:deleted'; workspaceId: string; name: string }
28
- // A workspace's chat state changed (pin, selection, chat settings, views
29
- // being built). Carries the whole state, so caches update without a refetch.
30
- | { type: 'state:changed'; workspaceId: string; state: WorkspaceState }
31
- // `origin` on an event is the browser tab whose write caused it (absent for
32
- // CLI and agent changes), so that tab can skip its own echo. See
33
- // client/lib/browser-tab-id.ts.
34
- | { type: 'theme:updated'; workspaceId: string; origin?: string }
35
- | { type: 'workspace:updated'; workspaceId: string; origin?: string }
36
- // The registry list changed (reorder, create) without touching any open
37
- // workspace's layout — clients refetch just the sidebar list.
38
- | { type: 'workspaces-list:updated'; origin?: string }
39
- // A workspace's env changed outside the UI — refetch the env view.
40
- | { type: 'env:updated'; workspaceId: string }
41
- // Workspace readiness changed. Patch its cache without a refetch.
42
- | {
43
- type: 'harness:updated'
44
- workspaceId: string
45
- availability: HarnessAvailability
46
- }
47
- // The Scratchpad canvas for `workspaceId` was saved — open tabs reload from
48
- // disk. `origin` is the tab that wrote it, so that tab can skip its own echo.
49
- | { type: 'scratchpad:updated'; workspaceId: string; origin?: string }
50
- // App settings changed (PATCH /api/settings from any client) — carries the
51
- // new value so caches update without a refetch.
52
- | { type: 'settings:updated'; settings: AppSettings }
53
- | NavigationRequest
54
-
55
- export type WorkspaceEventHandler = (event: WorkspaceEvent) => void
56
-
57
- export type WorkspaceEventsClientOptions = {
58
- // Delay before reopening after a drop. It doubles on repeated drops, up to
59
- // the max, so a downed server isn't hammered; it resets once a socket opens.
60
- reconnectBaseDelayMs?: number
61
- reconnectMaxDelayMs?: number
62
- }
63
-
64
- // The page's workspace events socket. `AppProvider` opens it when the app
65
- // mounts and closes it when the app unmounts; subscribers come and go freely
66
- // in between without touching the connection. A dropped socket reopens on its
67
- // own. Framework-free, so the connection logic is testable without React.
68
- export class WorkspaceEventsClient {
69
- private readonly listeners = new Set<WorkspaceEventHandler>()
70
- private readonly baseDelayMs: number
71
- private readonly maxDelayMs: number
72
- // The socket being opened or open; undefined while disconnected.
73
- private socket: WebSocket | undefined
74
- private closed = true
75
- private reconnectAttempt = 0
76
- private reconnectTimer: ReturnType<typeof setTimeout> | undefined
77
- private shownWorkspace: string | undefined
78
-
79
- constructor(
80
- private readonly url: string,
81
- options: WorkspaceEventsClientOptions = {}
82
- ) {
83
- this.baseDelayMs = options.reconnectBaseDelayMs ?? 1000
84
- this.maxDelayMs = options.reconnectMaxDelayMs ?? 30_000
85
- }
86
-
87
- connect() {
88
- this.closed = false
89
- this.open()
90
- }
91
-
92
- // Shut the connection down for good; no reconnect follows.
93
- close() {
94
- this.closed = true
95
- clearTimeout(this.reconnectTimer)
96
- const socket = this.socket
97
- this.socket = undefined
98
- socket?.close()
99
- }
100
-
101
- subscribe(handler: WorkspaceEventHandler): () => void {
102
- this.listeners.add(handler)
103
- return () => {
104
- this.listeners.delete(handler)
105
- }
106
- }
107
-
108
- send(message: object) {
109
- if (this.socket?.readyState !== WebSocket.OPEN) return
110
- this.socket.send(JSON.stringify(message))
111
- }
112
-
113
- // The workspace this tab shows, for the server's navigation relay. Sent now
114
- // and again on every reconnect.
115
- get navigationWorkspace(): string | undefined {
116
- return this.shownWorkspace
117
- }
118
-
119
- setNavigationWorkspace(workspaceId: string | undefined) {
120
- this.shownWorkspace = workspaceId
121
- this.sendNavigationPresence()
122
- }
123
-
124
- sendNavigationPresence() {
125
- this.send({
126
- type: 'navigation:presence',
127
- // The wire format uses `null` for "no workspace".
128
- workspaceId: this.shownWorkspace ?? null,
129
- focused: document.visibilityState === 'visible' && document.hasFocus()
130
- })
131
- }
132
-
133
- private open() {
134
- if (this.closed || this.socket) return
135
- const socket = new WebSocket(this.url)
136
- this.socket = socket
137
-
138
- socket.onopen = () => {
139
- this.reconnectAttempt = 0
140
- this.sendNavigationPresence()
141
- for (const handler of this.listeners) handler({ type: 'connection:opened' })
142
- }
143
-
144
- socket.onmessage = event => {
145
- try {
146
- const data = JSON.parse(event.data) as WorkspaceEvent
147
- for (const handler of this.listeners) handler(data)
148
- } catch {}
149
- }
150
-
151
- socket.onclose = () => {
152
- // A socket this client already let go of (closed or replaced).
153
- if (this.socket !== socket) return
154
- this.socket = undefined
155
- if (!this.closed) this.scheduleReconnect()
156
- }
157
-
158
- socket.onerror = () => {
159
- socket.close()
160
- }
161
- }
162
-
163
- private scheduleReconnect() {
164
- const delay = Math.min(this.baseDelayMs * 2 ** this.reconnectAttempt, this.maxDelayMs)
165
- this.reconnectAttempt++
166
- this.reconnectTimer = setTimeout(() => this.open(), delay)
167
- }
168
- }
@@ -1,2 +0,0 @@
1
- var lt=Object.create;var{getPrototypeOf:dt,defineProperty:rr,getOwnPropertyNames:pt}=Object;var fr=Object.prototype.hasOwnProperty;function ht(r){return this[r]}var gt,ut,e=(r,t,a)=>{var o=r!=null&&typeof r==="object";if(o){var i=t?gt??=new WeakMap:ut??=new WeakMap,c=i.get(r);if(c)return c}a=r!=null?lt(dt(r)):{};let d=t||!r||!r.__esModule||!fr.call(r,"default")?rr(a,"default",{value:r,enumerable:!0}):a;if(r&&typeof r==="object"||typeof r==="function"){for(let n of pt(r))if(!fr.call(d,n))rr(d,n,{get:ht.bind(r,n),enumerable:!0})}if(o)i.set(r,d);return d};var I=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports);var mt=(r)=>r;function ft(r,t){this[r]=mt.bind(null,t)}var Ft=(r,t)=>{for(var a in t)rr(r,a,{get:t[a],enumerable:!0,configurable:!0,set:ft.bind(t,a)})};var tn=((r)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(t,a)=>(typeof require<"u"?require:t)[a]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var xr,tr,F,Fe=(r,t)=>{for(var[a,o,i]of xr||[])for(var c=[r],d=globalThis,n=d.document,s,p,g,h,u;p=c.pop();)if(!tr[p]&&(g=o[p])){tr[p]=1;for(h=1;h<g.length;h++)c.push(i[g[h]]);if(!t&&p!==r&&(s=n&&n.head)){if(F===void 0)F=(h=n.querySelector("meta[property=csp-nonce]"))&&(h.nonce||h.getAttribute("nonce"))||"";if(u=n.createElement("link"),u.rel="modulepreload",u.crossOrigin="",F)u.nonce=F;u.href=new d.URL(g[0],a),s.appendChild(u)}}},xt=(r,t,a,o)=>{for(var i={},c=0;c<t.length;c++)i[t[c]]=a[c];(xr||=[]).push([r,i,t]),tr||={},Fe(t[o],1)};xt(import.meta.url,["44khk4sp","ba6mz56s","en7w5ypg","ec5ennpv","nf2wkvf9","rmd0ctfx","f695wcx5","ectsnw81","pdt9hxfw","zv22wv0g","n0fawy9x"],[["/chunk-44khk4sp.js"],["/chunk-ba6mz56s.js",6,0,7,8],["/chunk-en7w5ypg.js",7],["/chunk-ec5ennpv.js",0,8],["/chunk-nf2wkvf9.js"],["/chunk-rmd0ctfx.js",6,7,0,10,8],["/chunk-f695wcx5.js",0,7,8],["/chunk-ectsnw81.js",0,8],["/chunk-pdt9hxfw.js"],["/chunk-zv22wv0g.js",10],["/chunk-n0fawy9x.js"]],0);
2
- if(typeof globalThis.structuredClone==="function")globalThis.structuredClone=globalThis.structuredClone.bind(globalThis);var A=["pink","orange","amber","lime","emerald","cyan","blue","violet"];function Q(r){return typeof r==="string"&&A.includes(r)}function Jr(r){let t=2166136261;for(let a=0;a<r.length;a++)t^=r.charCodeAt(a),t=Math.imul(t,16777619);return A[(t>>>0)%A.length]??A[0]}var rn=1;var yt=8192,kt=320;function Be(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)}function L(r,t=256){return typeof r==="string"&&r.length>0&&!r.includes("\x00")&&new TextEncoder().encode(r).length<=t}function yr(r){return Be(r)&&L(r.id,240)&&r.id.trim().length>0&&(r.name===void 0||L(r.name)&&r.name.trim().length>0)&&Q(r.color)&&(r.avatar===void 0||L(r.avatar,yt))&&(r.email===void 0||L(r.email,kt))}function N(r,t){return typeof r==="string"&&r.length<=t&&!r.includes("\x00")}function zt(r){if(!N(r,2048))return!1;try{return["http:","https:"].includes(new URL(r).protocol)}catch{return!1}}function nt(r){if(!Be(r)||!N(r.id,240)||!r.id.trim()||r.id!==r.id.trim()||!N(r.name,256)||r.avatar!==void 0&&!zt(r.avatar))throw Error("Invalid identity");let t={id:r.id,name:r.name,...r.avatar!==void 0?{avatar:r.avatar}:{}};if(r.type==="agent")return{...t,type:"agent"};if(r.type==="user"&&N(r.email,320)&&typeof r.isAnonymous==="boolean")return{...t,type:"user",email:r.email,isAnonymous:r.isAnonymous};throw Error("Invalid identity")}var ze=(r)=>`${r.type}:${r.id}`,bt=(r)=>r.type==="agent"?`agent:${r.id}`:r.id;var W,kr=0,zr=0,ar=new Set,Te=()=>W,br=()=>zr,ce=()=>kr;function Qr(r){return ar.add(r),()=>{ar.delete(r)}}function vt(r){let t=r===null?null:nt(r);if((W&&ze(W))!==(t&&ze(t)))kr++;zr++,W=t,ar.forEach((o)=>o())}var _t=["Curious Kiwi","Cheerful Cherry","Sleepy Peach","Excited Banana","Cosmic Mango","Velvet Lemon","Electric Plum","Wandering Pear","Dramatic Papaya","Suspicious Pineapple","Confused Coconut","Sneaky Tangerine","Gentle Fig","Quiet Apricot","Mellow Melon","Dreamy Guava"];function _r(r,t){let a=r.filter((o)=>o!==t);return a[Math.floor(Math.random()*a.length)]??r[0]}function Ct(r){return{name:_r(_t,r?.name),color:_r(A,r?.color)}}function Et(r,t){let a=t.name.trim();return{id:r,...a?{name:a}:{},color:t.color}}function Cr(){return Et(`local-${crypto.randomUUID().slice(0,8)}`,Ct())}var ir="moi:local-profile",_,E,D=new Set;function nr(r,t){return JSON.stringify(r)===JSON.stringify(t)}function P(r){if(!r||typeof r.id!=="string"||!r.id.trim())throw Error("A user profile needs an id.");if(r.name!==void 0&&typeof r.name!=="string")throw Error("A user profile name must be a string when provided.");if(r.color!==void 0&&!Q(r.color))throw Error("A user profile color must be one of the user palette names.");let t=r.id.trim(),a=r.name?.trim(),o={id:t,...a?{name:a}:{},color:r.color??Jr(t),...r.avatar!==void 0?{avatar:r.avatar}:{},...r.email!==void 0?{email:r.email}:{}};if(!yr(o))throw Error("Invalid user profile.");return Object.freeze(o)}var or,Er;function pe(){let r=Te();if(r===void 0)return _;if(r!==Er){Er=r;let t=!r||r.type==="user"&&r.isAnonymous?void 0:P({id:bt(r),name:r.name||void 0,avatar:r.avatar,email:r.type==="user"?r.email||void 0:void 0});if(!nr(or,t))or=t}return or}function wt(r){let t=pe(),a=ve(),o=()=>{let c=pe(),d=ve();if(t===c&&a===d)return;t=c,a=d,r()};D.add(o);let i=Qr(o);return()=>{D.delete(o),i()}}function ve(){return Te()!==void 0?"external":E}function on({provider:r,profile:t}){if(ve()==="external")return;if(r===void 0){if(E===void 0||E==="local")return;E=void 0,_=void 0}else{let a=t===void 0?void 0:P(t);if(E===r&&nr(_,a))return;E=r,_=a}D.forEach((a)=>a())}function At(){try{localStorage.setItem(ir,JSON.stringify(_))}catch{}}function eo(r){if(ve()!==void 0&&ve()!=="local")return;let t=P(r);E="local",_=t,At(),D.forEach((a)=>a())}function Ar(r,t){if(!r||!t||t.provider!==void 0||ve()!==void 0)return;try{let a=localStorage.getItem(ir);if(a){eo(JSON.parse(a));return}}catch{}eo(Cr())}function Sr(r){if(r.key!==ir||!r.newValue||ve()!=="local")return;try{let t=P(JSON.parse(r.newValue));if(nr(t,_))return;_=t,D.forEach((a)=>a())}catch{}}function Pr(){return window.addEventListener("storage",Sr),()=>window.removeEventListener("storage",Sr)}var Pt={setTimeout:(r,t)=>setTimeout(r,t),clearTimeout:(r)=>clearTimeout(r),setInterval:(r,t)=>setInterval(r,t),clearInterval:(r)=>clearInterval(r)},jt=class{#r=Pt;#t=!1;setTimeoutProvider(r){this.#r=r}setTimeout(r,t){return this.#r.setTimeout(r,t)}clearTimeout(r){this.#r.clearTimeout(r)}setInterval(r,t){return this.#r.setInterval(r,t)}clearInterval(r){this.#r.clearInterval(r)}},He=new jt;function jr(r){setTimeout(r,0)}var cr=typeof window>"u"||"Deno"in globalThis;function H(){}function Ir(r,t){return typeof r==="function"?r(t):r}function to(r){return typeof r==="number"&&r>=0&&r!==1/0}function ro(r,t){return Math.max(r+(t||0)-Date.now(),0)}function U(r,t){return typeof r==="function"?r(t):r}function Zt(r,t){let{type:a="all",exact:o,fetchStatus:i,predicate:c,queryKey:d,stale:n}=r;if(d){if(o){if(t.queryHash!==R(d,t.options))return!1}else if(!C(t.queryKey,d))return!1}if(a!=="all"){let s=t.isActive();if(a==="active"&&!s)return!1;if(a==="inactive"&&s)return!1}if(typeof n==="boolean"&&t.isStale()!==n)return!1;if(i&&i!==t.state.fetchStatus)return!1;if(c&&!c(t))return!1;return!0}function B(r,t){let{exact:a,status:o,predicate:i,mutationKey:c}=r;if(c){if(!t.options.mutationKey)return!1;if(a){if(Ue(t.options.mutationKey)!==Ue(c))return!1}else if(!C(t.options.mutationKey,c))return!1}if(o&&t.state.status!==o)return!1;if(i&&!i(t))return!1;return!0}function R(r,t){return(t?.queryKeyHashFn||Ue)(r)}function Ue(r){return JSON.stringify(r,(t,a)=>sr(a)?Object.keys(a).sort().reduce((o,i)=>(o[i]=a[i],o),{}):a)}function C(r,t){if(r===t)return!0;if(typeof r!==typeof t)return!1;if(r&&t&&typeof r==="object"&&typeof t==="object"){if(Array.isArray(r)&&Array.isArray(t)){for(let o=0;o<t.length;o++)if(!C(r[o],t[o]))return!1;return!0}let a=Object.keys(t);for(let o of a)if(!C(r[o],t[o]))return!1;return!0}return!1}var Mt=Object.prototype.hasOwnProperty;function We(r,t,a=0){if(r===t)return r;if(a>500)return t;let o=Mr(r)&&Mr(t);if(!o&&!(sr(r)&&sr(t)))return t;let i=(o?r:Object.keys(r)).length,c=o?t:Object.keys(t),d=c.length,n=o?Array(d):{},s=0;for(let p=0;p<d;p++){let g=o?p:c[p],h=r[g],u=t[g];if(h===u){if(n[g]=h,o?p<i:Mt.call(r,g))s++;continue}if(h===null||u===null||typeof h!=="object"||typeof u!=="object"){n[g]=u;continue}let y=We(h,u,a+1);if(n[g]=y,y===h)s++}return i===d&&s===i?r:n}function St(r,t){if(!t||Object.keys(r).length!==Object.keys(t).length)return!1;for(let a in r)if(r[a]!==t[a])return!1;return!0}function Mr(r){return Array.isArray(r)&&r.length===Object.keys(r).length}function sr(r){if(!Or(r))return!1;let t=r.constructor;if(t===void 0)return!0;let a=t.prototype;if(!Or(a))return!1;if(!a.hasOwnProperty("isPrototypeOf"))return!1;if(Object.getPrototypeOf(r)!==Object.prototype)return!1;return!0}function Or(r){return Object.prototype.toString.call(r)==="[object Object]"}function qr(r){return new Promise((t)=>{He.setTimeout(t,r)})}function vr(r,t,a){if(typeof a.structuralSharing==="function")return a.structuralSharing(r,t);else if(a.structuralSharing!==!1)return We(r,t);return t}function Dr(r,t,a=0){let o=[...r,t];return a&&o.length>a?o.slice(1):o}function Ur(r,t,a=0){let o=[t,...r];return a&&o.length>a?o.slice(0,-1):o}var j=Symbol();function K(r,t){if(!r.queryFn&&t?.initialPromise)return()=>t.initialPromise;if(!r.queryFn||r.queryFn===j)return()=>Promise.reject(Error(`Missing queryFn: '${r.queryHash}'`));return r.queryFn}function Jt(r,t){if(typeof r==="function")return r(...t);return!!r}function Rr(r,t,a){let o=!1,i;return Object.defineProperty(r,"signal",{enumerable:!0,get:()=>{if(i??=t(),o)return i;if(o=!0,i.aborted)a();else i.addEventListener("abort",a,{once:!0});return i}}),r}var Ot=()=>cr,Qt=()=>Ot();var ge=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(r){return this.listeners.add(r),this.onSubscribe(),()=>{this.listeners.delete(r),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var It=class extends ge{#r;#t;#a;constructor(){super();this.#a=(r)=>{if(typeof window<"u"&&window.addEventListener){let t=()=>r();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){if(!this.#t)this.setEventListener(this.#a)}onUnsubscribe(){if(!this.hasListeners())this.#t?.(),this.#t=void 0}setEventListener(r){this.#a=r,this.#t?.(),this.#t=r((t)=>{if(typeof t==="boolean")this.setFocused(t);else this.onFocus()})}setFocused(r){if(this.#r!==r)this.#r=r,this.onFocus()}onFocus(){let r=this.isFocused();this.listeners.forEach((t)=>{t(r)})}isFocused(){if(typeof this.#r==="boolean")return this.#r;return globalThis.document?.visibilityState!=="hidden"}},er=new It;var Tr=jr;function qt(){let r=[],t=0,a=(n)=>{n()},o=(n)=>{n()},i=Tr,c=(n)=>{if(t)r.push(n);else i(()=>{a(n)})},d=()=>{let n=r;if(r=[],n.length)i(()=>{o(()=>{n.forEach((s)=>{a(s)})})})};return{batch:(n)=>{let s;t++;try{s=n()}finally{if(t--,!t)d()}return s},batchCalls:(n)=>(...s)=>{c(()=>{n(...s)})},schedule:c,setNotifyFunction:(n)=>{a=n},setBatchNotifyFunction:(n)=>{o=n},setScheduler:(n)=>{i=n}}}var M=qt();var Dt=class extends ge{#r=!0;#t;#a;constructor(){super();this.#a=(r)=>{if(typeof window<"u"&&window.addEventListener){let t=()=>r(!0),a=()=>r(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",a,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",a)}}}}onSubscribe(){if(!this.#t)this.setEventListener(this.#a)}onUnsubscribe(){if(!this.hasListeners())this.#t?.(),this.#t=void 0}setEventListener(r){this.#a=r,this.#t?.(),this.#t=r(this.setOnline.bind(this))}setOnline(r){if(this.#r!==r)this.#r=r,this.listeners.forEach((t)=>{t(r)})}isOnline(){return this.#r}},O=new Dt;function Ut(r){return Math.min(1000*2**r,30000)}function lr(r){return(r??"online")==="online"?O.isOnline():!0}var V=class extends Error{constructor(r){super("CancelledError");this.revert=r?.revert,this.silent=r?.silent}};function Y(r){let t=!1,a=0,o,i="pending",c,d,n=new Promise((v,f)=>{c=v,d=f});n.catch(H);let s=()=>i!=="pending",p=(v)=>{if(!s()){let f=new V(v);m(f),r.onCancel?.(f)}},g=()=>{t=!0},h=()=>{t=!1},u=()=>er.isFocused()&&(r.networkMode==="always"||O.isOnline())&&r.canRun(),y=()=>lr(r.networkMode)&&r.canRun(),w=(v)=>{if(!s())o?.(),i="resolved",c(v)},m=(v)=>{if(!s())o?.(),i="rejected",d(v)},k=()=>new Promise((v)=>{o=(f)=>{if(s()||u())v(f)},r.onPause?.()}).then(()=>{if(o=void 0,!s())r.onContinue?.()}),T=()=>{if(s())return;let v,f=a===0?r.initialPromise:void 0;try{v=f??r.fn()}catch(b){v=Promise.reject(b)}Promise.resolve(v).then(w).catch((b)=>{if(s())return;let z=r.retry??(Qt()?0:3),S=r.retryDelay??Ut,st=typeof S==="function"?S(a,b):S,ct=z===!0||typeof z==="number"&&a<z||typeof z==="function"&&z(a,b);if(t||!ct){m(b);return}a++,r.onFail?.(a,b),qr(st).then(()=>u()?void 0:k()).then(()=>{if(t)m(b);else T()})})};return{promise:n,status:()=>i,cancel:p,continue:()=>(o?.(),n),cancelRetry:g,continueRetry:h,canStart:y,start:()=>{if(y())T();else k().then(T);return n}}}var X=class{#r;destroy(){this.clearGcTimeout()}scheduleGc(){if(this.clearGcTimeout(),to(this.gcTime))this.#r=He.setTimeout(()=>{this.optionalRemove()},this.gcTime)}updateGcTime(r){this.gcTime=Math.max(this.gcTime||0,r??(Qt()?1/0:300000))}clearGcTimeout(){if(this.#r!==void 0)He.clearTimeout(this.#r),this.#r=void 0}};function Lr(r){return{onFetch:(t,a)=>{let o=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,c=t.state.data?.pages||[],d=t.state.data?.pageParams||[],n={pages:[],pageParams:[]},s=0,p=async()=>{let g=!1,h=(w)=>{Rr(w,()=>t.signal,()=>g=!0)},u=K(t.options,t.fetchOptions),y=async(w,m,k)=>{if(g)return Promise.reject(t.signal.reason);if(m==null&&w.pages.length)return Promise.resolve(w);let v=(()=>{let S={client:t.client,queryKey:t.queryKey,pageParam:m,direction:k?"backward":"forward",meta:t.options.meta};return h(S),S})(),f=await u(v),{maxPages:b}=t.options,z=k?Ur:Dr;return{pages:z(w.pages,f,b),pageParams:z(w.pageParams,m,b)}};if(i&&c.length){let w=i==="backward",m=w?Rt:Fr,k={pages:c,pageParams:d};n=await y(k,m(o,k),w)}else{let w=r??c.length;do{let m=s===0?d[0]??o.initialPageParam:Fr(o,n);if(s>0&&m==null)break;n=await y(n,m),s++}while(s<w)}return n};if(t.options.persister)t.fetchFn=()=>t.options.persister?.(p,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},a);else t.fetchFn=p}}}function Fr(r,{pages:t,pageParams:a}){let o=t.length-1;return t.length>0?r.getNextPageParam(t[o],t,a[o],a):void 0}function Rt(r,{pages:t,pageParams:a}){return t.length>0?r.getPreviousPageParam?.(t[0],t,a[0],a):void 0}var Br=class extends X{#r;#t;#a;#o;#i;#e;#c;#n;constructor(r){super();this.#n=!1,this.#c=r.defaultOptions,this.setOptions(r.options),this.observers=[],this.#i=r.client,this.#o=this.#i.getQueryCache(),this.queryKey=r.queryKey,this.queryHash=r.queryHash,this.#t=Wr(this.options),this.state=r.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#r}get promise(){return this.#e?.promise}setOptions(r){if(this.options={...this.#c,...r},r?._type)this.#r=r._type;if(this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let t=Wr(this.options);if(t.data!==void 0)this.setState(Nr(t.data,t.dataUpdatedAt)),this.#t=t}}optionalRemove(){if(!this.observers.length&&this.state.fetchStatus==="idle")this.#o.remove(this)}setData(r,t){let a=vr(this.state.data,r,this.options);return this.#s({data:a,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),a}setState(r){this.#s({type:"setState",state:r})}cancel(r){let t=this.#e?.promise;return this.#e?.cancel(r),t?t.then(H).catch(H):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some((r)=>U(r.options.enabled,this)!==!1)}isDisabled(){if(this.getObserversCount()>0)return!this.isActive();return this.options.queryFn===j||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){if(this.getObserversCount()>0)return this.observers.some((r)=>U(r.options.staleTime,this)==="static");return!1}isStale(){if(this.getObserversCount()>0)return this.observers.some((r)=>r.getCurrentResult().isStale);return this.state.data===void 0||this.state.isInvalidated}isStaleByTime(r=0){if(this.state.data===void 0)return!0;if(r==="static")return!1;if(this.state.isInvalidated)return!0;return!ro(this.state.dataUpdatedAt,r)}onFocus(){this.observers.find((r)=>r.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#e?.continue()}onOnline(){this.observers.find((r)=>r.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#e?.continue()}addObserver(r){if(!this.observers.includes(r))this.observers.push(r),this.clearGcTimeout(),this.#o.notify({type:"observerAdded",query:this,observer:r})}removeObserver(r){let t=this.observers.indexOf(r);if(t!==-1){if(this.observers.splice(t,1),!this.observers.length){if(this.#e)if(this.#n||this.state.fetchStatus==="paused"&&this.state.status==="pending")this.#e.cancel({revert:!0});else this.#e.cancelRetry();this.scheduleGc()}this.#o.notify({type:"observerRemoved",query:this,observer:r})}}getObserversCount(){return this.observers.length}invalidate(){if(!this.state.isInvalidated)this.#s({type:"invalidate"})}async fetch(r,t){if(this.state.fetchStatus!=="idle"&&this.#e?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#e)return this.#e.continueRetry(),this.#e.promise}if(r)this.setOptions(r);if(!this.options.queryFn){let s=this.observers.find((p)=>p.options.queryFn);if(s)this.setOptions(s.options)}let a=new AbortController,o=(s)=>{Object.defineProperty(s,"signal",{enumerable:!0,get:()=>(this.#n=!0,a.signal)})},i=()=>{let s=K(this.options,t),g=(()=>{let h={client:this.#i,queryKey:this.queryKey,meta:this.meta};return o(h),h})();if(this.#n=!1,this.options.persister)return this.options.persister(s,g,this);return s(g)},d=(()=>{let s={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return o(s),s})();if((this.#r==="infinite"?Lr(this.options.pages):this.options.behavior)?.onFetch(d,this),this.#a=this.state,this.state.fetchStatus==="idle"||this.state.fetchMeta!==d.fetchOptions?.meta)this.#s({type:"fetch",meta:d.fetchOptions?.meta});let n=this.#e=Y({initialPromise:t?.initialPromise,fn:d.fetchFn,onCancel:(s)=>{if(s instanceof V&&s.revert)this.setState({...this.#a,fetchStatus:"idle"});a.abort()},onFail:(s,p)=>{this.#s({type:"failed",failureCount:s,error:p})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:d.options.retry,retryDelay:d.options.retryDelay,networkMode:d.options.networkMode,canRun:()=>!0});try{let s=await n.start();if(s===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(s),this.#o.config.onSuccess?.(s,this),this.#o.config.onSettled?.(s,this.state.error,this),s}catch(s){if(s instanceof V){if(s.silent)return this.#e.promise;else if(s.revert){if(this.state.data===void 0)throw s;return this.state.data}}throw this.#s({type:"error",error:s}),this.#o.config.onError?.(s,this),this.#o.config.onSettled?.(this.state.data,s,this),s}finally{if(this.#e===n)this.#e=void 0;this.scheduleGc()}}#s(r){let t=(a)=>{switch(r.type){case"failed":return{...a,fetchFailureCount:r.failureCount,fetchFailureReason:r.error};case"pause":return{...a,fetchStatus:"paused"};case"continue":return{...a,fetchStatus:"fetching"};case"fetch":return{...a,..._o(a.data,this.options),fetchMeta:r.meta??null};case"success":let o={...a,...Nr(r.data,r.dataUpdatedAt),dataUpdateCount:a.dataUpdateCount+1,...!r.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#a=r.manual?o:void 0,o;case"error":let i=r.error;return{...a,error:i,errorUpdateCount:a.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:a.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...a,isInvalidated:!0};case"setState":return{...a,...r.state}}};this.state=t(this.state),M.batch(()=>{this.observers.slice().forEach((a)=>{a.onQueryUpdate()}),this.#o.notify({query:this,type:"updated",action:r})})}};function _o(r,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:lr(t.networkMode)?"fetching":"paused",...r===void 0&&{error:null,status:"pending"}}}function Nr(r,t){return{data:r,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Wr(r){let t=typeof r.initialData==="function"?r.initialData():r.initialData,a=t!==void 0,o=a?typeof r.initialDataUpdatedAt==="function"?r.initialDataUpdatedAt():r.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:a?o??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:a?"success":"pending",fetchStatus:"idle"}}var Hr=class extends X{#r;#t;#a;#o;constructor(r){super();this.#r=r.client,this.mutationId=r.mutationId,this.#a=r.mutationCache,this.#t=[],this.state=r.state||Mo(),this.setOptions(r.options),this.scheduleGc()}setOptions(r){this.options=r,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(r){if(!this.#t.includes(r))this.#t.push(r),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",mutation:this,observer:r})}removeObserver(r){this.#t=this.#t.filter((t)=>t!==r),this.scheduleGc(),this.#a.notify({type:"observerRemoved",mutation:this,observer:r})}optionalRemove(){if(!this.#t.length)if(this.state.status==="pending")this.scheduleGc();else this.#a.remove(this)}continue(){return this.#o?.continue()??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(r){let t=()=>{this.#i({type:"continue"})},a={client:this.#r,meta:this.options.meta,mutationKey:this.options.mutationKey},o=this.#o=Y({fn:()=>{if(!this.options.mutationFn)return Promise.reject(Error("No mutationFn found"));return this.options.mutationFn(r,a)},onFail:(d,n)=>{this.#i({type:"failed",failureCount:d,error:n})},onPause:()=>{this.#i({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#a.canRun(this)}),i=this.state.status==="pending",c=!o.canStart();try{if(i)t();else{if(this.#i({type:"pending",variables:r,isPaused:c}),this.#a.config.onMutate)await this.#a.config.onMutate(r,this,a);let n=await this.options.onMutate?.(r,a);if(n!==this.state.context)this.#i({type:"pending",context:n,variables:r,isPaused:c})}let d=await o.start();return await this.#a.config.onSuccess?.(d,r,this.state.context,this,a),await this.options.onSuccess?.(d,r,this.state.context,a),await this.#a.config.onSettled?.(d,null,this.state.variables,this.state.context,this,a),await this.options.onSettled?.(d,null,r,this.state.context,a),this.#i({type:"success",data:d}),d}catch(d){try{await this.#a.config.onError?.(d,r,this.state.context,this,a)}catch(n){Promise.reject(n)}try{await this.options.onError?.(d,r,this.state.context,a)}catch(n){Promise.reject(n)}try{await this.#a.config.onSettled?.(void 0,d,this.state.variables,this.state.context,this,a)}catch(n){Promise.reject(n)}try{await this.options.onSettled?.(void 0,d,r,this.state.context,a)}catch(n){Promise.reject(n)}throw this.#i({type:"error",error:d}),d}finally{if(this.#o===o)this.#o=void 0;this.#a.runNext(this)}}#i(r){let t=(a)=>{switch(r.type){case"failed":return{...a,failureCount:r.failureCount,failureReason:r.error};case"pause":return{...a,isPaused:!0};case"continue":return{...a,isPaused:!1};case"pending":return{...a,context:r.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:r.isPaused,status:"pending",variables:r.variables,submittedAt:Date.now()};case"success":return{...a,data:r.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...a,data:void 0,error:r.error,failureCount:a.failureCount+1,failureReason:r.error,isPaused:!1,status:"error"}}};this.state=t(this.state),M.batch(()=>{this.#t.forEach((a)=>{a.onMutationUpdate(r)}),this.#a.notify({mutation:this,type:"updated",action:r})})}};function Mo(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Kr=class extends ge{#r;#t;#a;constructor(r={}){super();this.config=r,this.#r=new Set,this.#t=new Map,this.#a=0}build(r,t,a){let o=new Hr({client:r,mutationCache:this,mutationId:++this.#a,options:r.defaultMutationOptions(t),state:a});return this.add(o),o}add(r){this.#r.add(r);let t=J(r);if(typeof t==="string"){let a=this.#t.get(t);if(a)a.push(r);else this.#t.set(t,[r])}this.notify({type:"added",mutation:r})}remove(r){if(this.#r.delete(r)){let t=J(r);if(typeof t==="string"){let a=this.#t.get(t);if(a){if(a.length>1){let o=a.indexOf(r);if(o!==-1)a.splice(o,1)}else if(a[0]===r)this.#t.delete(t)}}}this.notify({type:"removed",mutation:r})}canRun(r){let t=J(r);if(typeof t==="string"){let a=this.#t.get(t)?.find((o)=>o.state.status==="pending");return!a||a===r}else return!0}runNext(r){let t=J(r);if(typeof t==="string")return this.#t.get(t)?.find((a)=>a!==r&&a.state.isPaused)?.continue()??Promise.resolve();else return Promise.resolve()}clear(){M.batch(()=>{this.#r.forEach((r)=>{this.notify({type:"removed",mutation:r})}),this.#r.clear(),this.#t.clear()})}getAll(){return Array.from(this.#r)}find(r){let t={exact:!0,...r};return this.getAll().find((a)=>B(t,a))}findAll(r={}){return this.getAll().filter((t)=>B(r,t))}notify(r){M.batch(()=>{this.listeners.forEach((t)=>{t(r)})})}resumePausedMutations(){let r=this.getAll().filter((t)=>t.state.isPaused);return M.batch(()=>Promise.all(r.map((t)=>t.continue().catch(H))))}};function J(r){return r.options.scope?.id}var Vr=class extends ge{#r;constructor(r={}){super();this.config=r,this.#r=new Map}build(r,t,a){let o=t.queryKey,i=t.queryHash??R(o,t),c=this.get(i);if(!c)c=new Br({client:r,queryKey:o,queryHash:i,options:r.defaultQueryOptions(t),state:a,defaultOptions:r.getQueryDefaults(o)}),this.add(c);return c}add(r){if(!this.#r.has(r.queryHash))this.#r.set(r.queryHash,r),this.notify({type:"added",query:r})}remove(r){let t=this.#r.get(r.queryHash);if(t){if(r.destroy(),t===r)this.#r.delete(r.queryHash);this.notify({type:"removed",query:r})}}clear(){M.batch(()=>{this.getAll().forEach((r)=>{this.remove(r)})})}get(r){return this.#r.get(r)}getAll(){return[...this.#r.values()]}find(r){let t={exact:!0,...r};return this.getAll().find((a)=>Zt(t,a))}findAll(r={}){let t=this.getAll();return Object.keys(r).length>0?t.filter((a)=>Zt(r,a)):t}notify(r){M.batch(()=>{this.listeners.forEach((t)=>{t(r)})})}onFocus(){M.batch(()=>{this.getAll().forEach((r)=>{r.onFocus()})})}onOnline(){M.batch(()=>{this.getAll().forEach((r)=>{r.onOnline()})})}};var dr=class{#r;#t;#a;#o;#i;#e;#c;#n;constructor(r={}){this.#r=r.queryCache||new Vr,this.#t=r.mutationCache||new Kr,this.#a=r.defaultOptions||{},this.#o=new Map,this.#i=new Map,this.#e=0}mount(){if(this.#e++,this.#e!==1)return;this.#c=er.subscribe(async(r)=>{if(r)await this.resumePausedMutations(),this.#r.onFocus()}),this.#n=O.subscribe(async(r)=>{if(r)await this.resumePausedMutations(),this.#r.onOnline()})}unmount(){if(this.#e--,this.#e!==0)return;this.#c?.(),this.#c=void 0,this.#n?.(),this.#n=void 0}isFetching(r){return this.#r.findAll({...r,fetchStatus:"fetching"}).length}isMutating(r){return this.#t.findAll({...r,status:"pending"}).length}getQueryData(r){let t=this.defaultQueryOptions({queryKey:r});return this.#r.get(t.queryHash)?.state.data}ensureQueryData(r){let t=this.defaultQueryOptions(r),a=this.#r.build(this,t),o=a.state.data;if(o===void 0)return this.fetchQuery(r);if(r.revalidateIfStale&&a.isStaleByTime(U(t.staleTime,a)))this.prefetchQuery(t);return Promise.resolve(o)}getQueriesData(r){return this.#r.findAll(r).map(({queryKey:t,state:a})=>[t,a.data])}setQueryData(r,t,a){let o=this.defaultQueryOptions({queryKey:r}),i=this.#r.get(o.queryHash)?.state.data,c=Ir(t,i);if(c===void 0)return;return this.#r.build(this,o).setData(c,{...a,manual:!0})}setQueriesData(r,t,a){return M.batch(()=>this.#r.findAll(r).map(({queryKey:o})=>[o,this.setQueryData(o,t,a)]))}getQueryState(r){let t=this.defaultQueryOptions({queryKey:r});return this.#r.get(t.queryHash)?.state}removeQueries(r){let t=this.#r;M.batch(()=>{t.findAll(r).forEach((a)=>{t.remove(a)})})}resetQueries(r,t){let a=this.#r;return M.batch(()=>{let o=a.findAll(r),i=new Set(o);return o.forEach((c)=>{c.reset()}),this.refetchQueries({type:"active",predicate:(c)=>i.has(c)},t)})}cancelQueries(r,t={}){let a={revert:!0,...t},o=M.batch(()=>this.#r.findAll(r).map((i)=>i.cancel(a)));return Promise.all(o).then(H).catch(H)}invalidateQueries(r,t={}){return M.batch(()=>{if(this.#r.findAll(r).forEach((a)=>{a.invalidate()}),r?.refetchType==="none")return Promise.resolve();return this.refetchQueries({...r,type:r?.refetchType??r?.type??"active"},t)})}refetchQueries(r,t={}){let a={...t,cancelRefetch:t.cancelRefetch??!0},o=M.batch(()=>this.#r.findAll(r).filter((i)=>!i.isDisabled()&&!i.isStatic()).map((i)=>{let c=i.fetch(void 0,a);if(!a.throwOnError)c=c.catch(H);return i.state.fetchStatus==="paused"?Promise.resolve():c}));return Promise.all(o).then(H)}async query(r){let t=this.defaultQueryOptions(r);if(t.retry===void 0)t.retry=!1;let a=this.#r.build(this,t),o=a.isStaleByTime(U(t.staleTime,a))?await a.fetch(t):a.state.data,i=t.select;if(i)return i(o);return o}fetchQuery(r){let t=this.defaultQueryOptions(r);if(t.retry===void 0)t.retry=!1;let a=this.#r.build(this,t);return a.isStaleByTime(U(t.staleTime,a))?a.fetch(t):Promise.resolve(a.state.data)}prefetchQuery(r){return this.fetchQuery(r).then(H).catch(H)}infiniteQuery(r){return r._type="infinite",this.query(r)}fetchInfiniteQuery(r){return r._type="infinite",this.fetchQuery(r)}prefetchInfiniteQuery(r){return this.fetchInfiniteQuery(r).then(H).catch(H)}ensureInfiniteQueryData(r){return r._type="infinite",this.ensureQueryData(r)}resumePausedMutations(){if(O.isOnline())return this.#t.resumePausedMutations();return Promise.resolve()}getQueryCache(){return this.#r}getMutationCache(){return this.#t}getDefaultOptions(){return this.#a}setDefaultOptions(r){this.#a=r}setQueryDefaults(r,t){this.#o.set(Ue(r),{queryKey:r,defaultOptions:t})}getQueryDefaults(r){let t=[...this.#o.values()],a={};return t.forEach((o)=>{if(C(r,o.queryKey))Object.assign(a,o.defaultOptions)}),a}setMutationDefaults(r,t){this.#i.set(Ue(r),{mutationKey:r,defaultOptions:t})}getMutationDefaults(r){let t=[...this.#i.values()],a={};return t.forEach((o)=>{if(C(r,o.mutationKey))Object.assign(a,o.defaultOptions)}),a}defaultQueryOptions(r){if(r._defaulted)return r;let t={...this.#a.queries,...this.getQueryDefaults(r.queryKey),...r,_defaulted:!0};if(!t.queryHash)t.queryHash=R(t.queryKey,t);if(t.refetchOnReconnect===void 0)t.refetchOnReconnect=t.networkMode!=="always";if(t.throwOnError===void 0)t.throwOnError=!!t.suspense;if(!t.networkMode&&t.persister)t.networkMode="offlineFirst";if(t.queryFn===j)t.enabled=!1;return t}defaultMutationOptions(r){if(r?._defaulted)return r;return{...this.#a.mutations,...r?.mutationKey&&this.getMutationDefaults(r.mutationKey),...r,_defaulted:!0}}clear(){this.#r.clear(),this.#t.clear()}};var it=new dr;var l={all:["workspaces"],discover:["workspaces","discover"],previews:["workspaces","previews"],layout:(r)=>["workspaces","layout",r],widgets:(r)=>["workspaces","widgets",r],appletThumbnails:(r)=>["workspaces","applet-thumbnails",r],views:(r)=>["workspaces","views",r],sessions:(r)=>["workspaces","sessions",r],events:(r,t)=>["workspaces","events",r,t],state:(r)=>["workspaces","state",r],mcp:(r)=>["workspaces","mcp",r],harness:(r)=>["workspaces","harness",r],skills:(r)=>["workspaces","skills",r],env:(r)=>["workspaces","env",r]};var pr=(r,t)=>t.getQueryData(l.layout(r));function Bt(r,t=it){return pr(r,t)?.isRemote??!1}function ie(r,t=it){let a=pr(r,t)?.apiBase;if(!a)throw Error("Workspace identity is not loaded");return a}function hr(r,t=it){let a=pr(r,t)?.apiBase;return a?decodeURIComponent(a.slice(16)):r}function gr(r){if(!Be(r)||!Array.isArray(r.members)||!Array.isArray(r.invitations))throw Error("Invalid workspace members");let t=r.members.map((o)=>{let i=nt(o);if(Be(o)&&o.membershipId!==void 0){if(typeof o.membershipId!=="string"||!o.membershipId||o.membershipId.length>240)throw Error("Invalid membership id");return{...i,membershipId:o.membershipId}}return i}),a=r.invitations.map((o)=>{if(!Be(o)||typeof o.id!=="string"||!o.id||typeof o.email!=="string"||!o.email||typeof o.expiresAt!=="string"||!Number.isFinite(Date.parse(o.expiresAt)))throw Error("Invalid invitation");return{id:o.id,email:o.email,expiresAt:o.expiresAt}});if(new Set(t.map(ze)).size!==t.length||new Set(a.map((o)=>o.id)).size!==a.length)throw Error("Duplicate workspace member or invitation");return{members:t,invitations:a}}function G(r){if(!/^(?:[A-Za-z0-9_-]{1,64}:)?[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(r))throw Error("Invalid workspace id");return r}var ur;function x(){let r=ce();if(ur?.accountGeneration!==r)ur={accountGeneration:r,lists:new Map,complete:!1};return ur}var Xr=0,mr=new Set;function q(){Xr++,mr.forEach((r)=>r())}var Gr=()=>Xr,$r=new WeakMap,Tt={members:[],invitations:[]},Yr=new WeakMap;function Zr(r){if(!x().complete)return;if(r.includes(":"))return Tt;let t=Te();if(t?.type!=="user"||t.isAnonymous)return;let a=$r.get(t);if(!a)a={members:[t],invitations:[]},$r.set(t,a);return a}function Z(r,t){let{lists:a}=x();a.set(r,We(a.get(r),t))}function rt(r,t){Z(G(r),gr(t)),q()}function tt(r){if(!Array.isArray(r))throw Error("Invalid workspace members");let t=r.map((i)=>[G(i.id),gr(i)]),a=new Set(t.map(([i])=>i));if(a.size!==t.length)throw Error("Duplicate workspace id");let{lists:o}=x();for(let i of o.keys())if(!a.has(i))o.delete(i);for(let[i,c]of t)Z(i,c);x().complete=!0,q()}function at(r){x().lists.delete(G(r)),q()}function et(){x().lists.clear(),q()}function nn(r,t){let a=hr(r),o=x().lists.get(a)??Zr(a),i=o&&t(o);if(!i)return;Z(a,i),q()}function sn(r){let t=ze(r);for(let[a,o]of x().lists)Z(a,{...o,members:o.members.map((i)=>ze(i)===t?{...r,...i.membershipId&&{membershipId:i.membershipId}}:i)});q()}function Do(r){let t=hr(r);return x().lists.get(t)??Zr(t)}function an(r){let t=Do(r);if(!t)return;let a=Yr.get(t);if(!a)a=t.members.map((o)=>P({id:bt(o),name:o.name||void 0,avatar:o.avatar,email:o.type==="user"?o.email||void 0:void 0})),Yr.set(t,a);return a}function wr(r){mr.add(r);let t=it.getQueryCache().subscribe((a)=>{let[o,i]=a.query.queryKey;if(o===l.all[0]&&i==="layout")r()});return()=>{mr.delete(r),t()}}function ot(){if(typeof window>"u")return;let r=window;r.moi??={},r.moi.identity={set:vt,getRevision:br},r.moi.workspaceMembers={set:rt,setAll:tt,remove:at,clear:et,getRevision:Gr}}ot();Pr();async function Lt(r){let[{mount:t},a,o]=await Promise.all([(Fe("ba6mz56s"),import("/chunk-ba6mz56s.js")),(Fe("en7w5ypg"),import("/chunk-en7w5ypg.js")).then((i)=>i.loadAppConfig()),(Fe("ec5ennpv"),import("/chunk-ec5ennpv.js")).then((i)=>i.loadProxyUser())]);Ar(a?.environment==="local"&&!a.demo,o),t(r)}globalThis.__init=Lt;export{e,I,Ft,tn,Fe,Jr,rn,Be,nt,ze,bt,Te,br,ce,Qr,vt,pe,wt,ve,on,eo,He,H,to,ro,U,Zt,Ue,We,St,vr,Jt,Qt,ge,er,M,_o,Mo,it,l,Bt,ie,nn,sn,Do,an,wr};