moi-computer 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/LICENSE +95 -0
  2. package/README.md +71 -0
  3. package/bin/moi.mjs +25 -0
  4. package/bunfig.toml +3 -0
  5. package/client/CLAUDE.md +12 -0
  6. package/client/api/workspaces.ts +158 -0
  7. package/client/assets/claude.svg +3 -0
  8. package/client/assets/favicon.png +0 -0
  9. package/client/assets/hermes-nous.png +0 -0
  10. package/client/assets/mcp/.gitkeep +0 -0
  11. package/client/assets/mcp/atlassian.png +0 -0
  12. package/client/assets/mcp/discord.png +0 -0
  13. package/client/assets/mcp/figma.png +0 -0
  14. package/client/assets/mcp/github.png +0 -0
  15. package/client/assets/mcp/gitlab.png +0 -0
  16. package/client/assets/mcp/granola.png +0 -0
  17. package/client/assets/mcp/hubspot.png +0 -0
  18. package/client/assets/mcp/linear.png +0 -0
  19. package/client/assets/mcp/neon.png +0 -0
  20. package/client/assets/mcp/notion.png +0 -0
  21. package/client/assets/mcp/sentry.png +0 -0
  22. package/client/assets/mcp/slack.png +0 -0
  23. package/client/assets/mcp/stripe.png +0 -0
  24. package/client/assets/mcp/supabase.png +0 -0
  25. package/client/assets/mcp/vercel.png +0 -0
  26. package/client/assets/moi-logo.svg +11 -0
  27. package/client/assets/openclaw.svg +22 -0
  28. package/client/components/App.tsx +35 -0
  29. package/client/components/BottomPanel.tsx +33 -0
  30. package/client/components/ChatInput.tsx +62 -0
  31. package/client/components/ChatPanel.tsx +206 -0
  32. package/client/components/ChatPopup.tsx +60 -0
  33. package/client/components/CustomizePanel.tsx +117 -0
  34. package/client/components/HiddenPanel.tsx +79 -0
  35. package/client/components/HomePage.tsx +17 -0
  36. package/client/components/MarkdownContent.tsx +41 -0
  37. package/client/components/ThreadSelector.tsx +88 -0
  38. package/client/components/TurnView.tsx +618 -0
  39. package/client/components/WidgetErrorBoundary.tsx +46 -0
  40. package/client/components/WidgetFrame.tsx +66 -0
  41. package/client/components/WidgetGrid.tsx +113 -0
  42. package/client/components/WidgetShell.tsx +44 -0
  43. package/client/components/Widgets.tsx +132 -0
  44. package/client/components/WorkspacePreview.tsx +48 -0
  45. package/client/components/WorkspacesPage.tsx +237 -0
  46. package/client/components/layout/SidebarLayout.tsx +260 -0
  47. package/client/components/playground/LedLogo.tsx +181 -0
  48. package/client/components/playground/PixelPainter.tsx +105 -0
  49. package/client/components/playground/PlaygroundPage.tsx +71 -0
  50. package/client/components/routes/workspace/[id].tsx +282 -0
  51. package/client/components/ui/button.tsx +48 -0
  52. package/client/components/ui/dropdown-menu.tsx +257 -0
  53. package/client/components/ui/input.tsx +21 -0
  54. package/client/components/ui/popover.tsx +79 -0
  55. package/client/components/ui/textarea.tsx +18 -0
  56. package/client/externalize-react.ts +29 -0
  57. package/client/hooks/useChat.ts +88 -0
  58. package/client/hooks/useFitsSidebar.ts +34 -0
  59. package/client/hooks/useGridReconcile.ts +73 -0
  60. package/client/hooks/useMeiEvents.ts +66 -0
  61. package/client/hooks/useScrollFade.ts +38 -0
  62. package/client/hooks/useWidget.ts +72 -0
  63. package/client/hooks/useWidgetList.ts +30 -0
  64. package/client/hooks/useWorkspaceTheme.ts +76 -0
  65. package/client/index.css +182 -0
  66. package/client/index.html +43 -0
  67. package/client/index.tsx +19 -0
  68. package/client/lib/WorkspaceContext.tsx +24 -0
  69. package/client/lib/WorkspaceLayoutContext.tsx +92 -0
  70. package/client/lib/cn.ts +6 -0
  71. package/client/lib/grid-pack.ts +35 -0
  72. package/client/lib/group-turns.ts +44 -0
  73. package/client/lib/mcp-icons.ts +53 -0
  74. package/client/lib/ws.ts +129 -0
  75. package/client/main.tsx +23 -0
  76. package/client/store/chat.tsx +162 -0
  77. package/client/store/ui.ts +21 -0
  78. package/client/theme.css +66 -0
  79. package/lib/claude-adapter.ts +602 -0
  80. package/lib/format.ts +212 -0
  81. package/lib/themes.ts +89 -0
  82. package/lib/types.ts +144 -0
  83. package/package.json +117 -0
  84. package/server/CLAUDE.md +6 -0
  85. package/server/agent.ts +132 -0
  86. package/server/build-widget.ts +343 -0
  87. package/server/cli.ts +632 -0
  88. package/server/constants.ts +3 -0
  89. package/server/control.ts +98 -0
  90. package/server/functions-worker.ts +89 -0
  91. package/server/functions.ts +171 -0
  92. package/server/layout.ts +83 -0
  93. package/server/openclaw-adapter.ts +242 -0
  94. package/server/openclaw-gateway.ts +255 -0
  95. package/server/openclaw-session.ts +485 -0
  96. package/server/openclaw-strip.ts +134 -0
  97. package/server/openclaw.ts +206 -0
  98. package/server/registry.ts +150 -0
  99. package/server/skills-template.ts +21 -0
  100. package/server/state.ts +87 -0
  101. package/server/theme.ts +55 -0
  102. package/server/web.ts +321 -0
  103. package/server/widgets.ts +254 -0
  104. package/tsconfig.json +21 -0
  105. package/workspace/.claude/skills/widgets/DESIGN.md +630 -0
  106. package/workspace/.claude/skills/widgets/SKILL.md +176 -0
@@ -0,0 +1,206 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { homedir } from 'node:os'
3
+ import { join, resolve } from 'node:path'
4
+
5
+ export type OpenClawAgent = {
6
+ path: string
7
+ agentId: string
8
+ name?: string
9
+ isDefault: boolean
10
+ lastRunAt?: string
11
+ }
12
+
13
+ // Subset of the session row returned by `sessions.list`. The gateway ships
14
+ // more fields, but these are the ones we map to our SessionInfo/StreamEvent.
15
+ export type OpenClawSessionRow = {
16
+ key: string
17
+ sessionId: string
18
+ updatedAt: number
19
+ lastMessagePreview?: string
20
+ displayName?: string
21
+ label?: string
22
+ model?: string
23
+ modelProvider?: string
24
+ status?: string
25
+ }
26
+
27
+ // Shape returned by `sessions.get({ key })` — the full transcript, unlike
28
+ // `sessions.preview` which is capped at ~11 items regardless of maxChars.
29
+ export type OpenClawContentBlock =
30
+ | { type: 'text'; text: string; textSignature?: string }
31
+ | { type: 'thinking'; thinking: string; thinkingSignature?: string }
32
+ | { type: 'toolCall'; id: string; name: string; arguments: unknown }
33
+ | { type: string; [k: string]: unknown }
34
+
35
+ export type OpenClawMessage = {
36
+ role: 'user' | 'assistant' | 'toolResult' | string
37
+ content: OpenClawContentBlock[] | string
38
+ timestamp?: number
39
+ __openclaw?: { id?: string; seq?: number }
40
+ }
41
+
42
+ export type OpenClawSessionDetail = {
43
+ messages: OpenClawMessage[]
44
+ }
45
+
46
+ const TIMEOUT_MS = 2000
47
+
48
+ type AgentsList = {
49
+ defaultId: string
50
+ agents: Array<{ id: string; workspace: string }>
51
+ }
52
+ type SessionsList = {
53
+ sessions: Array<{ key: string; updatedAt: number }>
54
+ }
55
+ type FileGet = { file?: { content?: string } }
56
+
57
+ function withTimeout<T>(p: Promise<T>, ms: number, label: string): Promise<T> {
58
+ return new Promise<T>((res, rej) => {
59
+ const t = setTimeout(() => rej(new Error(`openclaw ${label} timed out after ${ms}ms`)), ms)
60
+ p.then(
61
+ v => {
62
+ clearTimeout(t)
63
+ res(v)
64
+ },
65
+ e => {
66
+ clearTimeout(t)
67
+ rej(e)
68
+ }
69
+ )
70
+ })
71
+ }
72
+
73
+ function parseIdentityName(md: string | undefined): string | undefined {
74
+ if (!md) return undefined
75
+ const m = /^-\s*\*\*Name:\*\*\s*(.+)$/m.exec(md)
76
+ return m ? m[1].trim() : undefined
77
+ }
78
+
79
+ type Rpc = <T>(method: string, params?: Record<string, unknown>) => Promise<T>
80
+
81
+ // Connect, hand the scoped `rpc(method, params)` to `fn`, then stop the client.
82
+ // Any connect/auth/timeout failure → returns `null` silently (caller's choice).
83
+ async function withGatewayClient<T>(fn: (rpc: Rpc) => Promise<T>): Promise<T | null> {
84
+ let cfg: { gateway?: { port?: number; auth?: { token?: string } } }
85
+ try {
86
+ const raw = await readFile(join(homedir(), '.openclaw/openclaw.json'), 'utf8')
87
+ cfg = JSON.parse(raw)
88
+ } catch {
89
+ return null
90
+ }
91
+ const port = cfg.gateway?.port
92
+ const token = cfg.gateway?.auth?.token
93
+ if (!port || !token) return null
94
+
95
+ let GatewayClient: typeof import('openclaw/plugin-sdk/gateway-runtime').GatewayClient
96
+ try {
97
+ ;({ GatewayClient } = await import('openclaw/plugin-sdk/gateway-runtime'))
98
+ } catch {
99
+ return null
100
+ }
101
+
102
+ const client = new GatewayClient({
103
+ url: `ws://127.0.0.1:${port}`,
104
+ token,
105
+ role: 'operator',
106
+ scopes: ['operator.admin', 'operator.read', 'operator.write'],
107
+ requestTimeoutMs: TIMEOUT_MS
108
+ })
109
+
110
+ const connect = new Promise<void>((res, rej) => {
111
+ client.opts.onHelloOk = () => res()
112
+ client.opts.onConnectError = rej
113
+ })
114
+
115
+ try {
116
+ client.start()
117
+ await withTimeout(connect, TIMEOUT_MS, 'connect')
118
+ const rpc: Rpc = (method, params = {}) =>
119
+ withTimeout(client.request(method, params), TIMEOUT_MS, method)
120
+ return await fn(rpc)
121
+ } catch {
122
+ return null
123
+ } finally {
124
+ client.stop()
125
+ }
126
+ }
127
+
128
+ export async function discoverOpenClawAgents(): Promise<OpenClawAgent[]> {
129
+ const out = await withGatewayClient(async rpc => {
130
+ const [agents, sessions] = await Promise.all([
131
+ rpc<AgentsList>('agents.list'),
132
+ rpc<SessionsList>('sessions.list', { includeGlobal: true })
133
+ ])
134
+
135
+ const identities = await Promise.all(
136
+ agents.agents.map(a =>
137
+ rpc<FileGet>('agents.files.get', { agentId: a.id, name: 'IDENTITY.md' }).catch(() => null)
138
+ )
139
+ )
140
+
141
+ const lastRun = new Map<string, number>()
142
+ for (const s of sessions.sessions) {
143
+ const m = /^agent:([^:]+):/.exec(s.key)
144
+ if (!m) continue
145
+ const cur = lastRun.get(m[1]) ?? 0
146
+ if (s.updatedAt > cur) lastRun.set(m[1], s.updatedAt)
147
+ }
148
+
149
+ return agents.agents.map((a, i) => {
150
+ const ts = lastRun.get(a.id)
151
+ return {
152
+ path: resolve(a.workspace),
153
+ agentId: a.id,
154
+ name: parseIdentityName(identities[i]?.file?.content),
155
+ isDefault: a.id === agents.defaultId,
156
+ lastRunAt: ts ? new Date(ts).toISOString() : undefined
157
+ }
158
+ })
159
+ })
160
+ return out ?? []
161
+ }
162
+
163
+ // Resolve an OpenClaw agentId for a workspace path. Used when the saved
164
+ // workspace entry was registered before we started capturing agentId.
165
+ async function resolveAgentIdForPath(rpc: Rpc, path: string): Promise<string | undefined> {
166
+ const agents = await rpc<AgentsList>('agents.list')
167
+ return agents.agents.find(a => resolve(a.workspace) === resolve(path))?.id
168
+ }
169
+
170
+ export async function getOpenClawSessions(
171
+ workspacePath: string,
172
+ agentId?: string
173
+ ): Promise<OpenClawSessionRow[]> {
174
+ const out = await withGatewayClient(async rpc => {
175
+ const id = agentId ?? (await resolveAgentIdForPath(rpc, workspacePath))
176
+ if (!id) return []
177
+ const res = await rpc<{ sessions: OpenClawSessionRow[] }>('sessions.list', {
178
+ agentId: id,
179
+ includeLastMessage: true
180
+ })
181
+ return res.sessions
182
+ })
183
+ return out ?? []
184
+ }
185
+
186
+ export async function getOpenClawSessionMessages(
187
+ sessionId: string,
188
+ workspacePath: string,
189
+ agentId?: string
190
+ ): Promise<OpenClawSessionDetail | null> {
191
+ const out = await withGatewayClient(async rpc => {
192
+ const id = agentId ?? (await resolveAgentIdForPath(rpc, workspacePath))
193
+ if (!id) return null
194
+
195
+ // sessionId → key. `sessions.get` needs the composite key, not sessionId.
196
+ const resolved = await rpc<{ key?: string }>('sessions.resolve', {
197
+ sessionId,
198
+ agentId: id
199
+ }).catch(() => null)
200
+ const key = resolved?.key
201
+ if (!key) return null
202
+
203
+ return await rpc<OpenClawSessionDetail>('sessions.get', { key })
204
+ })
205
+ return out ?? null
206
+ }
@@ -0,0 +1,150 @@
1
+ import envPaths from 'env-paths'
2
+ import { mkdir } from 'node:fs/promises'
3
+ import { homedir } from 'node:os'
4
+ import { join, resolve } from 'path'
5
+
6
+ import type { DiscoveredWorkspace, WorkspaceEntry, WorkspaceType } from '@/lib/types'
7
+
8
+ import { type OpenClawAgent, discoverOpenClawAgents } from './openclaw'
9
+
10
+ // Replace the home-dir prefix with `~` for display. Keeps the original
11
+ // absolute path in place; callers should put the result in `displayPath`.
12
+ function tildify(absPath: string): string {
13
+ const home = homedir()
14
+ if (!home) return absPath
15
+ if (absPath === home) return '~'
16
+ const prefix = home.endsWith('/') ? home : home + '/'
17
+ if (absPath.startsWith(prefix)) return '~/' + absPath.slice(prefix.length)
18
+ return absPath
19
+ }
20
+
21
+ function withDisplayPath<T extends { path: string }>(entry: T): T & { displayPath: string } {
22
+ return { ...entry, displayPath: tildify(entry.path) }
23
+ }
24
+
25
+ const DATA_DIR = envPaths('moi', { suffix: false }).data
26
+ export const DEFAULT_REGISTRY_PATH = join(DATA_DIR, 'workspaces.json')
27
+
28
+ // Overridable for tests
29
+ let _registryPath = DEFAULT_REGISTRY_PATH
30
+ export function setRegistryPath(p: string) {
31
+ _registryPath = p
32
+ }
33
+
34
+ async function readRegistry(): Promise<WorkspaceEntry[]> {
35
+ try {
36
+ const text = await Bun.file(_registryPath).text()
37
+ return JSON.parse(text) as WorkspaceEntry[]
38
+ } catch {
39
+ return []
40
+ }
41
+ }
42
+
43
+ async function writeRegistry(entries: WorkspaceEntry[]): Promise<void> {
44
+ await mkdir(join(_registryPath, '..'), { recursive: true })
45
+ await Bun.write(_registryPath, JSON.stringify(entries, null, 2))
46
+ }
47
+
48
+ export type RegisterOptions = {
49
+ type?: WorkspaceType
50
+ name?: string
51
+ agentId?: string
52
+ isDefault?: boolean
53
+ lastRunAt?: string
54
+ }
55
+
56
+ export async function registerWorkspace(
57
+ absPath: string,
58
+ opts: RegisterOptions = {}
59
+ ): Promise<WorkspaceEntry> {
60
+ const normalPath = resolve(absPath)
61
+ const entries = await readRegistry()
62
+ const existing = entries.find(e => e.path === normalPath)
63
+ if (existing) return existing
64
+ const entry: WorkspaceEntry = {
65
+ id: crypto.randomUUID(),
66
+ path: normalPath,
67
+ addedAt: new Date().toISOString(),
68
+ ...(opts.type ? { type: opts.type } : {}),
69
+ ...(opts.name ? { name: opts.name } : {}),
70
+ ...(opts.agentId ? { agentId: opts.agentId } : {}),
71
+ ...(opts.isDefault ? { isDefault: opts.isDefault } : {}),
72
+ ...(opts.lastRunAt ? { lastRunAt: opts.lastRunAt } : {})
73
+ }
74
+ await writeRegistry([...entries, entry])
75
+ return withDisplayPath(entry)
76
+ }
77
+
78
+ export async function getWorkspace(id: string): Promise<WorkspaceEntry | null> {
79
+ const entries = await readRegistry()
80
+ return entries.find(e => e.id === id) ?? null
81
+ }
82
+
83
+ export async function removeWorkspace(id: string): Promise<boolean> {
84
+ const entries = await readRegistry()
85
+ const next = entries.filter(e => e.id !== id)
86
+ if (next.length === entries.length) return false
87
+ await writeRegistry(next)
88
+ return true
89
+ }
90
+
91
+ export async function listWorkspaces(): Promise<WorkspaceEntry[]> {
92
+ const entries = await readRegistry()
93
+ return entries.map(withDisplayPath)
94
+ }
95
+
96
+ // Discover CC-active directories not yet in the registry
97
+ async function discoverFromCC(registeredPaths: Set<string>): Promise<string[]> {
98
+ try {
99
+ const { listSessions } = await import('@anthropic-ai/claude-agent-sdk')
100
+ const sessions = await listSessions({})
101
+ const { stat } = await import('node:fs/promises')
102
+ const paths = new Set<string>()
103
+
104
+ for (const s of sessions) {
105
+ if (!s.cwd || registeredPaths.has(s.cwd)) continue
106
+ try {
107
+ const info = await stat(s.cwd)
108
+ if (info.isDirectory()) paths.add(s.cwd)
109
+ } catch {}
110
+ }
111
+
112
+ return [...paths]
113
+ } catch {
114
+ return []
115
+ }
116
+ }
117
+
118
+ // Discover OpenClaw agents via the gateway WebSocket (2s timeout). Returns []
119
+ // if the gateway is unreachable, auth is missing, or probes time out.
120
+ async function discoverFromOpenClaw(registeredPaths: Set<string>): Promise<OpenClawAgent[]> {
121
+ const agents = await discoverOpenClawAgents()
122
+ return agents.filter(a => !registeredPaths.has(a.path))
123
+ }
124
+
125
+ export async function discoverWorkspaces(): Promise<DiscoveredWorkspace[]> {
126
+ const registeredPaths = new Set((await readRegistry()).map(e => e.path))
127
+ const [ccPaths, openclawAgents] = await Promise.all([
128
+ discoverFromCC(registeredPaths),
129
+ discoverFromOpenClaw(registeredPaths)
130
+ ])
131
+ const openclawByPath = new Map(openclawAgents.map(a => [a.path, a]))
132
+ const out: DiscoveredWorkspace[] = []
133
+ for (const a of openclawAgents) {
134
+ out.push(
135
+ withDisplayPath({
136
+ path: a.path,
137
+ type: 'openclaw',
138
+ ...(a.name ? { name: a.name } : {}),
139
+ ...(a.agentId ? { agentId: a.agentId } : {}),
140
+ ...(a.isDefault ? { isDefault: a.isDefault } : {}),
141
+ ...(a.lastRunAt ? { lastRunAt: a.lastRunAt } : {})
142
+ })
143
+ )
144
+ }
145
+ for (const p of ccPaths) {
146
+ if (openclawByPath.has(p)) continue
147
+ out.push(withDisplayPath({ path: p, type: 'claude-code' }))
148
+ }
149
+ return out
150
+ }
@@ -0,0 +1,21 @@
1
+ // Skills the project ships, copied into a target workspace by `moi init`
2
+ // (Claude Code workspace) and `moi openclaw init <agent>` (OpenClaw agent
3
+ // workspace). Both commands take a fresh or existing directory and lay
4
+ // down the same set of skill folders.
5
+ import { cp, mkdir } from 'node:fs/promises'
6
+ import { join } from 'node:path'
7
+
8
+ // Source directory for shipped templates. Resolved relative to this file so
9
+ // symlinked CLI binaries still find the source tree.
10
+ export const TEMPLATE_DIR = join(import.meta.dir, '..', 'workspace')
11
+
12
+ // Copy each shipped skill folder into `targetSkillsDir`. Overwrites existing
13
+ // files (e.g. on a re-install after a moi upgrade) but leaves unrelated
14
+ // directories alone. Creates the target if missing.
15
+ export async function installBundledSkills(targetSkillsDir: string): Promise<void> {
16
+ await mkdir(targetSkillsDir, { recursive: true })
17
+ await cp(join(TEMPLATE_DIR, '.claude', 'skills'), targetSkillsDir, {
18
+ recursive: true,
19
+ force: true
20
+ })
21
+ }
@@ -0,0 +1,87 @@
1
+ import { getSessionMessages, listSessions } from '@anthropic-ai/claude-agent-sdk'
2
+
3
+ import { ClaudeAdapter } from '@/lib/claude-adapter'
4
+ import type { ServerMessage, SessionInfo, StreamEvent } from '@/lib/types'
5
+
6
+ // Per-workspace connected chat clients
7
+ const clientsByWorkspace = new Map<string, Set<Bun.ServerWebSocket<unknown>>>()
8
+
9
+ export function addClient(workspaceId: string, ws: Bun.ServerWebSocket<unknown>) {
10
+ if (!clientsByWorkspace.has(workspaceId)) clientsByWorkspace.set(workspaceId, new Set())
11
+ clientsByWorkspace.get(workspaceId)!.add(ws)
12
+ }
13
+
14
+ export function removeClient(workspaceId: string, ws: Bun.ServerWebSocket<unknown>) {
15
+ clientsByWorkspace.get(workspaceId)?.delete(ws)
16
+ }
17
+
18
+ // Per-session agent state — the ONLY mutable state
19
+ type Agent = { processing: boolean; abortController: AbortController | null }
20
+ const agents = new Map<string, Agent>()
21
+
22
+ export function getAgent(id: string): Agent {
23
+ if (!agents.has(id)) agents.set(id, { processing: false, abortController: null })
24
+ return agents.get(id)!
25
+ }
26
+
27
+ export function renameAgent(from: string, to: string) {
28
+ const a = agents.get(from)
29
+ if (!a) return
30
+ agents.set(to, a)
31
+ agents.delete(from)
32
+ }
33
+
34
+ export function getProcessingSessions(workspaceId: string): string[] {
35
+ void workspaceId
36
+ const result: string[] = []
37
+ for (const [id, a] of agents) if (a.processing) result.push(id)
38
+ return result
39
+ }
40
+
41
+ export function broadcast(workspaceId: string, msg: ServerMessage) {
42
+ const json = JSON.stringify(msg)
43
+ for (const ws of clientsByWorkspace.get(workspaceId) ?? []) ws.send(json)
44
+ }
45
+
46
+ export function broadcastAll(msg: ServerMessage) {
47
+ const json = JSON.stringify(msg)
48
+ for (const clients of clientsByWorkspace.values()) {
49
+ for (const ws of clients) ws.send(json)
50
+ }
51
+ }
52
+
53
+ export function sendToClient(ws: Bun.ServerWebSocket<unknown>, msg: ServerMessage) {
54
+ ws.send(JSON.stringify(msg))
55
+ }
56
+
57
+ export async function getSessions(workspacePath: string): Promise<SessionInfo[]> {
58
+ const sessions = await listSessions({ dir: workspacePath })
59
+ return sessions.map(s => ({
60
+ sessionId: s.sessionId,
61
+ summary: s.summary,
62
+ lastModified: s.lastModified,
63
+ cwd: s.cwd
64
+ }))
65
+ }
66
+
67
+ /**
68
+ * Replay a session's persisted raw messages through a fresh adapter and
69
+ * return the resulting StreamEvents. Events are carefully NOT deduplicated —
70
+ * the client reducer is idempotent under upsert-by-id.
71
+ */
72
+ export async function getSessionEvents(
73
+ sessionId: string,
74
+ workspacePath: string
75
+ ): Promise<StreamEvent[]> {
76
+ const adapter = new ClaudeAdapter()
77
+ const events: StreamEvent[] = []
78
+ try {
79
+ const raw = await getSessionMessages(sessionId, { dir: workspacePath })
80
+ for (const msg of raw) {
81
+ for (const ev of adapter.ingest(msg)) events.push(ev)
82
+ }
83
+ } catch {
84
+ // session file missing or unreadable — return whatever we have (often [])
85
+ }
86
+ return events
87
+ }
@@ -0,0 +1,55 @@
1
+ import { COLOR_THEMES, FONT_THEMES } from '@/lib/themes'
2
+ import type { ColorTheme, FontTheme, WorkspaceLayout } from '@/lib/types'
3
+
4
+ type ThemeShape = NonNullable<WorkspaceLayout['theme']>
5
+
6
+ export type ThemeUpdate = { font?: string; color?: string }
7
+ export type ThemeUpdateResult =
8
+ | { ok: true; theme: ThemeShape; applied: { font?: FontTheme; color?: ColorTheme } }
9
+ | { ok: false; error: string }
10
+
11
+ // Pure merge + validation for a theme update. Spreads the existing theme so
12
+ // setting one axis never wipes the other. 'default' color is stored as
13
+ // `undefined` bg/fg, which JSON.stringify drops on save.
14
+ export function applyThemeUpdate(
15
+ current: WorkspaceLayout['theme'],
16
+ update: ThemeUpdate
17
+ ): ThemeUpdateResult {
18
+ if (update.font && !(update.font in FONT_THEMES)) {
19
+ return { ok: false, error: `Unknown font theme: ${update.font}` }
20
+ }
21
+ if (update.color && !(update.color in COLOR_THEMES)) {
22
+ return { ok: false, error: `Unknown color theme: ${update.color}` }
23
+ }
24
+
25
+ const theme: ThemeShape = {
26
+ ...current,
27
+ font: (update.font as FontTheme) ?? current?.font ?? 'default'
28
+ }
29
+
30
+ if (update.color) {
31
+ const preset = COLOR_THEMES[update.color as ColorTheme]
32
+ theme.background = preset.background
33
+ theme.foreground = preset.foreground
34
+ }
35
+
36
+ return {
37
+ ok: true,
38
+ theme,
39
+ applied: {
40
+ ...(update.font ? { font: update.font as FontTheme } : {}),
41
+ ...(update.color ? { color: update.color as ColorTheme } : {})
42
+ }
43
+ }
44
+ }
45
+
46
+ // Reverse-lookup: resolve stored bg/fg to a preset key, or null for custom colors.
47
+ export function matchColorTheme(bg: string | undefined, fg: string | undefined): ColorTheme | null {
48
+ for (const [key, preset] of Object.entries(COLOR_THEMES) as [
49
+ ColorTheme,
50
+ (typeof COLOR_THEMES)[ColorTheme]
51
+ ][]) {
52
+ if (preset.background === bg && preset.foreground === fg) return key
53
+ }
54
+ return null
55
+ }