@myrialabs/clopen 0.4.46 → 0.4.48
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 +11 -11
- package/backend/artifacts/project/sources.ts +1 -1
- package/backend/auth/auth-service.ts +52 -358
- package/backend/auth/onboarding.test.ts +2 -3
- package/backend/auth/permissions.test.ts +10 -20
- package/backend/auth/permissions.ts +4 -290
- package/backend/auth/rate-limiter.test.ts +8 -9
- package/backend/auth/rate-limiter.ts +0 -2
- package/backend/auth/tokens.ts +1 -8
- package/backend/bootstrap.ts +7 -0
- package/backend/chat/attachments.test.ts +88 -0
- package/backend/chat/attachments.ts +159 -0
- package/backend/chat/engine-handoff.test.ts +0 -2
- package/backend/chat/stream-manager.ts +62 -62
- package/backend/chat/turn-answer.test.ts +64 -0
- package/backend/chat/turn-answer.ts +125 -0
- package/backend/chat-apps/awaiting.test.ts +39 -0
- package/backend/chat-apps/awaiting.ts +49 -0
- package/backend/chat-apps/conversation.ts +746 -0
- package/backend/chat-apps/inbound.ts +324 -0
- package/backend/chat-apps/index.ts +309 -0
- package/backend/chat-apps/link-events.ts +20 -0
- package/backend/chat-apps/media.test.ts +62 -0
- package/backend/chat-apps/media.ts +208 -0
- package/backend/chat-apps/messages.test.ts +229 -0
- package/backend/chat-apps/messages.ts +365 -0
- package/backend/chat-apps/outbound.ts +243 -0
- package/backend/chat-apps/pairing.test.ts +45 -0
- package/backend/chat-apps/pairing.ts +74 -0
- package/backend/chat-apps/platforms/index.ts +20 -0
- package/backend/chat-apps/platforms/telegram.test.ts +35 -0
- package/backend/chat-apps/platforms/telegram.ts +191 -0
- package/backend/chat-apps/platforms/types.ts +114 -0
- package/backend/chat-apps/questions.ts +133 -0
- package/backend/chat-apps/runtime.ts +572 -0
- package/backend/chat-apps/storage.test.ts +201 -0
- package/backend/chat-apps/turns.test.ts +45 -0
- package/backend/chat-apps/turns.ts +208 -0
- package/backend/containers/pty.ts +3 -11
- package/backend/control/actions/accounts.ts +89 -0
- package/backend/control/actions/files.ts +116 -0
- package/backend/control/actions/models.ts +188 -0
- package/backend/control/actions/projects.ts +272 -0
- package/backend/control/actions/sessions.ts +280 -0
- package/backend/control/actions/skills.ts +111 -0
- package/backend/control/control.test.ts +169 -0
- package/backend/control/define.ts +20 -0
- package/backend/control/folders.test.ts +67 -0
- package/backend/control/index.ts +213 -0
- package/backend/control/invoke.ts +44 -0
- package/backend/control/links.ts +35 -0
- package/backend/control/paging.ts +26 -0
- package/backend/control/types.ts +117 -0
- package/backend/control/workspace.ts +127 -0
- package/backend/database/migrations/084_create_channel_links.ts +71 -0
- package/backend/database/migrations/085_add_home_projects.ts +36 -0
- package/backend/database/migrations/086_single_owner.test.ts +170 -0
- package/backend/database/migrations/086_single_owner.ts +418 -0
- package/backend/database/migrations/index.ts +21 -0
- package/backend/database/queries/auth-queries.ts +7 -85
- package/backend/database/queries/channel-queries.ts +270 -0
- package/backend/database/queries/db-client-connection-queries.ts +18 -56
- package/backend/database/queries/file-share-queries.ts +5 -23
- package/backend/database/queries/git-identity-queries.ts +31 -42
- package/backend/database/queries/graph-queries.ts +1 -1
- package/backend/database/queries/index.ts +13 -1
- package/backend/database/queries/message-queries.test.ts +146 -0
- package/backend/database/queries/message-queries.ts +42 -1
- package/backend/database/queries/permission-set-queries.ts +1 -1
- package/backend/database/queries/profile-queries.ts +1 -1
- package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
- package/backend/database/queries/project-queries.ts +50 -63
- package/backend/database/queries/session-queries.ts +28 -56
- package/backend/database/queries/ssh-connection-queries.ts +18 -41
- package/backend/db-client/integrations/projector.ts +0 -5
- package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
- package/backend/engine/adapters/claude/message-converter.ts +25 -2
- package/backend/engine/adapters/cline/message-converter.ts +0 -1
- package/backend/engine/adapters/cline/stream.ts +11 -15
- package/backend/engine/adapters/codex/message-converter.ts +0 -2
- package/backend/engine/adapters/copilot/message-converter.ts +1 -2
- package/backend/engine/adapters/cursor/message-converter.ts +0 -1
- package/backend/engine/adapters/opencode/message-converter.ts +2 -4
- package/backend/engine/adapters/opencode/presets.ts +27 -2
- package/backend/engine/adapters/opencode/server.ts +6 -4
- package/backend/engine/adapters/opencode/stream.ts +11 -0
- package/backend/engine/adapters/parent-scope.test.ts +38 -0
- package/backend/engine/adapters/parent-scope.ts +44 -0
- package/backend/engine/adapters/pi/message-converter.ts +0 -1
- package/backend/engine/adapters/pi/stream.ts +4 -5
- package/backend/engine/adapters/qwen/message-converter.ts +0 -2
- package/backend/engine/bootstrap-default-engine.ts +2 -2
- package/backend/engine/docs/adapter-contract.md +8 -1
- package/backend/engine/install-runner.ts +8 -17
- package/backend/files/file-shares.ts +20 -44
- package/backend/files/file-size-limit.ts +3 -3
- package/backend/files/image-processing.ts +1 -1
- package/backend/files/os-clipboard.ts +2 -2
- package/backend/git/git-executor.ts +25 -5
- package/backend/git/git-service.ts +420 -19
- package/backend/git/identity/credential-helper.test.ts +2 -7
- package/backend/git/identity/import-local.test.ts +11 -16
- package/backend/git/identity/import-local.ts +12 -12
- package/backend/git/identity/index.ts +10 -24
- package/backend/git/identity/resolve.ts +13 -14
- package/backend/git/identity/scope-config.ts +33 -28
- package/backend/git/identity/service.ts +44 -47
- package/backend/git/op-lock.test.ts +111 -0
- package/backend/git/op-lock.ts +180 -0
- package/backend/git/remote-sync.test.ts +249 -0
- package/backend/host/metrics.ts +1 -1
- package/backend/http/bearer-auth.ts +1 -2
- package/backend/http/files-download.test.ts +8 -9
- package/backend/http/files-download.ts +2 -2
- package/backend/http/files-shared.test.ts +62 -89
- package/backend/http/files-shared.ts +2 -2
- package/backend/http/files-upload.test.ts +3 -7
- package/backend/http/files-upload.ts +3 -3
- package/backend/http/notes-images.test.ts +15 -38
- package/backend/http/notes-images.ts +6 -8
- package/backend/http/ssh-sftp.ts +5 -10
- package/backend/index.ts +21 -7
- package/backend/integrations/accounts.ts +61 -3
- package/backend/integrations/index.ts +2 -2
- package/backend/integrations/registry/define.ts +15 -0
- package/backend/integrations/registry/index.ts +2 -0
- package/backend/integrations/registry/providers/telegram.ts +54 -0
- package/backend/integrations/registry/types.ts +21 -1
- package/backend/integrations/webhooks/gateway.ts +7 -6
- package/backend/integrations/webhooks/verify.test.ts +30 -0
- package/backend/integrations/webhooks/verify.ts +4 -0
- package/backend/mcp/external/project.ts +1 -1
- package/backend/mcp/internal/remote-server.test.ts +1 -3
- package/backend/mcp/internal/remote-server.ts +4 -4
- package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
- package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
- package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
- package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
- package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
- package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
- package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
- package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
- package/backend/memory/redact.ts +1 -1
- package/backend/notes/access.test.ts +28 -29
- package/backend/notes/access.ts +6 -11
- package/backend/permissions/service.ts +1 -1
- package/backend/preview/browser/browser-clipboard.test.ts +46 -0
- package/backend/preview/browser/browser-clipboard.ts +67 -0
- package/backend/preview/browser/browser-dialog-handler.ts +95 -6
- package/backend/preview/browser/browser-host-bridge.ts +9 -0
- package/backend/preview/browser/browser-interaction-handler.ts +316 -86
- package/backend/preview/browser/browser-mcp-control.ts +34 -0
- package/backend/preview/browser/browser-pool.ts +67 -6
- package/backend/preview/browser/browser-preview-service.ts +361 -25
- package/backend/preview/browser/browser-tab-manager.ts +66 -23
- package/backend/preview/browser/browser-video-capture.ts +92 -5
- package/backend/preview/browser/element-locator.ts +190 -17
- package/backend/preview/browser/keyboard-chords.test.ts +68 -0
- package/backend/preview/browser/keyboard-chords.ts +132 -0
- package/backend/preview/browser/paste.ts +81 -0
- package/backend/preview/browser/process-usage.ts +142 -0
- package/backend/preview/browser/profile-lock.ts +209 -0
- package/backend/preview/browser/scripts/host-bridge.ts +59 -0
- package/backend/preview/browser/scripts/video-stream.ts +58 -0
- package/backend/preview/browser/types.ts +40 -2
- package/backend/preview/browser/viewport.test.ts +45 -0
- package/backend/preview/browser/viewport.ts +96 -0
- package/backend/profiles/service.ts +2 -2
- package/backend/project/status-manager.ts +43 -172
- package/backend/projects/home.ts +61 -0
- package/backend/projects/project-cleanup.integration.test.ts +2 -2
- package/backend/projects/project-cleanup.ts +0 -8
- package/backend/skills/service.ts +2 -3
- package/backend/snapshot/helpers.ts +0 -1
- package/backend/snapshot/restore.ts +252 -0
- package/backend/ssh/ptykit.ts +1 -2
- package/backend/terminal/ptykit.ts +5 -8
- package/backend/tunnel/public-origin.ts +31 -20
- package/backend/utils/user-helpers.ts +0 -55
- package/backend/utils/ws.ts +61 -154
- package/backend/worktrees/branching/engine.ts +3 -16
- package/backend/worktrees/branching/index.ts +1 -1
- package/backend/worktrees/branching/projector.ts +1 -1
- package/backend/worktrees/branching/service.ts +13 -25
- package/backend/ws/access.ts +12 -21
- package/backend/ws/artifacts/generate.ts +2 -2
- package/backend/ws/auth/device.ts +16 -71
- package/backend/ws/auth/index.ts +4 -22
- package/backend/ws/auth/login.test.ts +14 -60
- package/backend/ws/auth/login.ts +24 -124
- package/backend/ws/auth/status.ts +0 -1
- package/backend/ws/chat/composer.ts +118 -118
- package/backend/ws/chat/stream.ts +64 -47
- package/backend/ws/chat-apps/index.ts +117 -0
- package/backend/ws/containers/actions.ts +11 -25
- package/backend/ws/containers/index.ts +3 -4
- package/backend/ws/containers/list.ts +10 -36
- package/backend/ws/containers/logs.ts +2 -2
- package/backend/ws/containers/tunnel.ts +1 -2
- package/backend/ws/db-client/access.ts +2 -16
- package/backend/ws/db-client/accounts.ts +5 -15
- package/backend/ws/db-client/connections.ts +17 -25
- package/backend/ws/db-client/context.ts +1 -1
- package/backend/ws/db-client/env.ts +7 -10
- package/backend/ws/db-client/index.ts +2 -2
- package/backend/ws/db-client/io.ts +5 -5
- package/backend/ws/db-client/query-history-retention.test.ts +8 -8
- package/backend/ws/db-client/query.ts +18 -17
- package/backend/ws/db-client/schema.ts +13 -13
- package/backend/ws/db-client/structure.ts +35 -35
- package/backend/ws/db-client/supabase.ts +4 -21
- package/backend/ws/deployments/context.ts +1 -1
- package/backend/ws/deployments/crud.ts +0 -5
- package/backend/ws/engine/access.ts +7 -20
- package/backend/ws/engine/claude/accounts.ts +4 -4
- package/backend/ws/engine/cline/accounts.ts +5 -5
- package/backend/ws/engine/codex/accounts.ts +3 -3
- package/backend/ws/engine/opencode/providers.ts +2 -1
- package/backend/ws/engine/pi/accounts.ts +5 -5
- package/backend/ws/files/clipboard.ts +8 -27
- package/backend/ws/files/image-edit.ts +6 -6
- package/backend/ws/files/index.ts +1 -1
- package/backend/ws/files/path-access.test.ts +32 -131
- package/backend/ws/files/path-access.ts +8 -87
- package/backend/ws/files/read.ts +15 -19
- package/backend/ws/files/reveal.ts +3 -3
- package/backend/ws/files/search.ts +7 -7
- package/backend/ws/files/share.ts +9 -13
- package/backend/ws/files/state.ts +9 -12
- package/backend/ws/files/watch.ts +3 -3
- package/backend/ws/files/write.ts +30 -31
- package/backend/ws/git/branch.ts +80 -59
- package/backend/ws/git/commit.ts +63 -44
- package/backend/ws/git/conflict.ts +16 -18
- package/backend/ws/git/identity-context.ts +8 -17
- package/backend/ws/git/identity.ts +17 -27
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/git/op-state.ts +139 -0
- package/backend/ws/git/remote.ts +241 -141
- package/backend/ws/git/repo-context.ts +67 -0
- package/backend/ws/git/staging.ts +18 -28
- package/backend/ws/git/status.ts +5 -2
- package/backend/ws/index.ts +5 -1
- package/backend/ws/instructions/crud.ts +1 -1
- package/backend/ws/integrations/crud.ts +1 -3
- package/backend/ws/mcp/crud.ts +3 -5
- package/backend/ws/mcp/tools.ts +1 -1
- package/backend/ws/memory/crud.ts +14 -46
- package/backend/ws/memory/index.ts +2 -2
- package/backend/ws/messages/crud.ts +29 -8
- package/backend/ws/notes/index.ts +33 -39
- package/backend/ws/permissions/crud.ts +3 -4
- package/backend/ws/ports/index.ts +1 -2
- package/backend/ws/ports/kill.ts +5 -10
- package/backend/ws/ports/list.ts +4 -10
- package/backend/ws/preview/access.ts +1 -1
- package/backend/ws/preview/browser/interact.ts +52 -79
- package/backend/ws/preview/browser/native-ui.ts +24 -0
- package/backend/ws/preview/browser/stats.ts +98 -1
- package/backend/ws/preview/browser/tab-info.ts +15 -0
- package/backend/ws/preview/browser/tab.ts +19 -4
- package/backend/ws/preview/index.ts +27 -0
- package/backend/ws/profiles/crud.ts +6 -8
- package/backend/ws/project-artifacts/index.ts +30 -31
- package/backend/ws/projects/crud.ts +33 -35
- package/backend/ws/projects/index.ts +3 -8
- package/backend/ws/projects/info.ts +3 -3
- package/backend/ws/projects/overview.ts +19 -30
- package/backend/ws/projects/status.ts +17 -57
- package/backend/ws/sessions/crud.ts +34 -45
- package/backend/ws/sessions/index.ts +1 -1
- package/backend/ws/settings/crud.ts +1 -1
- package/backend/ws/skills/crud.ts +3 -4
- package/backend/ws/skills/index.ts +1 -1
- package/backend/ws/snapshot/changes.ts +7 -7
- package/backend/ws/snapshot/restore.ts +11 -295
- package/backend/ws/snapshot/timeline.ts +2 -4
- package/backend/ws/ssh/access.ts +6 -21
- package/backend/ws/ssh/connections.ts +21 -31
- package/backend/ws/ssh/forwards.ts +12 -12
- package/backend/ws/ssh/sftp.ts +34 -34
- package/backend/ws/ssh/tunnel.ts +1 -2
- package/backend/ws/stack/install.ts +7 -17
- package/backend/ws/subagents/crud.ts +1 -1
- package/backend/ws/tunnel/share.ts +0 -2
- package/backend/ws/user/crud.ts +1 -59
- package/backend/ws/user/index.ts +1 -1
- package/backend/ws/work/context.ts +1 -1
- package/backend/ws/work/crud.ts +0 -5
- package/backend/ws/workspace/state.ts +10 -13
- package/backend/ws/worktrees/branching.ts +7 -36
- package/backend/ws/worktrees/crud.ts +2 -2
- package/bin/clopen.ts +10 -11
- package/dist/assets/{index-CwuKQelV.js → index-CONlwAXZ.js} +1 -1
- package/dist/assets/{index-BTcR1byF.js → index-DJzwt-hq.js} +1 -1
- package/dist/assets/main-BUiUL3eZ.css +1 -0
- package/dist/assets/main-nBOb9YOA.js +1240 -0
- package/dist/index.html +2 -2
- package/package.json +2 -1
- package/shared/constants/attachments.ts +14 -0
- package/shared/constants/engine-tools.ts +1 -1
- package/shared/constants/preview.test.ts +259 -0
- package/shared/constants/preview.ts +1018 -57
- package/shared/constants/tool-icons.ts +5 -0
- package/shared/types/containers/container.ts +1 -1
- package/shared/types/database/schema.ts +9 -6
- package/shared/types/git-identity.ts +1 -1
- package/shared/types/git.ts +116 -0
- package/shared/types/integrations.ts +7 -0
- package/shared/types/stores/settings.ts +1 -1
- package/shared/types/unified/index.ts +1 -1
- package/shared/types/unified/message.ts +0 -7
- package/shared/types/unified/stream.ts +2 -4
- package/shared/types/unified/tool.ts +15 -1
- package/shared/utils/ask-user-question.test.ts +319 -0
- package/shared/utils/ask-user-question.ts +154 -0
- package/shared/utils/home-project.ts +25 -0
- package/shared/utils/logger.ts +2 -0
- package/shared/utils/ws-server.ts +32 -7
- package/backend/auth/session-invalidation.test.ts +0 -112
- package/backend/auth/session-invalidation.ts +0 -77
- package/backend/project/status-manager.test.ts +0 -32
- package/backend/ws/auth/invites.ts +0 -94
- package/backend/ws/auth/users.ts +0 -112
- package/backend/ws/projects/presence.ts +0 -46
- package/backend/ws/stack/access.ts +0 -31
- package/dist/assets/main-BiDNMWb3.css +0 -1
- package/dist/assets/main-BlhKWz2B.js +0 -1241
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Files — what the last turn changed, and getting a file out of a session.
|
|
3
|
+
*
|
|
4
|
+
* Paths are always the session's own working tree (its worktree when it has
|
|
5
|
+
* one), never the whole disk: `/file ../../etc/passwd` is refused like any
|
|
6
|
+
* path outside the tree, so a chat can read exactly what the web Files panel
|
|
7
|
+
* of that session can.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { t } from 'elysia';
|
|
11
|
+
import { existsSync, readdirSync, statSync } from 'fs';
|
|
12
|
+
import { basename, join, relative, resolve } from 'path';
|
|
13
|
+
import { resolveSessionPath, isPathInside } from '$backend/worktrees';
|
|
14
|
+
import { MAX_ATTACHMENT_BYTES } from '$shared/constants/attachments';
|
|
15
|
+
import { formatBytes } from '$backend/chat/attachments';
|
|
16
|
+
import type { ControlChoice } from '../types';
|
|
17
|
+
import { defineAction } from '../define';
|
|
18
|
+
import { paged } from '../paging';
|
|
19
|
+
import { accessibleSession, projectLabel, resolveTarget } from '../workspace';
|
|
20
|
+
import { escapeMd } from './projects';
|
|
21
|
+
import { sessionTitle } from './sessions';
|
|
22
|
+
|
|
23
|
+
interface TurnFile {
|
|
24
|
+
path: string;
|
|
25
|
+
status: 'added' | 'modified' | 'deleted';
|
|
26
|
+
insertions: number;
|
|
27
|
+
deletions: number;
|
|
28
|
+
isBinary: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface TurnChanges {
|
|
32
|
+
turns: Array<{ turnIndex: number; promptText: string; files: TurnFile[] }>;
|
|
33
|
+
net: { filesChanged: number; insertions: number; deletions: number };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const STATUS_MARK: Record<TurnFile['status'], string> = { added: '🆕', modified: '✏️', deleted: '🗑️' };
|
|
37
|
+
|
|
38
|
+
/** Entries that are never worth listing in a folder. */
|
|
39
|
+
const HIDDEN = new Set(['.git', 'node_modules', '.DS_Store']);
|
|
40
|
+
|
|
41
|
+
/** The folder a session works in — its worktree when it has one. */
|
|
42
|
+
function workingRoot(target: { projectId: string; sessionId: string | null }): string {
|
|
43
|
+
const { project, session } = resolveTarget(target);
|
|
44
|
+
return session ? resolveSessionPath(session.id, project.path) : project.path;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const turnDiff = defineAction({
|
|
48
|
+
id: 'files.diff',
|
|
49
|
+
group: 'files',
|
|
50
|
+
title: 'Changes',
|
|
51
|
+
description: 'Files the last turn changed',
|
|
52
|
+
args: t.Object({}),
|
|
53
|
+
command: { name: 'diff' },
|
|
54
|
+
async run(ctx) {
|
|
55
|
+
const found = accessibleSession(ctx.target.sessionId);
|
|
56
|
+
if (!found) return { text: 'No session yet. Send a message first.' };
|
|
57
|
+
const { turns, net } = await ctx.call<TurnChanges>('snapshot:list-turn-changes', { sessionId: found.session.id }, { projectId: found.project.id });
|
|
58
|
+
const turn = turns.find((entry) => entry.files.length > 0);
|
|
59
|
+
if (!turn) return { text: `No file has changed in **${escapeMd(sessionTitle(found.session))}**.` };
|
|
60
|
+
|
|
61
|
+
const lines = turn.files.slice(0, 30).map((file) => {
|
|
62
|
+
const counts = file.isBinary ? 'binary' : `+${file.insertions} −${file.deletions}`;
|
|
63
|
+
return `${STATUS_MARK[file.status]} \`${file.path}\` ${counts}`;
|
|
64
|
+
});
|
|
65
|
+
const more = turn.files.length > 30 ? `\n…and ${turn.files.length - 30} more.` : '';
|
|
66
|
+
const latest = turn === turns[0] ? 'the last turn' : `turn ${turn.turnIndex} (the latest that changed files)`;
|
|
67
|
+
const total = `\n\n_Whole session: ${net.filesChanged} file${net.filesChanged === 1 ? '' : 's'}, +${net.insertions} −${net.deletions}._`;
|
|
68
|
+
const choices: ControlChoice[] = turn.files
|
|
69
|
+
.filter((file) => file.status !== 'deleted')
|
|
70
|
+
.slice(0, 20)
|
|
71
|
+
.map((file) => ({ label: basename(file.path), detail: file.path, action: 'files.get', args: { path: file.path } }));
|
|
72
|
+
return { text: `**🧾 Files changed in ${latest}**\n\n${lines.join('\n')}${more}${total}`, choices };
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
export const getFile = defineAction({
|
|
77
|
+
id: 'files.get',
|
|
78
|
+
group: 'files',
|
|
79
|
+
title: 'Get a file',
|
|
80
|
+
description: 'Get a file from the project, or browse its folders',
|
|
81
|
+
args: t.Object({ path: t.Optional(t.String()), page: t.Optional(t.Number({ minimum: 0 })) }),
|
|
82
|
+
command: { name: 'file', argument: { keys: ['path'], hint: '[path in the project]' } },
|
|
83
|
+
async run(ctx, args) {
|
|
84
|
+
const { project } = resolveTarget(ctx.target);
|
|
85
|
+
const root = workingRoot(ctx.target);
|
|
86
|
+
const requested = (args.path ?? '').trim().replace(/^["']|["']$/g, '').replace(/^\.\//, '');
|
|
87
|
+
const full = resolve(root, requested || '.');
|
|
88
|
+
if (!isPathInside(root, full)) throw new Error('Only files inside the project can be sent.');
|
|
89
|
+
if (!existsSync(full)) throw new Error(`There is no \`${requested}\` in ${projectLabel(project)}.`);
|
|
90
|
+
|
|
91
|
+
const shown = relative(root, full) || '.';
|
|
92
|
+
const stats = statSync(full);
|
|
93
|
+
if (stats.isDirectory()) {
|
|
94
|
+
const entries = readdirSync(full, { withFileTypes: true })
|
|
95
|
+
.filter((entry) => !HIDDEN.has(entry.name))
|
|
96
|
+
.sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
|
|
97
|
+
if (entries.length === 0) return { text: `📂 \`${shown}\` is empty.` };
|
|
98
|
+
const { choices, range } = paged(
|
|
99
|
+
entries,
|
|
100
|
+
args.page,
|
|
101
|
+
(entry) => ({
|
|
102
|
+
label: `${entry.isDirectory() ? '📁' : '📄'} ${entry.name}`,
|
|
103
|
+
action: 'files.get',
|
|
104
|
+
args: { path: relative(root, join(full, entry.name)) }
|
|
105
|
+
}),
|
|
106
|
+
{ action: 'files.get', args: { path: shown } }
|
|
107
|
+
);
|
|
108
|
+
return { text: `**📂 \`${shown}\`** in ${escapeMd(projectLabel(project))}${range}`, choices };
|
|
109
|
+
}
|
|
110
|
+
if (stats.size > MAX_ATTACHMENT_BYTES) {
|
|
111
|
+
throw new Error(`\`${shown}\` is ${formatBytes(stats.size)}, and a chat can only take files up to ${formatBytes(MAX_ATTACHMENT_BYTES)}.`);
|
|
112
|
+
}
|
|
113
|
+
const mime = Bun.file(full).type.split(';')[0] || 'application/octet-stream';
|
|
114
|
+
return { text: `📄 \`${shown}\` · ${formatBytes(stats.size)}`, files: [{ path: full, filename: basename(full), mime }] };
|
|
115
|
+
}
|
|
116
|
+
});
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Engines, models and reasoning — every engine, every model it offers, and
|
|
3
|
+
* the reasoning level when the model has one.
|
|
4
|
+
*
|
|
5
|
+
* Model lists come from the same `models:list` route the web picker uses, so
|
|
6
|
+
* an engine that is not installed or not signed in answers with the same
|
|
7
|
+
* reason the web shows, and a catalog that changes upstream changes here too.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { t } from 'elysia';
|
|
11
|
+
import type { EngineModel, EngineType } from '$shared/types/unified';
|
|
12
|
+
import { ENGINES } from '$shared/constants/engines';
|
|
13
|
+
import { engineQueries, sessionQueries } from '$backend/database/queries';
|
|
14
|
+
import { checkEngineSetup } from '$backend/engine/engine-setup';
|
|
15
|
+
import { defineAction } from '../define';
|
|
16
|
+
import type { ControlChoice, ControlContext, ControlResult } from '../types';
|
|
17
|
+
import { paged } from '../paging';
|
|
18
|
+
import { accessibleSession, createSession, modelOf, resolveTarget } from '../workspace';
|
|
19
|
+
import { escapeMd } from './projects';
|
|
20
|
+
|
|
21
|
+
const ENGINE_TYPES = ENGINES.map((engine) => engine.type) as [EngineType, ...EngineType[]];
|
|
22
|
+
const ENGINE_SCHEMA = t.Union(ENGINE_TYPES.map((type) => t.Literal(type)));
|
|
23
|
+
|
|
24
|
+
export function engineName(type: string): string {
|
|
25
|
+
return ENGINES.find((engine) => engine.type === type)?.name ?? type;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Accept "claude", "Claude Code", "claude-code" — whatever a person types. */
|
|
29
|
+
export function parseEngine(input: string | undefined): EngineType | null {
|
|
30
|
+
const needle = (input ?? '').trim().toLowerCase().replace(/[\s_]+/g, '-');
|
|
31
|
+
if (!needle) return null;
|
|
32
|
+
const exact = ENGINES.find((engine) => engine.type === needle || engine.name.toLowerCase().replace(/\s+/g, '-') === needle);
|
|
33
|
+
if (exact) return exact.type;
|
|
34
|
+
const prefix = ENGINES.find((engine) => engine.type.startsWith(needle) || engine.name.toLowerCase().startsWith(needle.replace(/-/g, ' ')));
|
|
35
|
+
return prefix?.type ?? null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** One engine's models, searchable and paged: what `/model <engine>` and an engine button show. */
|
|
39
|
+
async function modelsOf(ctx: ControlContext, args: { engine: string; query?: string; page?: number }): Promise<ControlResult> {
|
|
40
|
+
const engine = parseEngine(args.engine);
|
|
41
|
+
if (!engine) throw new Error(`No engine called "${args.engine}". Engines: ${ENGINES.map((e) => e.type).join(', ')}.`);
|
|
42
|
+
const models = await ctx.call<EngineModel[]>('models:list', { engine });
|
|
43
|
+
const query = args.query?.trim().toLowerCase();
|
|
44
|
+
const matching = query
|
|
45
|
+
? models.filter((model) => `${model.engine.model.name} ${model.engine.model.id} ${model.engine.provider}`.toLowerCase().includes(query))
|
|
46
|
+
: models;
|
|
47
|
+
if (matching.length === 0) return { text: query ? `No ${engineName(engine)} model matches “${args.query}”.` : `${engineName(engine)} offers no models right now.` };
|
|
48
|
+
|
|
49
|
+
const { session } = resolveTarget(ctx.target);
|
|
50
|
+
const current = modelOf(session);
|
|
51
|
+
const { choices, range } = paged(
|
|
52
|
+
matching,
|
|
53
|
+
args.page,
|
|
54
|
+
(model): ControlChoice => ({
|
|
55
|
+
label: model.engine.model.name,
|
|
56
|
+
detail: model.engine.provider || undefined,
|
|
57
|
+
current: current?.engine === engine && current.modelId === model.engine.model.id,
|
|
58
|
+
action: 'models.set',
|
|
59
|
+
args: { engine, provider: model.engine.provider, modelId: model.engine.model.id, modelName: model.engine.model.name }
|
|
60
|
+
}),
|
|
61
|
+
{ action: 'models.list', args: { engine, ...(args.query ? { query: args.query } : {}) } }
|
|
62
|
+
);
|
|
63
|
+
return { text: `**🤖 ${engineName(engine)} models${range}**${query ? ` matching “${escapeMd(args.query ?? '')}”` : ''}`, choices };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const listEngines = defineAction({
|
|
67
|
+
id: 'models.engines',
|
|
68
|
+
group: 'models',
|
|
69
|
+
title: 'Model',
|
|
70
|
+
description: 'Pick the model for this session',
|
|
71
|
+
args: t.Object({ engine: t.Optional(t.String()), query: t.Optional(t.String()) }),
|
|
72
|
+
command: { name: 'model', argument: { keys: ['engine', 'query'], hint: '[engine] [search]' } },
|
|
73
|
+
async run(ctx, args) {
|
|
74
|
+
if (args.engine?.trim()) return modelsOf(ctx, { engine: args.engine, query: args.query });
|
|
75
|
+
const { session } = resolveTarget(ctx.target);
|
|
76
|
+
const current = modelOf(session);
|
|
77
|
+
// The same readiness check the model picker and the chat gate use, so an
|
|
78
|
+
// engine that would only answer "install it first" says so up front.
|
|
79
|
+
const issues = await Promise.all(
|
|
80
|
+
ENGINES.map((engine) => checkEngineSetup(engine.type, engineQueries.getActiveAccountForEngine(engine.type)?.id ?? 0).catch(() => null))
|
|
81
|
+
);
|
|
82
|
+
const ready = ENGINES.filter((_, index) => !issues[index]).length;
|
|
83
|
+
const header = current ? `🤖 Now: \`${current.modelName}\` on ${engineName(current.engine)}.\n\n` : '';
|
|
84
|
+
const note = ready < ENGINES.length ? `\n_⚠️ marks an engine that is not set up yet. Set it up in Clopen → Settings → Engines._` : '';
|
|
85
|
+
return {
|
|
86
|
+
text: `${header}**🤖 Pick an engine**${note}`,
|
|
87
|
+
choices: ENGINES.map((engine, index) => ({
|
|
88
|
+
label: `${issues[index] ? '⚠️ ' : ''}${engine.name}`,
|
|
89
|
+
detail: issues[index] ? (issues[index]!.reason === 'not-installed' ? 'not installed' : issues[index]!.reason.replace(/-/g, ' ')) : engine.description,
|
|
90
|
+
current: current?.engine === engine.type,
|
|
91
|
+
action: 'models.list',
|
|
92
|
+
args: { engine: engine.type }
|
|
93
|
+
}))
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
export const listModels = defineAction({
|
|
99
|
+
id: 'models.list',
|
|
100
|
+
group: 'models',
|
|
101
|
+
title: 'Models of an engine',
|
|
102
|
+
description: 'Every model an engine offers, searchable, paged.',
|
|
103
|
+
args: t.Object({
|
|
104
|
+
engine: t.String({ minLength: 1 }),
|
|
105
|
+
query: t.Optional(t.String()),
|
|
106
|
+
page: t.Optional(t.Number({ minimum: 0 }))
|
|
107
|
+
}),
|
|
108
|
+
async run(ctx, args) {
|
|
109
|
+
return modelsOf(ctx, args);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
export const setModel = defineAction({
|
|
114
|
+
id: 'models.set',
|
|
115
|
+
group: 'models',
|
|
116
|
+
title: 'Use model',
|
|
117
|
+
description: 'Use a model for the current session (or for the next one, when there is none).',
|
|
118
|
+
args: t.Object({
|
|
119
|
+
engine: ENGINE_SCHEMA,
|
|
120
|
+
provider: t.String(),
|
|
121
|
+
modelId: t.String({ minLength: 1 }),
|
|
122
|
+
modelName: t.String({ minLength: 1 })
|
|
123
|
+
}),
|
|
124
|
+
async run(ctx, args) {
|
|
125
|
+
const { project, session } = resolveTarget(ctx.target);
|
|
126
|
+
const model = { engine: args.engine as EngineType, provider: args.provider, modelId: args.modelId, modelName: args.modelName };
|
|
127
|
+
if (session) {
|
|
128
|
+
const switchedEngine = session.engine !== model.engine;
|
|
129
|
+
sessionQueries.updateEngineModel(session.id, model.engine, model.provider, model.modelId, model.modelName);
|
|
130
|
+
if (switchedEngine) {
|
|
131
|
+
// An account and a reasoning level belong to one engine: carried over
|
|
132
|
+
// they would sign the new engine in as the old one's account. Cleared,
|
|
133
|
+
// the next turn uses the new engine's active account and its default.
|
|
134
|
+
sessionQueries.updateAccount(session.id, null, null);
|
|
135
|
+
sessionQueries.updateReasoning(session.id, null);
|
|
136
|
+
}
|
|
137
|
+
return { text: `🤖 This session now uses \`${args.modelName}\` on ${engineName(args.engine)}.` };
|
|
138
|
+
}
|
|
139
|
+
// No session to switch: start one with this model, so the choice is kept.
|
|
140
|
+
const created = createSession(project, model);
|
|
141
|
+
return {
|
|
142
|
+
text: `🤖 \`${args.modelName}\` on ${engineName(args.engine)}. Your next message starts a session with it.`,
|
|
143
|
+
target: { projectId: project.id, sessionId: created.id }
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
export const listReasoning = defineAction({
|
|
149
|
+
id: 'models.reasoning',
|
|
150
|
+
group: 'models',
|
|
151
|
+
title: 'Reasoning level',
|
|
152
|
+
description: 'Set how hard the model thinks',
|
|
153
|
+
args: t.Object({}),
|
|
154
|
+
command: { name: 'reasoning' },
|
|
155
|
+
async run(ctx) {
|
|
156
|
+
const found = accessibleSession(ctx.target.sessionId);
|
|
157
|
+
const current = modelOf(found?.session);
|
|
158
|
+
if (!found || !current) return { text: 'Pick a model first with /model.' };
|
|
159
|
+
const models = await ctx.call<EngineModel[]>('models:list', { engine: current.engine }, { projectId: found.project.id });
|
|
160
|
+
const control = models.find((model) => model.engine.model.id === current.modelId)?.capabilities.reasoningControl;
|
|
161
|
+
if (!control?.levels.length) return { text: `\`${current.modelName}\` has no reasoning level to choose.` };
|
|
162
|
+
const active = found.session.reasoning_effort ?? control.default;
|
|
163
|
+
return {
|
|
164
|
+
text: `**🧠 Reasoning for \`${current.modelName}\`**`,
|
|
165
|
+
choices: control.levels.map((level) => ({
|
|
166
|
+
label: level.label,
|
|
167
|
+
detail: level.value === control.default ? 'default' : undefined,
|
|
168
|
+
current: level.value === active,
|
|
169
|
+
action: 'models.set-reasoning',
|
|
170
|
+
args: { value: level.value }
|
|
171
|
+
}))
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
export const setReasoning = defineAction({
|
|
177
|
+
id: 'models.set-reasoning',
|
|
178
|
+
group: 'models',
|
|
179
|
+
title: 'Use reasoning level',
|
|
180
|
+
description: 'Set the reasoning level of the current session.',
|
|
181
|
+
args: t.Object({ value: t.String({ minLength: 1 }) }),
|
|
182
|
+
async run(ctx, args) {
|
|
183
|
+
const found = accessibleSession(ctx.target.sessionId);
|
|
184
|
+
if (!found) throw new Error('No session yet. Send a message first.');
|
|
185
|
+
sessionQueries.updateReasoning(found.session.id, args.value);
|
|
186
|
+
return { text: `🧠 Reasoning set to **${escapeMd(args.value)}**.` };
|
|
187
|
+
}
|
|
188
|
+
});
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Projects: list, open, Home, and adding one by walking the machine's
|
|
3
|
+
* folders (making, renaming or deleting folders on the way).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { t } from 'elysia';
|
|
7
|
+
import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync } from 'fs';
|
|
8
|
+
import { basename, dirname, isAbsolute, join, resolve, sep } from 'path';
|
|
9
|
+
import { homedir } from 'os';
|
|
10
|
+
import { projectQueries } from '$backend/database/queries';
|
|
11
|
+
import { ensureHomeProject } from '$backend/projects/home';
|
|
12
|
+
import { homeFirst, isHomeProject, HOME_PROJECT_NAME } from '$shared/utils/home-project';
|
|
13
|
+
import type { Project } from '$shared/types/database/schema';
|
|
14
|
+
import { defineAction } from '../define';
|
|
15
|
+
import type { ControlChoice, ControlResult } from '../types';
|
|
16
|
+
import { isPathInside } from '$backend/worktrees';
|
|
17
|
+
import { getClopenDir } from '$backend/utils/paths';
|
|
18
|
+
import { latestSession, projectLabel } from '../workspace';
|
|
19
|
+
import { paged } from '../paging';
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
export const listProjects = defineAction({
|
|
23
|
+
id: 'projects.list',
|
|
24
|
+
group: 'projects',
|
|
25
|
+
title: 'Projects',
|
|
26
|
+
description: 'Switch project',
|
|
27
|
+
args: t.Object({ page: t.Optional(t.Number({ minimum: 0 })) }),
|
|
28
|
+
command: { name: 'projects' },
|
|
29
|
+
async run(ctx, args) {
|
|
30
|
+
ensureHomeProject();
|
|
31
|
+
const projects = homeFirst(
|
|
32
|
+
projectQueries.getListed().sort((a, b) => (b.last_opened_at ?? '').localeCompare(a.last_opened_at ?? ''))
|
|
33
|
+
);
|
|
34
|
+
const { choices, range } = paged(
|
|
35
|
+
projects,
|
|
36
|
+
args.page,
|
|
37
|
+
(project) => ({
|
|
38
|
+
label: projectLabel(project),
|
|
39
|
+
detail: isHomeProject(project) ? 'no project, just chat' : project.path,
|
|
40
|
+
current: project.id === ctx.target.projectId,
|
|
41
|
+
action: 'projects.open',
|
|
42
|
+
args: { projectId: project.id }
|
|
43
|
+
}),
|
|
44
|
+
{ action: 'projects.list' }
|
|
45
|
+
);
|
|
46
|
+
return { text: `**📁 Pick a project**${range}`, choices };
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
export const openProject = defineAction({
|
|
51
|
+
id: 'projects.open',
|
|
52
|
+
group: 'projects',
|
|
53
|
+
title: 'Open project',
|
|
54
|
+
description: 'Switch to a project; the next message continues its latest session.',
|
|
55
|
+
args: t.Object({ projectId: t.String({ minLength: 1 }) }),
|
|
56
|
+
async run(_ctx, args) {
|
|
57
|
+
const project = projectQueries.getById(args.projectId);
|
|
58
|
+
if (!project || !projectQueries.isListed(project.id)) throw new Error('That project is not in Clopen any more.');
|
|
59
|
+
projectQueries.updateLastOpened(project.id);
|
|
60
|
+
return {
|
|
61
|
+
text: `📁 Now in **${escapeMd(projectLabel(project))}**. Your next message continues its latest session, or /new starts a fresh one.`,
|
|
62
|
+
target: { projectId: project.id, sessionId: latestSession(project.id)?.id ?? null }
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
export const goHome = defineAction({
|
|
68
|
+
id: 'projects.home',
|
|
69
|
+
group: 'projects',
|
|
70
|
+
title: 'Home',
|
|
71
|
+
description: 'Chat without a project',
|
|
72
|
+
args: t.Object({}),
|
|
73
|
+
command: { name: 'home' },
|
|
74
|
+
async run() {
|
|
75
|
+
const home = ensureHomeProject();
|
|
76
|
+
return {
|
|
77
|
+
text: `🏠 Now in **${HOME_PROJECT_NAME}**, with no project.`,
|
|
78
|
+
target: { projectId: home.id, sessionId: latestSession(home.id)?.id ?? null }
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
/** `~/code/app` and relative paths resolve against the server user's home. */
|
|
84
|
+
function normalisePath(input: string): string {
|
|
85
|
+
const trimmed = input.trim().replace(/^["']|["']$/g, '');
|
|
86
|
+
const expanded = trimmed === '~' ? homedir() : trimmed.startsWith('~/') ? resolve(homedir(), trimmed.slice(2)) : trimmed;
|
|
87
|
+
return isAbsolute(expanded) ? resolve(expanded) : resolve(homedir(), expanded);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** How a folder reads in a chat: `~/code/app` rather than the full home path. */
|
|
91
|
+
function shortPath(path: string): string {
|
|
92
|
+
const home = homedir();
|
|
93
|
+
return path === home ? '~' : path.startsWith(`${home}${sep}`) ? `~${path.slice(home.length)}` : path;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Folders not worth walking into when looking for a project. */
|
|
97
|
+
const SKIPPED_FOLDERS = new Set(['node_modules', 'Library', 'Applications', 'AppData']);
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Why a folder must not be renamed or deleted from a chat, or null when it
|
|
101
|
+
* may. The home folder and everything above it, Clopen's own data, and any
|
|
102
|
+
* folder that is (or holds) a project are off limits: a project whose folder
|
|
103
|
+
* moved or vanished is broken in Clopen for everyone who has it.
|
|
104
|
+
*/
|
|
105
|
+
function protectedReason(folder: string): string | null {
|
|
106
|
+
if (folder === resolve(sep) || isPathInside(folder, homedir())) return 'it is your home folder or one above it';
|
|
107
|
+
const data = getClopenDir();
|
|
108
|
+
if (isPathInside(data, folder) || isPathInside(folder, data)) return "it holds Clopen's own data";
|
|
109
|
+
const project = projectQueries.getAll().find((entry) => isPathInside(folder, resolve(entry.path)));
|
|
110
|
+
if (project) return `it ${resolve(project.path) === folder ? 'is' : 'holds'} the project ${isHomeProject(project) ? HOME_PROJECT_NAME : project.name}`;
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** A folder name typed in a chat: one path segment, nothing that climbs out. */
|
|
115
|
+
function folderName(input: string | undefined): string {
|
|
116
|
+
const name = (input ?? '').trim();
|
|
117
|
+
if (!name || name === '.' || name === '..' || /[/\\\0]/.test(name) || name.length > 255) {
|
|
118
|
+
throw new Error('That is not a folder name. Use a single name, without slashes.');
|
|
119
|
+
}
|
|
120
|
+
return name;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function existingFolder(path: string): string {
|
|
124
|
+
const folder = normalisePath(path);
|
|
125
|
+
if (!existsSync(folder) || !statSync(folder).isDirectory()) throw new Error(`There is no folder at ${shortPath(folder)}.`);
|
|
126
|
+
return folder;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** One folder as a menu: add or open it, move around, and manage its folders. */
|
|
130
|
+
function browse(folder: string, page: number | undefined, note?: string): ControlResult {
|
|
131
|
+
let entries: string[] = [];
|
|
132
|
+
try {
|
|
133
|
+
entries = readdirSync(folder, { withFileTypes: true })
|
|
134
|
+
.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.') && !SKIPPED_FOLDERS.has(entry.name))
|
|
135
|
+
.map((entry) => entry.name)
|
|
136
|
+
.sort((a, b) => a.localeCompare(b));
|
|
137
|
+
} catch {
|
|
138
|
+
throw new Error(`Clopen cannot read ${shortPath(folder)}.`);
|
|
139
|
+
}
|
|
140
|
+
const existing = projectQueries.getAll().find((project) => resolve(project.path) === folder);
|
|
141
|
+
const { choices, range } = paged(
|
|
142
|
+
entries,
|
|
143
|
+
page,
|
|
144
|
+
(name) => ({ label: `📁 ${name}`, action: 'projects.browse', args: { path: join(folder, name) } }),
|
|
145
|
+
{ action: 'projects.browse', args: { path: folder } }
|
|
146
|
+
);
|
|
147
|
+
const parent = dirname(folder);
|
|
148
|
+
const locked = protectedReason(folder) !== null;
|
|
149
|
+
const top: ControlChoice[] = [
|
|
150
|
+
existing
|
|
151
|
+
? { label: `📂 Open ${existing.name}`, action: 'projects.open', args: { projectId: existing.id } }
|
|
152
|
+
: { label: `✅ Add ${basename(folder) || folder} as a project`, action: 'projects.create', args: { path: folder } },
|
|
153
|
+
...(parent !== folder ? [{ label: '⬆️ Up', action: 'projects.browse', args: { path: parent } }] : []),
|
|
154
|
+
{ label: '➕ New folder here', action: 'projects.mkdir', args: { path: folder } },
|
|
155
|
+
...(locked
|
|
156
|
+
? []
|
|
157
|
+
: [
|
|
158
|
+
{ label: '✏️ Rename this folder', action: 'projects.rename-folder', args: { path: folder } },
|
|
159
|
+
{ label: '🗑️ Delete this folder', action: 'projects.delete-folder', args: { path: folder } }
|
|
160
|
+
])
|
|
161
|
+
];
|
|
162
|
+
const lines = [
|
|
163
|
+
...(note ? [note] : []),
|
|
164
|
+
`**📂 \`${shortPath(folder)}\`**${range}`,
|
|
165
|
+
existing ? '_Already a project._' : entries.length ? '_Tap a folder to go into it._' : '_No folders inside._'
|
|
166
|
+
];
|
|
167
|
+
return { text: lines.join('\n'), choices: [...top, ...choices] };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Adding a project from a phone means finding a folder without typing its
|
|
172
|
+
* path: walk the machine's folders with buttons, starting at the home folder
|
|
173
|
+
* (or at the one named), make, rename or delete folders on the way, and add
|
|
174
|
+
* the one you are in.
|
|
175
|
+
*/
|
|
176
|
+
export const browseFolders = defineAction({
|
|
177
|
+
id: 'projects.browse',
|
|
178
|
+
group: 'projects',
|
|
179
|
+
title: 'Add project',
|
|
180
|
+
description: 'Add a folder as a project',
|
|
181
|
+
args: t.Object({ path: t.Optional(t.String()), page: t.Optional(t.Number({ minimum: 0 })) }),
|
|
182
|
+
command: { name: 'newproject', argument: { keys: ['path'], hint: '[start folder]' } },
|
|
183
|
+
async run(_ctx, args) {
|
|
184
|
+
return browse(existingFolder(args.path?.trim() || '~'), args.page);
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
export const makeFolder = defineAction({
|
|
189
|
+
id: 'projects.mkdir',
|
|
190
|
+
group: 'projects',
|
|
191
|
+
title: 'New folder',
|
|
192
|
+
description: 'Create a folder inside another.',
|
|
193
|
+
args: t.Object({ path: t.String({ minLength: 1 }), name: t.Optional(t.String()) }),
|
|
194
|
+
async run(_ctx, args) {
|
|
195
|
+
const parent = existingFolder(args.path);
|
|
196
|
+
if (args.name === undefined) {
|
|
197
|
+
return { text: `📂 \`${shortPath(parent)}\``, ask: { question: 'Name of the new folder?', action: 'projects.mkdir', args: { path: parent }, key: 'name' } };
|
|
198
|
+
}
|
|
199
|
+
const folder = join(parent, folderName(args.name));
|
|
200
|
+
if (existsSync(folder)) throw new Error(`${shortPath(folder)} already exists.`);
|
|
201
|
+
mkdirSync(folder);
|
|
202
|
+
return browse(folder, 0, `✅ Created \`${shortPath(folder)}\`.`);
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
export const renameFolder = defineAction({
|
|
207
|
+
id: 'projects.rename-folder',
|
|
208
|
+
group: 'projects',
|
|
209
|
+
title: 'Rename folder',
|
|
210
|
+
description: 'Rename a folder that is not a project.',
|
|
211
|
+
args: t.Object({ path: t.String({ minLength: 1 }), name: t.Optional(t.String()) }),
|
|
212
|
+
async run(_ctx, args) {
|
|
213
|
+
const folder = existingFolder(args.path);
|
|
214
|
+
const reason = protectedReason(folder);
|
|
215
|
+
if (reason) throw new Error(`${shortPath(folder)} cannot be renamed here: ${reason}.`);
|
|
216
|
+
if (args.name === undefined) {
|
|
217
|
+
return { text: `📂 \`${shortPath(folder)}\``, ask: { question: `New name for ${basename(folder)}?`, action: 'projects.rename-folder', args: { path: folder }, key: 'name' } };
|
|
218
|
+
}
|
|
219
|
+
const renamed = join(dirname(folder), folderName(args.name));
|
|
220
|
+
if (renamed === folder) return browse(folder, 0);
|
|
221
|
+
if (existsSync(renamed)) throw new Error(`${shortPath(renamed)} already exists.`);
|
|
222
|
+
renameSync(folder, renamed);
|
|
223
|
+
return browse(renamed, 0, `✏️ Renamed to \`${shortPath(renamed)}\`.`);
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
export const deleteFolder = defineAction({
|
|
228
|
+
id: 'projects.delete-folder',
|
|
229
|
+
group: 'projects',
|
|
230
|
+
title: 'Delete folder',
|
|
231
|
+
description: 'Delete a folder that is not a project, with everything in it.',
|
|
232
|
+
args: t.Object({ path: t.String({ minLength: 1 }) }),
|
|
233
|
+
confirm(args) {
|
|
234
|
+
const folder = normalisePath(args.path);
|
|
235
|
+
let count = 0;
|
|
236
|
+
try {
|
|
237
|
+
count = readdirSync(folder).length;
|
|
238
|
+
} catch {
|
|
239
|
+
// Unreadable: the run says why.
|
|
240
|
+
}
|
|
241
|
+
return `Delete ${shortPath(folder)}${count ? ` and the ${count} item${count === 1 ? '' : 's'} in it` : ''}? This cannot be undone.`;
|
|
242
|
+
},
|
|
243
|
+
async run(_ctx, args) {
|
|
244
|
+
const folder = existingFolder(args.path);
|
|
245
|
+
const reason = protectedReason(folder);
|
|
246
|
+
if (reason) throw new Error(`${shortPath(folder)} cannot be deleted here: ${reason}.`);
|
|
247
|
+
rmSync(folder, { recursive: true, force: true });
|
|
248
|
+
return browse(dirname(folder), 0, `🗑️ Deleted \`${shortPath(folder)}\`.`);
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
export const createProject = defineAction({
|
|
253
|
+
id: 'projects.create',
|
|
254
|
+
group: 'projects',
|
|
255
|
+
title: 'Add project',
|
|
256
|
+
description: 'Add a folder on this machine as a project, and switch to it.',
|
|
257
|
+
args: t.Object({ path: t.String({ minLength: 1 }), name: t.Optional(t.String()) }),
|
|
258
|
+
async run(ctx, args) {
|
|
259
|
+
const path = normalisePath(args.path);
|
|
260
|
+
if (!existsSync(path) || !statSync(path).isDirectory()) throw new Error(`There is no folder at ${shortPath(path)}.`);
|
|
261
|
+
const project = await ctx.call<Project>('projects:create', { name: args.name?.trim() || basename(path), path });
|
|
262
|
+
return {
|
|
263
|
+
text: `📁 Added and opened **${escapeMd(project.name)}** (\`${shortPath(path)}\`).`,
|
|
264
|
+
target: { projectId: project.id, sessionId: latestSession(project.id)?.id ?? null }
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
/** Names are user data: keep `*`, `_` and friends literal inside Markdown. */
|
|
270
|
+
export function escapeMd(value: string): string {
|
|
271
|
+
return value.replace(/([\\`*_~[\]])/g, '\\$1');
|
|
272
|
+
}
|