moi-computer 0.3.0-next.1 → 0.3.0-next.3
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.
- package/README.md +1 -1
- package/bunfig.toml +5 -1
- package/client/AGENTS.md +17 -2
- package/client/accept-hmr-dependencies.ts +22 -0
- package/client/api/http.ts +31 -0
- package/client/api/query-options.ts +6 -0
- package/client/api/workspace-keys.ts +18 -0
- package/client/app/AppRouter.tsx +44 -0
- package/client/app/routes/HomeRoute.tsx +13 -0
- package/client/app/routes/WorkspaceRoute.tsx +95 -0
- package/client/app/shell/SidebarLayout.tsx +196 -0
- package/client/assets/openai.svg +3 -0
- package/client/assets.d.ts +9 -0
- package/client/components/{BottomPanel.tsx → shared/BottomPanel.tsx} +2 -2
- package/client/components/shared/PanelHeader.tsx +9 -0
- package/client/components/shared/ReorderableList.tsx +199 -0
- package/client/components/ui/button.tsx +11 -7
- package/client/components/ui/collapsible.tsx +15 -0
- package/client/components/ui/dialog.tsx +2 -2
- package/client/components/ui/dropdown-menu.tsx +5 -5
- package/client/components/ui/hover-card.tsx +1 -1
- package/client/components/ui/input.tsx +1 -1
- package/client/components/ui/popover.tsx +1 -1
- package/client/components/ui/skeleton.tsx +13 -0
- package/client/components/ui/tooltip.tsx +1 -1
- package/client/externalize-react.ts +7 -1
- package/client/features/applets/AppletMount.tsx +44 -0
- package/client/{components → features/applets}/WidgetErrorBoundary.tsx +1 -1
- package/client/{components → features/applets}/WidgetShell.tsx +5 -2
- package/client/{lib → features/applets}/applet-cache.ts +8 -0
- package/client/features/applets/applet-styles.ts +61 -0
- package/client/{hooks → features/applets}/useApplet.ts +6 -7
- package/client/{components/ChatInput.tsx → features/chat/ChatComposer.tsx} +30 -24
- package/client/features/chat/ChatPanel.tsx +171 -0
- package/client/{components → features/chat}/ChatPopup.tsx +24 -13
- package/client/{components/ThreadSelector.tsx → features/chat/ChatSelector.tsx} +15 -13
- package/client/{components → features/chat}/MarkdownContent.tsx +1 -1
- package/client/{components → features/chat}/ModelPicker.tsx +68 -17
- package/client/{components → features/chat}/TurnView.tsx +17 -11
- package/client/features/chat/api.ts +78 -0
- package/client/features/chat/chat-connection.ts +107 -0
- package/client/features/chat/chat-frames.ts +131 -0
- package/client/features/chat/chat-send.ts +57 -0
- package/client/{lib → features/chat}/preview-turn.ts +1 -1
- package/client/{components → features/chat}/tool-group/ReadImagePreview.tsx +1 -1
- package/client/{components → features/chat}/tool-group/SubagentCard.tsx +12 -10
- package/client/{components → features/chat}/tool-group/TimelineRow.tsx +5 -5
- package/client/{components → features/chat}/tool-group/ToolCallGroup.tsx +14 -5
- package/client/{components → features/chat}/tool-group/ToolOutput.tsx +12 -18
- package/client/{components → features/chat}/tool-group/format.ts +117 -0
- package/client/{hooks → features/chat}/useChat.ts +16 -44
- package/client/features/connectors/ConnectorsPage.tsx +92 -0
- package/client/features/connectors/McpMenu.tsx +145 -0
- package/client/features/connectors/api.ts +28 -0
- package/client/features/dev/DevRoutes.tsx +18 -0
- package/client/features/dev/HarnessDebugPage.tsx +468 -0
- package/client/{components/playground → features/dev}/PixelPainter.tsx +10 -21
- package/client/{components/playground → features/dev}/PlaygroundPage.tsx +10 -12
- package/client/{components/playground → features/dev}/ToolCallsPage.tsx +9 -11
- package/client/features/home/CreateWorkspaceDialog.tsx +130 -0
- package/client/features/home/CreateWorkspaceDialogSteps.tsx +234 -0
- package/client/features/home/HomeLogo.tsx +344 -0
- package/client/features/home/HomePage.tsx +214 -0
- package/client/{components → features/home}/WorkspacePreview.tsx +4 -4
- package/client/features/home/api.ts +156 -0
- package/client/features/home/workspace-presentation.tsx +44 -0
- package/client/features/scratchpad/Scratchpad.tsx +312 -0
- package/client/features/scratchpad/ScratchpadControls.tsx +503 -0
- package/client/features/scratchpad/useScratchpadSnapshot.tsx +115 -0
- package/client/features/settings/EnvironmentSettings.tsx +149 -0
- package/client/features/settings/GeneralSettings.tsx +90 -0
- package/client/{components → features}/settings/IconPicker.tsx +76 -224
- package/client/features/settings/SettingsLayout.tsx +53 -0
- package/client/{components → features}/settings/WorkspaceSettings.tsx +12 -16
- package/client/features/settings/api.ts +88 -0
- package/client/features/settings/icon-picker-options.ts +30 -0
- package/client/{hooks → features/settings}/useEnvVars.ts +4 -4
- package/client/features/views/ViewBuilderTab.tsx +153 -0
- package/client/features/views/api.ts +124 -0
- package/client/features/views/useViewBuilderActions.ts +72 -0
- package/client/{components → features/widgets}/HiddenPanel.tsx +3 -3
- package/client/{components → features/widgets}/WidgetFrame.tsx +3 -8
- package/client/{components → features/widgets}/WidgetGrid.tsx +38 -29
- package/client/features/widgets/Widgets.tsx +265 -0
- package/client/{lib/grid-pack.ts → features/widgets/grid.ts} +7 -1
- package/client/{hooks → features/widgets}/useGridReconcile.ts +1 -1
- package/client/{components → features/workspace}/CustomizePanel.tsx +5 -6
- package/client/{lib → features/workspace}/WorkspaceLayoutContext.tsx +16 -15
- package/client/features/workspace/WorkspaceScreen.tsx +675 -0
- package/client/features/workspace/WorkspaceTabs.tsx +205 -0
- package/client/features/workspace/api.ts +56 -0
- package/client/features/workspace/useFitsSplitLayout.ts +37 -0
- package/client/global.d.ts +5 -0
- package/client/index.css +6 -45
- package/client/index.html +2 -2
- package/client/index.tsx +14 -31
- package/client/lib/app-icon-registry.ts +145 -0
- package/client/main.tsx +2 -2
- package/client/runtime/hmr-watchdog.ts +39 -0
- package/client/{hooks/useMeiEvents.ts → runtime/useWorkspaceEvents.ts} +12 -7
- package/client/store/ui.ts +5 -1
- package/client/theme.css +1 -3
- package/dist/chunk-11cab5dq.css +1 -0
- package/dist/chunk-4vf1t6v1.js +10 -0
- package/dist/chunk-6c24yndg.js +61 -0
- package/dist/chunk-6c8cwpzc.js +1 -0
- package/dist/chunk-b4b276wx.js +15 -0
- package/dist/chunk-cs8vbert.js +546 -0
- package/dist/chunk-cwqmay73.css +1 -0
- package/dist/chunk-kxmvv1ax.js +48 -0
- package/dist/chunk-pcnahct1.js +5 -0
- package/dist/chunk-rq0ar7vp.js +1 -0
- package/dist/chunk-tqd3pkg8.css +1 -0
- package/dist/chunk-vkvb3hjm.js +2 -0
- package/dist/chunk-zpxrb1ce.js +2 -0
- package/dist/index.html +3 -3
- package/dist/openai-h13pza4b.svg +3 -0
- package/lib/format.ts +2 -2
- package/lib/types.ts +56 -9
- package/lib/view-builder-meta.ts +35 -0
- package/lib/workspace-layout.ts +14 -0
- package/lib/workspace-name.ts +14 -0
- package/package.json +4 -2
- package/server/AGENTS.md +3 -3
- package/server/api.ts +279 -60
- package/server/applets.ts +1 -1
- package/server/bundle-queue.ts +19 -0
- package/server/bundler/applet-css.ts +50 -0
- package/server/{build-applet.ts → bundler/build-applet.ts} +36 -26
- package/server/cli.ts +90 -7
- package/server/control.ts +106 -8
- package/server/env-apply.ts +2 -2
- package/server/harness/README.md +228 -0
- package/server/harness/claude-code/NOTES.md +578 -0
- package/{lib/claude-adapter.ts → server/harness/claude-code/adapter.ts} +67 -5
- package/server/harness/claude-code/index.ts +124 -0
- package/server/{mcp.ts → harness/claude-code/mcp.ts} +73 -16
- package/server/{cc-session.ts → harness/claude-code/session.ts} +42 -14
- package/server/harness/claude-code/sessions.ts +42 -0
- package/server/harness/codex/NOTES.md +239 -0
- package/server/harness/codex/adapter.ts +414 -0
- package/server/harness/codex/client.ts +343 -0
- package/server/harness/codex/index.ts +68 -0
- package/server/harness/codex/probe.ts +186 -0
- package/server/harness/codex/session.ts +617 -0
- package/server/harness/debug.ts +57 -0
- package/server/harness/openclaw/NOTES.md +316 -0
- package/server/{openclaw-adapter.ts → harness/openclaw/adapter.ts} +2 -2
- package/server/harness/openclaw/index.ts +93 -0
- package/server/{openclaw-session.ts → harness/openclaw/session.ts} +44 -9
- package/server/{openclaw-strip.ts → harness/openclaw/strip.ts} +3 -1
- package/server/harness/registry.ts +36 -0
- package/server/harness/types.ts +87 -0
- package/server/layout.ts +36 -11
- package/server/moi-scaffold.ts +56 -11
- package/server/registry.ts +30 -52
- package/server/state.ts +5 -38
- package/server/status.ts +7 -46
- package/server/vendor.ts +1 -1
- package/server/view-builders.ts +428 -0
- package/server/views.ts +0 -0
- package/server/web.ts +19 -40
- package/server/workspace-init.ts +11 -25
- package/tsconfig.json +1 -1
- package/workspace/.claude/skills/moi-workspace/DESIGN.md +2 -1
- package/workspace/.claude/skills/moi-workspace/SKILL.md +28 -7
- package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +1 -1
- package/client/api/workspaces.ts +0 -427
- package/client/assets/hermes-nous.png +0 -0
- package/client/components/App.tsx +0 -41
- package/client/components/ChatPanel.tsx +0 -275
- package/client/components/HomePage.tsx +0 -17
- package/client/components/McpMenu.tsx +0 -125
- package/client/components/Scratchpad.tsx +0 -935
- package/client/components/Widgets.tsx +0 -132
- package/client/components/WorkspacesPage.tsx +0 -245
- package/client/components/layout/SidebarLayout.tsx +0 -258
- package/client/components/routes/workspace/[id].tsx +0 -675
- package/client/components/routes/workspace/create.tsx +0 -155
- package/client/components/settings/SettingsPages.tsx +0 -255
- package/client/hooks/useFitsSidebar.ts +0 -34
- package/client/hooks/useScrollFade.ts +0 -38
- package/client/lib/connection.ts +0 -238
- package/dist/chunk-07qf2tv1.css +0 -1
- package/dist/chunk-w18801vn.js +0 -672
- package/dist/hermes-nous-pznd63x9.png +0 -0
- /package/client/components/{playground → shared}/LedLogo.tsx +0 -0
- /package/client/{components → features/chat}/ShimmerText.tsx +0 -0
- /package/client/{store/live.ts → features/chat/chat-store.ts} +0 -0
- /package/client/{lib → features/chat}/group-turns.ts +0 -0
- /package/client/{components → features/chat}/tool-group/CodeBlock.tsx +0 -0
- /package/client/{components → features/chat}/tool-group/Collapse.tsx +0 -0
- /package/client/{components → features/chat}/tool-group/detect.ts +0 -0
- /package/client/{components → features/chat}/tool-group/fixtures.ts +0 -0
- /package/client/{components → features/chat}/tool-group/index.ts +0 -0
- /package/client/{lib → features/chat}/uploads.ts +0 -0
- /package/client/{hooks → features/chat}/useStickToBottom.ts +0 -0
- /package/client/{components → features/connectors}/IconMcp.tsx +0 -0
- /package/client/{lib → features/connectors}/mcp-icons.ts +0 -0
- /package/client/{lib → features/scratchpad}/scratch-executor.ts +0 -0
- /package/client/{lib → features/settings}/render-icon.ts +0 -0
- /package/client/{lib → features/workspace}/WorkspaceContext.tsx +0 -0
- /package/client/{hooks → features/workspace}/useWorkspaceTheme.ts +0 -0
- /package/server/{agent.ts → harness/claude-code/models.ts} +0 -0
- /package/server/{openclaw.ts → harness/openclaw/discovery.ts} +0 -0
- /package/server/{openclaw-gateway.ts → harness/openclaw/gateway.ts} +0 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const VIEW_BUILDER_OPEN = '<moi>'
|
|
2
|
+
const VIEW_BUILDER_CLOSE = '</moi>'
|
|
3
|
+
const VIEW_BUILDER_MARKER = 'View builder request'
|
|
4
|
+
|
|
5
|
+
export function appendViewBuilderMeta(
|
|
6
|
+
requirements: string,
|
|
7
|
+
builderId: string,
|
|
8
|
+
availableIcons: string[]
|
|
9
|
+
): string {
|
|
10
|
+
const context = [
|
|
11
|
+
VIEW_BUILDER_OPEN,
|
|
12
|
+
VIEW_BUILDER_MARKER,
|
|
13
|
+
`Builder id: ${builderId}`,
|
|
14
|
+
`Available view icons: ${availableIcons.join(', ')}`,
|
|
15
|
+
'Your first action must be to infer a stable view id, sentence-case title, and relevant icon from the requirements, then run:',
|
|
16
|
+
`moi builder set <view-id> --builder ${builderId} --kind view --title "<title>" --icon <icon-id>`,
|
|
17
|
+
'Do this before reading files, planning, or writing code. Choose the icon id from the available view icons above.',
|
|
18
|
+
'Capitalize only the first word of the title.',
|
|
19
|
+
'Use the same icon id in the view config.',
|
|
20
|
+
'After building the view, run `moi bundle --only views`.',
|
|
21
|
+
VIEW_BUILDER_CLOSE
|
|
22
|
+
].join('\n')
|
|
23
|
+
return `${requirements.trim()}\n\n${context}`
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function stripViewBuilderMeta(text: string): string {
|
|
27
|
+
const start = text.lastIndexOf(VIEW_BUILDER_OPEN)
|
|
28
|
+
if (start === -1) return text
|
|
29
|
+
const end = text.indexOf(VIEW_BUILDER_CLOSE, start)
|
|
30
|
+
if (end === -1) return text
|
|
31
|
+
if (!text.slice(start, end).includes(VIEW_BUILDER_MARKER)) return text
|
|
32
|
+
const before = text.slice(0, start)
|
|
33
|
+
const after = text.slice(end + VIEW_BUILDER_CLOSE.length)
|
|
34
|
+
return `${before}${after}`.trim()
|
|
35
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { WorkspaceLayout, WorkspaceTabsState } from './types'
|
|
2
|
+
|
|
3
|
+
export function createDefaultWorkspaceTabs(): WorkspaceTabsState {
|
|
4
|
+
return { open: ['agent', 'widgets'], active: 'agent' }
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function createDefaultWorkspaceLayout(): WorkspaceLayout {
|
|
8
|
+
return {
|
|
9
|
+
version: 1,
|
|
10
|
+
widgetGrid: [],
|
|
11
|
+
layoutMode: 'fullscreen',
|
|
12
|
+
tabs: createDefaultWorkspaceTabs()
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Validate a workspace folder name as one safe path segment. Shared by the
|
|
2
|
+
// server endpoint and the client form so instant feedback cannot drift from the
|
|
3
|
+
// authoritative create path.
|
|
4
|
+
export function validateWorkspaceFolderName(name: string): string | null {
|
|
5
|
+
if (!name) return 'Folder name is required'
|
|
6
|
+
if (name.length > 64) return 'Folder name is too long (max 64 characters)'
|
|
7
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._ -]*$/.test(name)) {
|
|
8
|
+
return 'Use letters, numbers, dots, dashes, underscores and spaces, starting with a letter or number'
|
|
9
|
+
}
|
|
10
|
+
if (name.endsWith('.') || name.endsWith(' ')) {
|
|
11
|
+
return 'Folder name cannot end with a dot or space'
|
|
12
|
+
}
|
|
13
|
+
return null
|
|
14
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "moi-computer",
|
|
3
|
-
"version": "0.3.0-next.
|
|
3
|
+
"version": "0.3.0-next.3",
|
|
4
4
|
"description": "Local AI workspace powered by the Claude Agent SDK, Bun, React, and Tailwind. Requires Bun.",
|
|
5
5
|
"license": "Elastic-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -50,6 +50,7 @@
|
|
|
50
50
|
"prepack": "bun scripts/build-client.ts",
|
|
51
51
|
"lint": "oxlint",
|
|
52
52
|
"lint:fix": "oxlint --fix",
|
|
53
|
+
"typecheck:client": "tsc -p tsconfig.client.json",
|
|
53
54
|
"format": "oxfmt",
|
|
54
55
|
"format:check": "oxfmt --check",
|
|
55
56
|
"prepare": "git config core.hooksPath .githooks"
|
|
@@ -77,6 +78,7 @@
|
|
|
77
78
|
"motion": "^12.35.1",
|
|
78
79
|
"pathe": "^2.0.3",
|
|
79
80
|
"picocolors": "^1.1.1",
|
|
81
|
+
"postcss": "^8.5.19",
|
|
80
82
|
"react": "^19",
|
|
81
83
|
"react-dom": "^19",
|
|
82
84
|
"react-grid-layout": "^2.2.3",
|
|
@@ -84,7 +86,7 @@
|
|
|
84
86
|
"react-resizable": "^3.1.3",
|
|
85
87
|
"rehype-highlight": "^7.0.2",
|
|
86
88
|
"remark-gfm": "^4.0.1",
|
|
87
|
-
"shadcn": "^4.0
|
|
89
|
+
"shadcn": "^4.13.0",
|
|
88
90
|
"sharp": "^0.35.1",
|
|
89
91
|
"sugar-high": "^1.2.1",
|
|
90
92
|
"tailwind-merge": "^3.5.0",
|
package/server/AGENTS.md
CHANGED
|
@@ -3,7 +3,7 @@ Bun server on port 13337. Serves the client at `/`, upgrades `/ws` to WebSocket.
|
|
|
3
3
|
- `web.ts` owns the Bun fullstack surface only: the SPA HTML shell (dev bundler + HMR / prebuilt `dist/`), the two WebSocket channels (`/ws` chat, `/api/workspaces/ws` live events), and graceful shutdown. Every HTTP API request is delegated to the Hono app via `fetch`.
|
|
4
4
|
- `api.ts` is the Hono REST API (all `/api/*` routes). `withWorkspace` middleware resolves `:id` → workspace (404 if missing) and stashes it on the context, so handlers read `c.get('ws')`. Its catch-all serves the prebuilt client from `dist/` in prod via Hono's `serveStatic` (cached, traversal-safe).
|
|
5
5
|
- `static.ts` exposes the `dist/` location (`DIST_DIR`), the `prebuilt` flag, and the prod SPA `distShell`. `events.ts` holds `publishEvent` (server→client live-event broadcast over `/api/workspaces/ws`) decoupled from `web.ts` to avoid an import cycle; `web.ts` wires it via `setEventServer`.
|
|
6
|
-
- `state.ts` holds
|
|
7
|
-
- `
|
|
6
|
+
- `state.ts` holds the connected chat clients and `broadcast()` (which also feeds the harness debug tap).
|
|
7
|
+
- `harness/` holds every agent backend (Claude Code, OpenClaw, Codex): per-harness adapter + session + transport + protocol NOTES, colocated. Read `harness/README.md` for the message-type layers, the adapter contract, and the folder conventions before touching agent-backend code.
|
|
8
8
|
- WebSocket protocol: server sends `ServerMessage`, client sends `ClientMessage` — both defined in `lib/types.ts`.
|
|
9
|
-
-
|
|
9
|
+
- Agents run in the workspace directory with bypass permissions; each backend persists its own session history (see `harness/README.md`).
|
package/server/api.ts
CHANGED
|
@@ -4,37 +4,45 @@ import { createMiddleware } from 'hono/factory'
|
|
|
4
4
|
import { existsSync } from 'node:fs'
|
|
5
5
|
import { basename, join, resolve } from 'node:path'
|
|
6
6
|
|
|
7
|
-
import type { UploadInfo, WorkspaceEntry, WorkspaceModels
|
|
7
|
+
import type { UploadInfo, ViewBuilderInput, WorkspaceEntry, WorkspaceModels } from '@/lib/types'
|
|
8
|
+
import { appendViewBuilderMeta } from '@/lib/view-builder-meta'
|
|
8
9
|
|
|
9
|
-
import { getClaudeModels } from './agent'
|
|
10
10
|
import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from './applets'
|
|
11
11
|
import { applyEnvChanged } from './env-apply'
|
|
12
|
+
import { publishEvent } from './events'
|
|
12
13
|
import { callFunction, parseFunctionPath } from './functions'
|
|
13
14
|
import { processIcon } from './icon'
|
|
14
15
|
import { getWorkspacePreview, loadLayout, mergeLayoutForSave, saveLayout } from './layout'
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import { toSessionInfo, toStreamEvents } from './openclaw-adapter'
|
|
19
|
-
import { ensureOpenClawSessionLive, getLiveOpenClawEvents } from './openclaw-session'
|
|
16
|
+
import { getUserMcpStatus } from './harness/claude-code/mcp'
|
|
17
|
+
import { getClientFrameLog, getWireLog } from './harness/debug'
|
|
18
|
+
import { allHarnesses, harnessFor, isHarnessType } from './harness/registry'
|
|
20
19
|
import {
|
|
21
20
|
discoverWorkspaces,
|
|
22
21
|
getWorkspace,
|
|
23
22
|
listWorkspaces,
|
|
24
23
|
registerWorkspace,
|
|
25
24
|
removeWorkspace,
|
|
25
|
+
reorderWorkspaces,
|
|
26
26
|
tildify
|
|
27
27
|
} from './registry'
|
|
28
28
|
import { loadScratchpadDoc, saveScratchpadDoc } from './scratchpad'
|
|
29
29
|
import { MAX_ASSET_BYTES, scratchpadAssetFile, storeScratchpadAsset } from './scratchpad-assets'
|
|
30
30
|
import { DIST_DIR, prebuilt } from './static'
|
|
31
|
-
import { getSessionEvents, getSessions } from './state'
|
|
32
31
|
import { getThreadConfig, saveThreadConfig } from './thread-config'
|
|
33
32
|
import type { ThreadConfigPatch } from './thread-config'
|
|
34
33
|
import { serveWorkspaceImagePreview } from './preview'
|
|
35
34
|
import { MAX_UPLOAD_BYTES, addUpload, getUpload } from './uploads'
|
|
36
35
|
import { requiredEnvFor } from './required-env'
|
|
37
|
-
import { listViews, serveView } from './views'
|
|
36
|
+
import { getViewList, listViews, serveView } from './views'
|
|
37
|
+
import {
|
|
38
|
+
ViewBuilderError,
|
|
39
|
+
beginViewBuilder,
|
|
40
|
+
createViewBuilder,
|
|
41
|
+
deleteViewBuilder,
|
|
42
|
+
markViewBuilderWaiting,
|
|
43
|
+
reconcileViewBuilders,
|
|
44
|
+
updateViewBuilderInput
|
|
45
|
+
} from './view-builders'
|
|
38
46
|
import { listWidgets, serveWidget } from './widgets'
|
|
39
47
|
import { getWorkspaceConfig, setWorkspaceConfig } from './workspace-config'
|
|
40
48
|
import {
|
|
@@ -69,7 +77,9 @@ async function handleFunctionCall(
|
|
|
69
77
|
}
|
|
70
78
|
const args = await req.text()
|
|
71
79
|
const result = await callFunction(module, name, args, workspacePath)
|
|
72
|
-
return new Response(result, {
|
|
80
|
+
return new Response(result, {
|
|
81
|
+
headers: { 'Content-Type': 'application/json' }
|
|
82
|
+
})
|
|
73
83
|
} catch (err) {
|
|
74
84
|
const message = err instanceof Error ? err.message : 'Unknown error'
|
|
75
85
|
return new Response(message, { status: 500 })
|
|
@@ -118,6 +128,129 @@ one.get('/views/*', c => {
|
|
|
118
128
|
return serveView(name, file, c.get('ws').path, apiBaseFor(id), c.req.header('if-none-match'))
|
|
119
129
|
})
|
|
120
130
|
|
|
131
|
+
function viewBuilderError(err: unknown): { message: string; status: 400 | 404 | 409 } | null {
|
|
132
|
+
return err instanceof ViewBuilderError ? { message: err.message, status: err.status } : null
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function parseAvailableViewIcons(value: unknown): string[] | null {
|
|
136
|
+
if (!Array.isArray(value)) return null
|
|
137
|
+
const icons = value.filter(
|
|
138
|
+
(icon): icon is string =>
|
|
139
|
+
typeof icon === 'string' && /^[a-z0-9][a-z0-9-]*$/.test(icon) && icon.length <= 64
|
|
140
|
+
)
|
|
141
|
+
return icons.length > 0 ? [...new Set(icons)] : null
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
one.get('/view-builders', async c => {
|
|
145
|
+
const ws = c.get('ws')
|
|
146
|
+
const activeSessionIds = new Set(
|
|
147
|
+
allHarnesses()
|
|
148
|
+
.flatMap(h => h.runningSessions())
|
|
149
|
+
.filter(session => session.workspaceId === ws.id)
|
|
150
|
+
.map(session => session.sessionId)
|
|
151
|
+
)
|
|
152
|
+
const builders = await reconcileViewBuilders(
|
|
153
|
+
ws.id,
|
|
154
|
+
ws.path,
|
|
155
|
+
await getViewList(ws.path),
|
|
156
|
+
activeSessionIds
|
|
157
|
+
)
|
|
158
|
+
// Widget builders are record-only for now — reconciled server-side but kept
|
|
159
|
+
// out of the host's view-builder tab list until their UI lands.
|
|
160
|
+
return c.json({ builders: builders.filter(builder => builder.kind !== 'widget') })
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
one.post('/view-builders', async c => {
|
|
164
|
+
const ws = c.get('ws')
|
|
165
|
+
return c.json(await createViewBuilder(ws.id, ws.path), 201)
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
one.patch('/view-builders/:builderId', async c => {
|
|
169
|
+
const ws = c.get('ws')
|
|
170
|
+
const body = await c.req.json<{ input?: Partial<ViewBuilderInput> }>()
|
|
171
|
+
if (typeof body?.input?.requirements !== 'string') {
|
|
172
|
+
return c.text('Expected { input: { requirements: string } }', 400)
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
return c.json(
|
|
176
|
+
await updateViewBuilderInput(
|
|
177
|
+
ws.id,
|
|
178
|
+
ws.path,
|
|
179
|
+
c.req.param('builderId'),
|
|
180
|
+
body.input.requirements
|
|
181
|
+
)
|
|
182
|
+
)
|
|
183
|
+
} catch (err) {
|
|
184
|
+
const known = viewBuilderError(err)
|
|
185
|
+
if (known) return c.text(known.message, known.status)
|
|
186
|
+
throw err
|
|
187
|
+
}
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
one.post('/view-builders/:builderId/submit', async c => {
|
|
191
|
+
const ws = c.get('ws')
|
|
192
|
+
const body = await c.req.json<{
|
|
193
|
+
input?: Partial<ViewBuilderInput>
|
|
194
|
+
optimisticId?: string
|
|
195
|
+
model?: string
|
|
196
|
+
effort?: string
|
|
197
|
+
stream?: boolean
|
|
198
|
+
availableIcons?: unknown
|
|
199
|
+
}>()
|
|
200
|
+
if (typeof body?.input?.requirements !== 'string') {
|
|
201
|
+
return c.text('Expected { input: { requirements: string } }', 400)
|
|
202
|
+
}
|
|
203
|
+
if (body.optimisticId !== undefined && typeof body.optimisticId !== 'string') {
|
|
204
|
+
return c.text('Invalid optimisticId', 400)
|
|
205
|
+
}
|
|
206
|
+
const availableIcons = parseAvailableViewIcons(body.availableIcons)
|
|
207
|
+
if (!availableIcons) return c.text('Available view icons are required', 400)
|
|
208
|
+
try {
|
|
209
|
+
const builder = await beginViewBuilder(
|
|
210
|
+
ws.id,
|
|
211
|
+
ws.path,
|
|
212
|
+
c.req.param('builderId'),
|
|
213
|
+
body.input.requirements
|
|
214
|
+
)
|
|
215
|
+
const content = appendViewBuilderMeta(builder.input.requirements, builder.id, availableIcons)
|
|
216
|
+
try {
|
|
217
|
+
await harnessFor(ws).sendMessage({
|
|
218
|
+
workspaceId: ws.id,
|
|
219
|
+
workspacePath: ws.path,
|
|
220
|
+
sessionId: builder.sessionId,
|
|
221
|
+
isNew: true,
|
|
222
|
+
content,
|
|
223
|
+
optimisticId: body.optimisticId,
|
|
224
|
+
model: typeof body.model === 'string' ? body.model : undefined,
|
|
225
|
+
effort: typeof body.effort === 'string' ? body.effort : undefined,
|
|
226
|
+
stream: body.stream === true ? true : undefined,
|
|
227
|
+
agentId: ws.agentId
|
|
228
|
+
})
|
|
229
|
+
} catch (err) {
|
|
230
|
+
const message = err instanceof Error ? err.message : 'Could not start view builder'
|
|
231
|
+
await markViewBuilderWaiting(ws.id, ws.path, builder.id, message)
|
|
232
|
+
return c.text(message, 500)
|
|
233
|
+
}
|
|
234
|
+
return c.json(builder)
|
|
235
|
+
} catch (err) {
|
|
236
|
+
const known = viewBuilderError(err)
|
|
237
|
+
if (known) return c.text(known.message, known.status)
|
|
238
|
+
throw err
|
|
239
|
+
}
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
one.delete('/view-builders/:builderId', async c => {
|
|
243
|
+
const ws = c.get('ws')
|
|
244
|
+
try {
|
|
245
|
+
await deleteViewBuilder(ws.id, ws.path, c.req.param('builderId'))
|
|
246
|
+
return c.body(null, 204)
|
|
247
|
+
} catch (err) {
|
|
248
|
+
const known = viewBuilderError(err)
|
|
249
|
+
if (known) return c.text(known.message, known.status)
|
|
250
|
+
throw err
|
|
251
|
+
}
|
|
252
|
+
})
|
|
253
|
+
|
|
121
254
|
// Workspace file stream — an applet's `fileUrl(path)` resolves here. Streams a
|
|
122
255
|
// media file from the workspace root (range-enabled). Guarded: traversal and
|
|
123
256
|
// dotfiles (`.env`, `.moi`, `.git`) are rejected and only media/asset extensions
|
|
@@ -212,41 +345,12 @@ one.get('/uploads/:uploadId', c => {
|
|
|
212
345
|
|
|
213
346
|
one.get('/sessions', async c => {
|
|
214
347
|
const ws = c.get('ws')
|
|
215
|
-
|
|
216
|
-
const rows = await getOpenClawSessions(ws.path, ws.agentId)
|
|
217
|
-
return c.json(rows.map(r => toSessionInfo(r, ws.path)))
|
|
218
|
-
}
|
|
219
|
-
return c.json(await getSessions(ws.path))
|
|
348
|
+
return c.json(await harnessFor(ws).listSessions(ws))
|
|
220
349
|
})
|
|
221
350
|
|
|
222
351
|
one.get('/sessions/:sessionId/events', async c => {
|
|
223
352
|
const ws = c.get('ws')
|
|
224
|
-
|
|
225
|
-
const sessionId = c.req.param('sessionId')
|
|
226
|
-
if (ws.type === 'openclaw') {
|
|
227
|
-
// Prefer the live view if we already hold one — keeps REST + WS in
|
|
228
|
-
// agreement for any reload that lands while a run is active. The first cold
|
|
229
|
-
// call also primes the live subscription so subsequent WS frames upsert into
|
|
230
|
-
// the same view.
|
|
231
|
-
const live = getLiveOpenClawEvents(id, sessionId)
|
|
232
|
-
if (live) return c.json(live)
|
|
233
|
-
if (ws.agentId) {
|
|
234
|
-
try {
|
|
235
|
-
const evs = await ensureOpenClawSessionLive({
|
|
236
|
-
workspaceId: id,
|
|
237
|
-
workspacePath: ws.path,
|
|
238
|
-
agentId: ws.agentId,
|
|
239
|
-
sessionId
|
|
240
|
-
})
|
|
241
|
-
return c.json(evs)
|
|
242
|
-
} catch {
|
|
243
|
-
// fall through to static path
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
const preview = await getOpenClawSessionMessages(sessionId, ws.path, ws.agentId)
|
|
247
|
-
return c.json(toStreamEvents(preview))
|
|
248
|
-
}
|
|
249
|
-
return c.json(await getSessionEvents(sessionId, ws.path))
|
|
353
|
+
return c.json(await harnessFor(ws).sessionEvents(ws, c.req.param('sessionId')))
|
|
250
354
|
})
|
|
251
355
|
|
|
252
356
|
// Per-thread agent settings (model + reasoning effort). GET returns the stored
|
|
@@ -276,7 +380,25 @@ one.put('/sessions/:sessionId/config', async c => {
|
|
|
276
380
|
})
|
|
277
381
|
|
|
278
382
|
one.get('/mcp', async c => {
|
|
279
|
-
|
|
383
|
+
const ws = c.get('ws')
|
|
384
|
+
return c.json((await harnessFor(ws).mcpStatus?.(ws)) ?? [])
|
|
385
|
+
})
|
|
386
|
+
|
|
387
|
+
// Harness debug tap for /playground/harness: the backend's native wire frames
|
|
388
|
+
// (Codex: app-server JSON-RPC, both directions; Claude Code: raw SDK messages
|
|
389
|
+
// + enqueued inputs) and the exact frames the server pushed to chat clients.
|
|
390
|
+
// `sinceWire`/`sinceBroadcast` are seq cursors so the page can poll deltas.
|
|
391
|
+
one.get('/harness/debug', async c => {
|
|
392
|
+
const ws = c.get('ws')
|
|
393
|
+
const harness = harnessFor(ws)
|
|
394
|
+
const sinceWire = Number(c.req.query('sinceWire') ?? 0) || 0
|
|
395
|
+
const sinceBroadcast = Number(c.req.query('sinceBroadcast') ?? 0) || 0
|
|
396
|
+
return c.json({
|
|
397
|
+
provider: harness.id,
|
|
398
|
+
process: (await harness.debugInfo?.(ws)) ?? null,
|
|
399
|
+
wire: getWireLog(harness.wireScope?.(ws) ?? ws.id, sinceWire),
|
|
400
|
+
broadcasts: getClientFrameLog(ws.id, sinceBroadcast)
|
|
401
|
+
})
|
|
280
402
|
})
|
|
281
403
|
|
|
282
404
|
// Per-workspace env vars. GET returns the effective view (discovered `.env` + UI
|
|
@@ -342,13 +464,12 @@ one.put('/env', async c => {
|
|
|
342
464
|
// account-wide Agent SDK model list.
|
|
343
465
|
one.get('/models', async c => {
|
|
344
466
|
const ws = c.get('ws')
|
|
345
|
-
const
|
|
346
|
-
|
|
347
|
-
provider
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
return c.json({ provider, models, supportsStreaming } satisfies WorkspaceModels)
|
|
467
|
+
const harness = harnessFor(ws)
|
|
468
|
+
return c.json({
|
|
469
|
+
provider: harness.id,
|
|
470
|
+
models: await harness.listModels(ws),
|
|
471
|
+
supportsStreaming: harness.capabilities.supportsStreaming
|
|
472
|
+
} satisfies WorkspaceModels)
|
|
352
473
|
})
|
|
353
474
|
|
|
354
475
|
// Workspace identity (name). GET returns the current {name, icon}; PUT a JSON
|
|
@@ -457,7 +578,7 @@ one.delete('/icon', async c => {
|
|
|
457
578
|
return c.body(null, 204)
|
|
458
579
|
})
|
|
459
580
|
|
|
460
|
-
// All info about a single workspace: its persisted layout (widget grid,
|
|
581
|
+
// All info about a single workspace: its persisted layout (widget grid, layout
|
|
461
582
|
// mode, theme) plus server-resolved metadata. GET reads, PUT writes the layout,
|
|
462
583
|
// DELETE unregisters.
|
|
463
584
|
one.get('/', async c => {
|
|
@@ -493,24 +614,45 @@ one.delete('/', async c => {
|
|
|
493
614
|
// ---- workspace collection: /api/workspaces ----------------------------------
|
|
494
615
|
const workspaces = new Hono<ApiEnv>()
|
|
495
616
|
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
// the sidebar reflects `moi config` changes immediately.
|
|
499
|
-
const entries = await listWorkspaces()
|
|
500
|
-
const merged = await Promise.all(
|
|
617
|
+
async function mergeWorkspaceList(entries: WorkspaceEntry[]) {
|
|
618
|
+
return Promise.all(
|
|
501
619
|
entries.map(async e => {
|
|
502
620
|
const layout = await loadLayout(e.path)
|
|
503
621
|
return { ...e, name: layout.name ?? e.name, icon: layout.icon }
|
|
504
622
|
})
|
|
505
623
|
)
|
|
506
|
-
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
workspaces.get('/', async c => {
|
|
627
|
+
// Merge each workspace's live layout name/icon over the registry snapshot so
|
|
628
|
+
// the sidebar reflects `moi config` changes immediately.
|
|
629
|
+
const entries = await listWorkspaces()
|
|
630
|
+
return c.json(await mergeWorkspaceList(entries))
|
|
631
|
+
})
|
|
632
|
+
|
|
633
|
+
workspaces.put('/order', async c => {
|
|
634
|
+
const body = await c.req.json()
|
|
635
|
+
if (!Array.isArray(body?.ids) || body.ids.some((id: unknown) => typeof id !== 'string')) {
|
|
636
|
+
return c.text('Expected { ids: string[] }', 400)
|
|
637
|
+
}
|
|
638
|
+
try {
|
|
639
|
+
const entries = await reorderWorkspaces(body.ids)
|
|
640
|
+
// List-only change: a narrow event so clients refetch just the sidebar
|
|
641
|
+
// list, not every per-workspace query (`workspace:updated` also triggers
|
|
642
|
+
// layout refetches in open workspaces).
|
|
643
|
+
publishEvent({ type: 'workspaces-list:updated' })
|
|
644
|
+
return c.json(await mergeWorkspaceList(entries))
|
|
645
|
+
} catch (err) {
|
|
646
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
647
|
+
return c.text(message, 400)
|
|
648
|
+
}
|
|
507
649
|
})
|
|
508
650
|
|
|
509
651
|
workspaces.post('/', async c => {
|
|
510
652
|
const body = await c.req.json()
|
|
511
653
|
if (!body?.path) return c.text('Missing path', 400)
|
|
512
654
|
const rawType = body?.type
|
|
513
|
-
const type = rawType
|
|
655
|
+
const type = isHarnessType(rawType) ? rawType : undefined
|
|
514
656
|
const path = resolve(String(body.path))
|
|
515
657
|
// Importing IS initializing: lay down the bundled skills (in the backend's
|
|
516
658
|
// skills dir) and the `.moi/` scaffold, exactly like `moi init` — a workspace
|
|
@@ -534,9 +676,14 @@ workspaces.post('/', async c => {
|
|
|
534
676
|
workspaces.get('/discover', async c => c.json(await discoverWorkspaces()))
|
|
535
677
|
|
|
536
678
|
// Where `/workspace/create` places new folders — the client shows the resolved
|
|
537
|
-
// location while the user types a name.
|
|
679
|
+
// location while the user types a name. `canChooseFolder` tells the UI whether
|
|
680
|
+
// the native folder picker is available (macOS only for now).
|
|
538
681
|
workspaces.get('/create', c =>
|
|
539
|
-
c.json({
|
|
682
|
+
c.json({
|
|
683
|
+
root: CREATED_WORKSPACES_ROOT,
|
|
684
|
+
displayRoot: tildify(CREATED_WORKSPACES_ROOT),
|
|
685
|
+
canChooseFolder: process.platform === 'darwin'
|
|
686
|
+
})
|
|
540
687
|
)
|
|
541
688
|
|
|
542
689
|
// Create a brand-new workspace: a fresh folder under CREATED_WORKSPACES_ROOT,
|
|
@@ -561,10 +708,78 @@ workspaces.post('/create', async c => {
|
|
|
561
708
|
}
|
|
562
709
|
const entry = await registerWorkspace(path, { type: 'claude-code' })
|
|
563
710
|
// Nudge every connected client (the sidebar list) to refetch.
|
|
564
|
-
publishEvent({ type: '
|
|
711
|
+
publishEvent({ type: 'workspaces-list:updated' })
|
|
565
712
|
return c.json(entry, 201)
|
|
566
713
|
})
|
|
567
714
|
|
|
715
|
+
// Guards against opening a second native picker while one is already up — a
|
|
716
|
+
// duplicate request (e.g. a quick re-click) resolves as canceled instead of
|
|
717
|
+
// spawning a second Finder dialog on top of the first.
|
|
718
|
+
let folderPickerOpen = false
|
|
719
|
+
|
|
720
|
+
export function isSameOriginRequest(req: Request): boolean {
|
|
721
|
+
const site = req.headers.get('sec-fetch-site')
|
|
722
|
+
if (site === 'cross-site') return false
|
|
723
|
+
// Modern browsers state the relationship directly — trust it. Reaching the
|
|
724
|
+
// Origin fallback below with a full-origin comparison would 403 every request
|
|
725
|
+
// behind a TLS-terminating proxy (Cloudflare Tunnel, nginx, ngrok — see
|
|
726
|
+
// client/lib/ws-url.ts): the browser sends `https://…` while `req.url` is
|
|
727
|
+
// built from the plain-HTTP listener.
|
|
728
|
+
if (site === 'same-origin') return true
|
|
729
|
+
const origin = req.headers.get('origin')
|
|
730
|
+
if (!origin) return true
|
|
731
|
+
// Older browsers without sec-fetch-site: compare hosts only, since the
|
|
732
|
+
// scheme the browser saw is unknowable behind TLS termination.
|
|
733
|
+
try {
|
|
734
|
+
return new URL(origin).host === new URL(req.url).host
|
|
735
|
+
} catch {
|
|
736
|
+
return false
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
// Open the OS-native folder picker so the user can choose an existing folder to
|
|
741
|
+
// import (the create dialog's "Use existing folder"). The server runs on the
|
|
742
|
+
// user's machine, so it can drive the real system dialog — the browser can't.
|
|
743
|
+
// Returns the chosen POSIX path, or `{ canceled: true }` if the dialog is
|
|
744
|
+
// dismissed. macOS only for now (via `osascript`).
|
|
745
|
+
workspaces.post('/choose-folder', async c => {
|
|
746
|
+
if (!isSameOriginRequest(c.req.raw)) return c.text('Forbidden', 403)
|
|
747
|
+
if (process.platform !== 'darwin') {
|
|
748
|
+
return c.text('Choosing a folder is only supported on macOS for now', 400)
|
|
749
|
+
}
|
|
750
|
+
if (folderPickerOpen) return c.json({ canceled: true })
|
|
751
|
+
folderPickerOpen = true
|
|
752
|
+
try {
|
|
753
|
+
// The picker is spawned by osascript, a background helper, so macOS won't
|
|
754
|
+
// give it focus by default. `tell me to activate` forces the script runner
|
|
755
|
+
// frontmost, and the short delay lets that settle before the panel opens so
|
|
756
|
+
// it appears focused rather than behind other windows.
|
|
757
|
+
const proc = Bun.spawn(
|
|
758
|
+
[
|
|
759
|
+
'osascript',
|
|
760
|
+
'-e',
|
|
761
|
+
'tell me to activate',
|
|
762
|
+
'-e',
|
|
763
|
+
'delay 0.2',
|
|
764
|
+
'-e',
|
|
765
|
+
'POSIX path of (choose folder with prompt "Select a project folder")'
|
|
766
|
+
],
|
|
767
|
+
{ stdout: 'pipe', stderr: 'pipe' }
|
|
768
|
+
)
|
|
769
|
+
const exitCode = await proc.exited
|
|
770
|
+
// osascript exits non-zero when the user presses Cancel.
|
|
771
|
+
if (exitCode !== 0) return c.json({ canceled: true })
|
|
772
|
+
const path = (await new Response(proc.stdout).text()).trim()
|
|
773
|
+
if (!path) return c.json({ canceled: true })
|
|
774
|
+
return c.json({ path })
|
|
775
|
+
} catch (err) {
|
|
776
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
777
|
+
return c.text(`Could not open the folder picker: ${message}`, 500)
|
|
778
|
+
} finally {
|
|
779
|
+
folderPickerOpen = false
|
|
780
|
+
}
|
|
781
|
+
})
|
|
782
|
+
|
|
568
783
|
// `/:id` is registered after the static `/discover` so the literal path wins.
|
|
569
784
|
// `/api/workspaces/ws` (the live-event WebSocket) is intercepted by Bun's routes
|
|
570
785
|
// table before it ever reaches Hono, so it never collides with `:id`.
|
|
@@ -573,6 +788,10 @@ workspaces.route('/:id', one)
|
|
|
573
788
|
// ---- top-level API ----------------------------------------------------------
|
|
574
789
|
export const api = new Hono()
|
|
575
790
|
|
|
791
|
+
api.get('/api/mcp', async c => {
|
|
792
|
+
return c.json(await getUserMcpStatus())
|
|
793
|
+
})
|
|
794
|
+
|
|
576
795
|
api.route('/api/workspaces', workspaces)
|
|
577
796
|
|
|
578
797
|
// Everything else: in production, serve the prebuilt client from `dist/` via
|
package/server/applets.ts
CHANGED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const bundleChains = new Map<string, Promise<unknown>>()
|
|
2
|
+
|
|
3
|
+
export function serializeWorkspaceBundle<T>(
|
|
4
|
+
workspacePath: string,
|
|
5
|
+
run: () => Promise<T>
|
|
6
|
+
): Promise<T> {
|
|
7
|
+
const previous = bundleChains.get(workspacePath) ?? Promise.resolve()
|
|
8
|
+
const current = previous.then(run, run)
|
|
9
|
+
bundleChains.set(workspacePath, current)
|
|
10
|
+
void current.then(
|
|
11
|
+
() => {
|
|
12
|
+
if (bundleChains.get(workspacePath) === current) bundleChains.delete(workspacePath)
|
|
13
|
+
},
|
|
14
|
+
() => {
|
|
15
|
+
if (bundleChains.get(workspacePath) === current) bundleChains.delete(workspacePath)
|
|
16
|
+
}
|
|
17
|
+
)
|
|
18
|
+
return current
|
|
19
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Scopes a compiled applet stylesheet to its mount container.
|
|
2
|
+
//
|
|
3
|
+
// Applet bundles compile with the full `@import 'tailwindcss'` — preflight,
|
|
4
|
+
// theme variables, utilities — and the result is injected into the host
|
|
5
|
+
// document at runtime. Unscoped, those rules are page-global: the widget's
|
|
6
|
+
// preflight resets host elements, its theme layer redefines variables on
|
|
7
|
+
// `:root`, and its utilities (arriving later in the document than the host
|
|
8
|
+
// stylesheet) win cascade ties against the host's — most visibly for
|
|
9
|
+
// media-query variants. Scoping pins every rule to the applet's own subtree.
|
|
10
|
+
//
|
|
11
|
+
// The transform prefixes each selector with `[data-applet="<scope>"]` — the
|
|
12
|
+
// attribute the client puts on the applet's mount container (see
|
|
13
|
+
// client/features/applets/AppletMount.tsx). Selectors that address the page
|
|
14
|
+
// root (`:root`, `:host`, `html`, `body`) are mapped onto the container
|
|
15
|
+
// itself, so theme variables and preflight inheritance (line-height, font)
|
|
16
|
+
// land there and inherit down. Rules inside `@keyframes` are left alone —
|
|
17
|
+
// keyframe step selectors (`0%`, `to`) aren't element selectors.
|
|
18
|
+
//
|
|
19
|
+
// The uniform `+1 attribute` specificity bump preserves the stylesheet's
|
|
20
|
+
// internal cascade and makes applet rules beat same-layer host rules inside
|
|
21
|
+
// the container — which is exactly the priority we want.
|
|
22
|
+
//
|
|
23
|
+
// Known limitation: content the applet portals outside its container
|
|
24
|
+
// (e.g. to document.body) escapes the scope and won't receive applet styles.
|
|
25
|
+
import postcss, { type Container, type Document } from 'postcss'
|
|
26
|
+
|
|
27
|
+
// A selector's leading page-root token, if any. `(?![\w-])` keeps `body` from
|
|
28
|
+
// matching an unrelated tag/class prefix like `bodycopy`.
|
|
29
|
+
const PAGE_ROOT_RE = /^(:root|:host|html|body)(?![\w-])/
|
|
30
|
+
|
|
31
|
+
function insideKeyframes(parent: Container | Document | undefined): boolean {
|
|
32
|
+
return parent?.type === 'atrule' && /keyframes$/i.test((parent as { name: string }).name)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function scopeAppletCss(css: string, scope: string): string {
|
|
36
|
+
const container = `[data-applet=${JSON.stringify(scope)}]`
|
|
37
|
+
const root = postcss.parse(css)
|
|
38
|
+
|
|
39
|
+
root.walkRules(rule => {
|
|
40
|
+
if (insideKeyframes(rule.parent)) return
|
|
41
|
+
rule.selectors = rule.selectors.map(selector => {
|
|
42
|
+
const s = selector.trim()
|
|
43
|
+
const rootToken = PAGE_ROOT_RE.exec(s)
|
|
44
|
+
if (rootToken) return container + s.slice(rootToken[0].length)
|
|
45
|
+
return `${container} ${s}`
|
|
46
|
+
})
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
return root.toString()
|
|
50
|
+
}
|