@myrialabs/clopen 0.4.47 → 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/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/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,365 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the bot says — pure functions from state to card, so the wording can be
|
|
3
|
+
* tested without a bot and stays identical however a message is (re)rendered.
|
|
4
|
+
*
|
|
5
|
+
* Cards are built as formatted RUNS, never as Markdown strings: anything that
|
|
6
|
+
* came from a user or a model (a project name, a session title, a question)
|
|
7
|
+
* is placed into a run as text, so an asterisk in a title is an asterisk and
|
|
8
|
+
* not the start of a bold span. The assistant's own output is the one thing
|
|
9
|
+
* that IS Markdown, and it goes through ChatKit's parser so it arrives as
|
|
10
|
+
* native formatting instead of literal `**`.
|
|
11
|
+
*
|
|
12
|
+
* Titles come from `chatNotificationMessage`, the same source the push
|
|
13
|
+
* notification and the tab toast use, so one event reads the same everywhere.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { markdownToRuns, type TextRun } from '@myrialabs/chatkit';
|
|
17
|
+
import type { AskUserQuestion } from '$shared/types/unified';
|
|
18
|
+
import { chatNotificationMessage } from '$shared/constants/notification-messages';
|
|
19
|
+
|
|
20
|
+
import type { ChannelButton, ChannelCard } from './platforms';
|
|
21
|
+
|
|
22
|
+
/** Where an event happened, as the chat shows it. */
|
|
23
|
+
export interface ChannelContext {
|
|
24
|
+
/** The project's name, or "Home" for a user's Home workspace. */
|
|
25
|
+
projectName?: string;
|
|
26
|
+
sessionTitle?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** A question as it is stored on its row. */
|
|
30
|
+
export interface QuestionPayload {
|
|
31
|
+
question: AskUserQuestion;
|
|
32
|
+
/** Position and count within its AskUserQuestion, for "(1 of 2)". */
|
|
33
|
+
index: number;
|
|
34
|
+
total: number;
|
|
35
|
+
context: ChannelContext;
|
|
36
|
+
/** Option indexes ticked so far (multi-select). */
|
|
37
|
+
selected: number[];
|
|
38
|
+
/** A typed answer ("Other"), kept until Submit on a multi-select question. */
|
|
39
|
+
custom?: string;
|
|
40
|
+
/** Set once this question has its answer — the whole tool may still wait on siblings. */
|
|
41
|
+
answer?: string;
|
|
42
|
+
openUrl?: string | null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Past this many items a menu lists them only as buttons — the text would scroll for pages. */
|
|
46
|
+
const MAX_LISTED_ITEMS = 12;
|
|
47
|
+
|
|
48
|
+
/** Button labels past this are cut; a long one renders as a wall of ellipsis anyway. */
|
|
49
|
+
const MAX_BUTTON_LABEL = 40;
|
|
50
|
+
|
|
51
|
+
/** Session titles are the first user message; a header must stay one line. */
|
|
52
|
+
const MAX_TITLE = 60;
|
|
53
|
+
|
|
54
|
+
function clip(value: string, max: number): string {
|
|
55
|
+
const trimmed = value.trim();
|
|
56
|
+
return trimmed.length > max ? `${trimmed.slice(0, max - 1).trimEnd()}…` : trimmed;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ── Run helpers ─────────────────────────────────────────────────────────────
|
|
60
|
+
|
|
61
|
+
const plain = (text: string): TextRun => ({ text });
|
|
62
|
+
const bold = (text: string): TextRun => ({ text, bold: true });
|
|
63
|
+
const italic = (text: string): TextRun => ({ text, italic: true });
|
|
64
|
+
const code = (text: string): TextRun => ({ text, code: true });
|
|
65
|
+
|
|
66
|
+
/** Join blocks of runs with a blank line between them, skipping empty blocks. */
|
|
67
|
+
function stack(...blocks: Array<TextRun[] | null | undefined | false>): TextRun[] {
|
|
68
|
+
const out: TextRun[] = [];
|
|
69
|
+
for (const block of blocks) {
|
|
70
|
+
if (!block || block.length === 0) continue;
|
|
71
|
+
if (out.length) out.push(plain('\n\n'));
|
|
72
|
+
out.push(...block);
|
|
73
|
+
}
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Join runs line by line. */
|
|
78
|
+
function lines(...rows: TextRun[][]): TextRun[] {
|
|
79
|
+
const out: TextRun[] = [];
|
|
80
|
+
rows.filter((row) => row.length).forEach((row, i) => {
|
|
81
|
+
if (i > 0) out.push(plain('\n'));
|
|
82
|
+
out.push(...row);
|
|
83
|
+
});
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function textCard(text: string, buttons?: ChannelButton[][]): ChannelCard {
|
|
88
|
+
return { runs: [plain(text)], ...(buttons ? { buttons } : {}) };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* `📁 Project · session title` — the project leads, because it is what tells
|
|
93
|
+
* two chats apart at a glance; the title is the first user message and only
|
|
94
|
+
* a hint.
|
|
95
|
+
*/
|
|
96
|
+
export function headerLine(context: ChannelContext): TextRun[] {
|
|
97
|
+
const project = context.projectName?.trim();
|
|
98
|
+
const title = context.sessionTitle?.trim();
|
|
99
|
+
const out: TextRun[] = [];
|
|
100
|
+
if (project) out.push(plain('📁 '), bold(project));
|
|
101
|
+
if (title) out.push(plain(project ? ' · ' : '💬 '), plain(clip(title, MAX_TITLE)));
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function openButton(url: string | null | undefined): ChannelButton[][] {
|
|
106
|
+
return url ? [[{ label: 'Open in Clopen', url }]] : [];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ── Button data ─────────────────────────────────────────────────────────────
|
|
110
|
+
//
|
|
111
|
+
// `<rowId>:<action>`, where the action is an index, `s` (submit), `o` (other:
|
|
112
|
+
// type your own), `y` or `n`.
|
|
113
|
+
// Ten characters of id plus a few of action stays far below Telegram's 64-byte
|
|
114
|
+
// ceiling, and nothing else in a button is trusted — the row it names is
|
|
115
|
+
// re-checked against the chat that pressed it.
|
|
116
|
+
|
|
117
|
+
export type ButtonAction =
|
|
118
|
+
| { type: 'option'; index: number }
|
|
119
|
+
| { type: 'submit' }
|
|
120
|
+
| { type: 'other' }
|
|
121
|
+
| { type: 'confirm' }
|
|
122
|
+
| { type: 'cancel' };
|
|
123
|
+
|
|
124
|
+
const ACTION_CODES = { submit: 's', other: 'o', confirm: 'y', cancel: 'n' } as const;
|
|
125
|
+
|
|
126
|
+
export function encodeButtonData(rowId: string, action: ButtonAction): string {
|
|
127
|
+
return `${rowId}:${action.type === 'option' ? String(action.index) : ACTION_CODES[action.type]}`;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function decodeButtonData(data: string): { rowId: string; action: ButtonAction } | null {
|
|
131
|
+
const match = /^([A-Za-z0-9]{6,32}):(s|o|y|n|\d{1,3})$/.exec(data);
|
|
132
|
+
if (!match) return null;
|
|
133
|
+
const raw = match[2];
|
|
134
|
+
const named = (Object.entries(ACTION_CODES) as Array<[Exclude<ButtonAction['type'], 'option'>, string]>).find(([, code]) => code === raw);
|
|
135
|
+
const action: ButtonAction = named ? ({ type: named[0] } as ButtonAction) : { type: 'option', index: Number(raw) };
|
|
136
|
+
return { rowId: match[1], action };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ── Questions ───────────────────────────────────────────────────────────────
|
|
140
|
+
|
|
141
|
+
/** The answer string the engine receives — the exact shape the web UI's form produces. */
|
|
142
|
+
export function answerFromSelection(question: AskUserQuestion, selected: number[], custom?: string): string {
|
|
143
|
+
const labels = selected
|
|
144
|
+
.filter((index) => index >= 0 && index < question.options.length)
|
|
145
|
+
.sort((a, b) => a - b)
|
|
146
|
+
.map((index) => question.options[index].label);
|
|
147
|
+
const customText = custom?.trim();
|
|
148
|
+
if (question.multiSelect) return [...labels, ...(customText ? [customText] : [])].join(', ');
|
|
149
|
+
return customText || labels.join(', ');
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function questionBody(payload: QuestionPayload): TextRun[] {
|
|
153
|
+
const { question, index, total } = payload;
|
|
154
|
+
const counter = total > 1 ? ` (${index + 1} of ${total})` : '';
|
|
155
|
+
const title = [bold(`❓ ${chatNotificationMessage('waiting-input').title}${counter}`)];
|
|
156
|
+
const asked: TextRun[][] = [];
|
|
157
|
+
if (question.header?.trim()) asked.push([bold(question.header.trim())]);
|
|
158
|
+
asked.push([plain(question.question.trim())]);
|
|
159
|
+
const described = question.options.some((option) => option.description?.trim());
|
|
160
|
+
const options = described
|
|
161
|
+
? question.options.map((option, i) => {
|
|
162
|
+
const description = option.description?.trim();
|
|
163
|
+
return description ? [bold(`${i + 1}. ${option.label}`), plain(`: ${description}`)] : [bold(`${i + 1}. ${option.label}`)];
|
|
164
|
+
})
|
|
165
|
+
: [];
|
|
166
|
+
return stack(lines(title, headerLine(payload.context)), lines(...asked), options.length ? lines(...options) : null);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* A question still waiting, laid out like the web form. Single choice: one
|
|
171
|
+
* button per option, and "Other…" to type an answer instead. Several
|
|
172
|
+
* choices: options are checkboxes, "Other…" adds a typed answer to the
|
|
173
|
+
* ticked ones, and Submit sends them together.
|
|
174
|
+
*/
|
|
175
|
+
export function questionCard(rowId: string, payload: QuestionPayload, options: { typing?: boolean } = {}): ChannelCard {
|
|
176
|
+
const { question, selected } = payload;
|
|
177
|
+
const custom = payload.custom?.trim();
|
|
178
|
+
const hint = options.typing
|
|
179
|
+
? 'Type your answer and send it.'
|
|
180
|
+
: question.multiSelect
|
|
181
|
+
? 'Tick what applies, then Submit.'
|
|
182
|
+
: 'Tap an answer, or Other to type your own.';
|
|
183
|
+
|
|
184
|
+
const optionRows: ChannelButton[][] = question.options.map((option, index) => {
|
|
185
|
+
const box = question.multiSelect ? (selected.includes(index) ? '☑️ ' : '⬜ ') : '';
|
|
186
|
+
return [{ label: clip(`${box}${option.label}`, MAX_BUTTON_LABEL), data: encodeButtonData(rowId, { type: 'option', index }) }];
|
|
187
|
+
});
|
|
188
|
+
const otherLabel = question.multiSelect
|
|
189
|
+
? custom ? `☑️ Other: ${custom}` : options.typing ? '✏️ Other (typing…)' : '⬜ Other…'
|
|
190
|
+
: options.typing ? '✏️ Other (typing…)' : '✏️ Other…';
|
|
191
|
+
optionRows.push([{ label: clip(otherLabel, MAX_BUTTON_LABEL), data: encodeButtonData(rowId, { type: 'other' }) }]);
|
|
192
|
+
if (question.multiSelect) {
|
|
193
|
+
const count = selected.length + (custom ? 1 : 0);
|
|
194
|
+
optionRows.push([{ label: count ? `Submit (${count})` : 'Submit', data: encodeButtonData(rowId, { type: 'submit' }) }]);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return { runs: stack(questionBody(payload), [italic(hint)]), buttons: [...optionRows, ...openButton(payload.openUrl)] };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** A question whose answer is in, but whose siblings in the same tool may not be. */
|
|
201
|
+
export function questionAnsweredCard(payload: QuestionPayload, answer: string, pending: number): ChannelCard {
|
|
202
|
+
const tail = pending > 0 ? [italic(`${pending} more question${pending === 1 ? '' : 's'} to go.`)] : null;
|
|
203
|
+
return { runs: stack(questionBody(payload), [plain('✅ '), bold(answer || '(no answer)')], tail), buttons: openButton(payload.openUrl) };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** A question settled somewhere else, or one that will never be answered. */
|
|
207
|
+
export function questionClosedCard(payload: QuestionPayload, reason: 'answered-elsewhere' | 'run-ended'): ChannelCard {
|
|
208
|
+
const note = reason === 'answered-elsewhere' ? '✅ Answered in Clopen.' : '⏹ No longer waiting. The run ended.';
|
|
209
|
+
return { runs: stack(questionBody(payload), [italic(note)]), buttons: openButton(payload.openUrl) };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ── Turns ───────────────────────────────────────────────────────────────────
|
|
213
|
+
|
|
214
|
+
export function formatDuration(ms: number): string {
|
|
215
|
+
const seconds = Math.max(0, Math.round(ms / 1000));
|
|
216
|
+
if (seconds < 60) return `${seconds}s`;
|
|
217
|
+
const minutes = Math.floor(seconds / 60);
|
|
218
|
+
if (minutes < 60) return `${minutes}m ${seconds % 60}s`;
|
|
219
|
+
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* The answer to a turn the chat started — the conversation itself. The header
|
|
224
|
+
* is only shown when the reply is not about the session the chat is already
|
|
225
|
+
* in: inside one conversation it would be noise on every message.
|
|
226
|
+
*/
|
|
227
|
+
export function answerRuns(input: { markdown: string; context: ChannelContext; showHeader: boolean }): TextRun[] {
|
|
228
|
+
const body = markdownToRuns(input.markdown.trim() || '_(no text in this reply)_');
|
|
229
|
+
return input.showHeader ? stack(headerLine(input.context), body) : body;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* A turn that failed. Whatever it said before failing is still shown — it is
|
|
234
|
+
* often most of the work — and the failure follows it, so a partial answer
|
|
235
|
+
* never reads as a finished one.
|
|
236
|
+
*/
|
|
237
|
+
export function failedRuns(input: { context: ChannelContext; showHeader: boolean; reason?: string | null; partial?: string | null }): TextRun[] {
|
|
238
|
+
const partial = input.partial?.trim();
|
|
239
|
+
return stack(
|
|
240
|
+
input.showHeader ? headerLine(input.context) : null,
|
|
241
|
+
partial ? markdownToRuns(partial) : null,
|
|
242
|
+
[bold(partial ? '⚠️ The run failed before it finished.' : '⚠️ The run failed.'), ...(input.reason ? [plain(` ${clip(input.reason, 300)}`)] : [])],
|
|
243
|
+
[italic('Reply to try again, or /retry.')]
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** A turn stopped part-way: what it had said, then that it stopped. */
|
|
248
|
+
export function stoppedRuns(input: { context: ChannelContext; showHeader: boolean; partial: string }): TextRun[] {
|
|
249
|
+
return stack(input.showHeader ? headerLine(input.context) : null, markdownToRuns(input.partial.trim()), [italic('⏹ Stopped.')]);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** The live "still working" line, edited in place while a turn the chat started runs. */
|
|
253
|
+
export function progressCard(input: { elapsedMs: number; activity: string | null; steps: number }): ChannelCard {
|
|
254
|
+
const steps = input.steps > 0 ? ` · ${input.steps} step${input.steps === 1 ? '' : 's'}` : '';
|
|
255
|
+
return {
|
|
256
|
+
runs: lines([italic(`⏳ Working · ${formatDuration(input.elapsedMs)}${steps}`)], input.activity ? [code(clip(input.activity, 120))] : [])
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** One line describing a tool call — what the progress card shows. */
|
|
261
|
+
export function describeToolUse(name: string, input: Record<string, unknown> | undefined): string {
|
|
262
|
+
const pick = (...keys: string[]) => {
|
|
263
|
+
for (const key of keys) {
|
|
264
|
+
const value = input?.[key];
|
|
265
|
+
if (typeof value === 'string' && value.trim()) return value.trim().split('\n')[0];
|
|
266
|
+
}
|
|
267
|
+
return null;
|
|
268
|
+
};
|
|
269
|
+
const target = pick('file_path', 'path', 'command', 'pattern', 'url', 'query', 'description', 'prompt');
|
|
270
|
+
return target ? `${name} ${target}` : name;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// ── Menus, confirmations, status ────────────────────────────────────────────
|
|
274
|
+
|
|
275
|
+
export interface MenuItem {
|
|
276
|
+
label: string;
|
|
277
|
+
/** A second line of context — a path, a provider. Shown in the text, not on the button. */
|
|
278
|
+
detail?: string;
|
|
279
|
+
current?: boolean;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* A title (already formatted) followed by numbered items, one button each.
|
|
284
|
+
* Items past the list's own length are not shown in the text — the buttons
|
|
285
|
+
* carry them — so a long model list stays readable.
|
|
286
|
+
*/
|
|
287
|
+
export function menuCard(rowId: string, title: TextRun[], items: MenuItem[]): ChannelCard {
|
|
288
|
+
const listed = items.length <= MAX_LISTED_ITEMS;
|
|
289
|
+
const listing = listed
|
|
290
|
+
? items.map((item, i) => {
|
|
291
|
+
const row: TextRun[] = [bold(`${i + 1}. ${item.label}`)];
|
|
292
|
+
if (item.current) row.push(plain(' ✓'));
|
|
293
|
+
if (item.detail) row.push(plain(` · ${clip(item.detail, 80)}`));
|
|
294
|
+
return row;
|
|
295
|
+
})
|
|
296
|
+
: [];
|
|
297
|
+
return {
|
|
298
|
+
runs: stack(title, listing.length ? lines(...listing) : null),
|
|
299
|
+
buttons: items.map((item, index) => [{ label: clip(`${item.current ? '✓ ' : ''}${item.label}`, MAX_BUTTON_LABEL), data: encodeButtonData(rowId, { type: 'option', index }) }])
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export function confirmCard(rowId: string, input: { title: string; detail: string; confirmLabel: string }): ChannelCard {
|
|
304
|
+
return {
|
|
305
|
+
runs: stack([bold(input.title)], [plain(input.detail)]),
|
|
306
|
+
buttons: [[
|
|
307
|
+
{ label: input.confirmLabel, data: encodeButtonData(rowId, { type: 'confirm' }) },
|
|
308
|
+
{ label: 'Cancel', data: encodeButtonData(rowId, { type: 'cancel' }) }
|
|
309
|
+
]]
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Commands the chat app owns itself: they are about THIS chat (help,
|
|
315
|
+
* unlinking, going back in its conversation). Everything else comes from
|
|
316
|
+
* the control catalog (`backend/control/`), which is where a new command belongs.
|
|
317
|
+
*/
|
|
318
|
+
export const CHAT_COMMANDS: { command: string; description: string; hint?: string }[] = [
|
|
319
|
+
{ command: 'help', description: 'What this bot can do' },
|
|
320
|
+
{ command: 'retry', description: 'Ask the last message again' },
|
|
321
|
+
{ command: 'undo', description: 'Undo the last message and its file changes' },
|
|
322
|
+
{ command: 'unlink', description: 'Unlink this chat' }
|
|
323
|
+
];
|
|
324
|
+
|
|
325
|
+
// ── Conversation replies ────────────────────────────────────────────────────
|
|
326
|
+
|
|
327
|
+
export const REPLIES = {
|
|
328
|
+
paired:
|
|
329
|
+
`Linked to your Clopen. Just type to chat, or send photos and files. You start in Home, with no project selected: /projects switches project, /model picks a model, /help lists everything.\n\nSend /unlink to unlink this chat.`,
|
|
330
|
+
chatOff: 'This chat is switched off in Clopen → Settings → Chat Apps, so it cannot do anything right now.',
|
|
331
|
+
chatOn: '✅ This chat is switched back on.',
|
|
332
|
+
pairingExpired: 'That link has expired or was already used. Open Clopen → Settings → Chat Apps and link Telegram again.',
|
|
333
|
+
notLinked: 'This chat is not linked to Clopen yet. Open Clopen → Settings → Chat Apps and choose "Link Telegram".',
|
|
334
|
+
groupRefused: 'Clopen only links to a private chat with this bot, never to a group.',
|
|
335
|
+
unlinked: 'Unlinked. This chat no longer controls Clopen.',
|
|
336
|
+
helpIntro:
|
|
337
|
+
'Type to chat with the session you are in, including photos, files and albums. Reply to any earlier message to continue from that point. Edit a message you sent to rewrite it, like Edit in Clopen.',
|
|
338
|
+
controlOff: 'Controlling Clopen is switched off for this bot. Turn on "Control Clopen" for it in Settings → Integrations.',
|
|
339
|
+
unknownCommand: (name: string) => `There is no /${name}. /help lists what this bot can do.`,
|
|
340
|
+
sendAsMessage: 'Send it to the session as a message instead?',
|
|
341
|
+
skillNotACommand: (name: string) => `${name.replace(/_/g, '-')} is one of your skills. Run it with /run ${name.replace(/_/g, '-')}, followed by what it needs.`,
|
|
342
|
+
pickReply: 'Several questions are waiting. Reply to the one you are answering (swipe it, or long-press and choose Reply) so it reaches the right session.',
|
|
343
|
+
staleQuestion: 'That question is no longer waiting for an answer.',
|
|
344
|
+
staleAction: 'That is no longer available.',
|
|
345
|
+
noAccess: 'You no longer have access to that project.',
|
|
346
|
+
sessionGone: 'That session no longer exists.',
|
|
347
|
+
answerFailed: 'The session stopped waiting before the answer arrived. Open Clopen to see where it is.',
|
|
348
|
+
noModel: 'No model is picked yet. Use /model to choose one, then send your message again.',
|
|
349
|
+
busyBranch: 'That session is still running. /stop it first, or wait for it to finish, then reply again.',
|
|
350
|
+
busyRestore: 'The session is running. Wait for it to finish (or /stop it) before going back.',
|
|
351
|
+
notEditable: 'Only messages you sent from this chat can be edited here, and only into a session that still exists.',
|
|
352
|
+
nothingToRetry: 'Nothing to retry yet. Send a message first.',
|
|
353
|
+
nothingToUndo: 'Nothing to undo. This session has no message yet.',
|
|
354
|
+
undone: (files: number) => (files > 0 ? `↩️ Went back to before the last message (${files} file${files === 1 ? '' : 's'} restored).` : '↩️ Went back to before the last message.'),
|
|
355
|
+
queuedEdited: '✏️ Updated. Your queued message will run with the new text.',
|
|
356
|
+
editReplaced: 'Replaced by your newer edit.',
|
|
357
|
+
attachmentsDropped: (problems: string[]) => `⚠️ Some files did not come through:\n${problems.map((problem) => `• ${problem}`).join('\n')}`,
|
|
358
|
+
nothingToSend: 'There was nothing in that message to send.',
|
|
359
|
+
otherAdded: '☑️ Added as "Other". Tick anything else, then Submit.',
|
|
360
|
+
answerTakesText: 'A question is answered with text or a tap, so the file was not sent with your answer.',
|
|
361
|
+
cancelled: 'Cancelled. Nothing changed.',
|
|
362
|
+
queued: '🕒 The session is still working. Your message is queued and runs next.',
|
|
363
|
+
branched: (files: number) => (files > 0 ? `↩️ Went back to that point (${files} file${files === 1 ? '' : 's'} restored) and sent your message.` : '↩️ Went back to that point and sent your message.'),
|
|
364
|
+
testMessage: '🔔 Test message from Clopen. This chat is linked and working.'
|
|
365
|
+
} as const;
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outbound: what Clopen tells a paired chat, and keeping it true.
|
|
3
|
+
*
|
|
4
|
+
* A chat is told only about turns IT started; it is a conversation, not a
|
|
5
|
+
* notifier. Fed by server-side stream events, so it fires whether or not
|
|
6
|
+
* any browser tab is open:
|
|
7
|
+
*
|
|
8
|
+
* - The turn asks something (AskUserQuestion): one message per question,
|
|
9
|
+
* its options as buttons.
|
|
10
|
+
* - A question is answered somewhere else (the web UI): the message is
|
|
11
|
+
* re-rendered as answered and loses its buttons, so the phone never
|
|
12
|
+
* offers a choice the session has already moved past.
|
|
13
|
+
* - The turn ends: the answer goes back in full, formatted and split as
|
|
14
|
+
* needed, with the images it shows sent as pictures.
|
|
15
|
+
*
|
|
16
|
+
* Every message that stands for a point in the conversation is recorded with
|
|
17
|
+
* the Clopen message it stands for, which is what lets a reply to it continue
|
|
18
|
+
* from exactly there.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { AskUserQuestion } from '$shared/types/unified';
|
|
22
|
+
import {
|
|
23
|
+
channelMessageQueries,
|
|
24
|
+
integrationAccountQueries,
|
|
25
|
+
newChannelMessageId,
|
|
26
|
+
channelLinkQueries,
|
|
27
|
+
projectQueries,
|
|
28
|
+
sessionQueries,
|
|
29
|
+
type ChannelMessageRow,
|
|
30
|
+
type ChannelLinkRow
|
|
31
|
+
} from '$backend/database/queries';
|
|
32
|
+
import { isHomeProject, HOME_PROJECT_NAME } from '$shared/utils/home-project';
|
|
33
|
+
import { debug } from '$shared/utils/logger';
|
|
34
|
+
import { channelRuntime } from './runtime';
|
|
35
|
+
import { lastTurnAnswer } from '$backend/chat/turn-answer';
|
|
36
|
+
import { endLiveTurn, liveTurn, takeStoppedByChat } from './turns';
|
|
37
|
+
import { answerImages } from './media';
|
|
38
|
+
import { resolveSessionPath } from '$backend/worktrees';
|
|
39
|
+
import {
|
|
40
|
+
answerRuns,
|
|
41
|
+
failedRuns,
|
|
42
|
+
stoppedRuns,
|
|
43
|
+
questionCard,
|
|
44
|
+
questionClosedCard,
|
|
45
|
+
textCard,
|
|
46
|
+
type ChannelContext,
|
|
47
|
+
type QuestionPayload
|
|
48
|
+
} from './messages';
|
|
49
|
+
|
|
50
|
+
/** A message older than this is no longer a sensible thing to reply to. */
|
|
51
|
+
const MESSAGE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
52
|
+
|
|
53
|
+
export function resolveContext(projectId: string, chatSessionId: string | null | undefined): ChannelContext {
|
|
54
|
+
const project = projectQueries.getById(projectId);
|
|
55
|
+
return {
|
|
56
|
+
projectName: project ? (isHomeProject(project) ? HOME_PROJECT_NAME : project.name) : undefined,
|
|
57
|
+
sessionTitle: chatSessionId ? sessionQueries.getById(chatSessionId)?.title || undefined : undefined
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A link that opens this session, when Clopen has an address another device can reach. */
|
|
62
|
+
export function sessionUrl(projectId: string, chatSessionId: string): string | null {
|
|
63
|
+
const origin = channelRuntime.publicOrigin();
|
|
64
|
+
return origin ? `${origin}/#session/${encodeURIComponent(projectId)}/${encodeURIComponent(chatSessionId)}` : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Does this account have `capability` switched on? */
|
|
68
|
+
export function accountHas(accountId: string, capability: 'control'): boolean {
|
|
69
|
+
const account = integrationAccountQueries.getById(accountId);
|
|
70
|
+
return Boolean(account) && integrationAccountQueries.capabilitiesOf(account!).includes(capability);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function parsePayload<T>(row: ChannelMessageRow): T {
|
|
74
|
+
try {
|
|
75
|
+
return JSON.parse(row.payload) as T;
|
|
76
|
+
} catch {
|
|
77
|
+
return {} as T;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Tool uses already announced (or being announced). The stream emits a
|
|
83
|
+
* question's message more than once as it fills in, and two sends racing each
|
|
84
|
+
* other would both find no row yet.
|
|
85
|
+
*/
|
|
86
|
+
const announced = new Set<string>();
|
|
87
|
+
|
|
88
|
+
export async function announceQuestion(input: {
|
|
89
|
+
projectId: string;
|
|
90
|
+
chatSessionId: string;
|
|
91
|
+
toolUseId: string;
|
|
92
|
+
questions: AskUserQuestion[];
|
|
93
|
+
}): Promise<void> {
|
|
94
|
+
const { projectId, chatSessionId, toolUseId } = input;
|
|
95
|
+
const questions = input.questions.filter((q) => q && typeof q.question === 'string' && Array.isArray(q.options));
|
|
96
|
+
if (questions.length === 0 || announced.has(toolUseId)) return;
|
|
97
|
+
if (channelMessageQueries.forToolUse(toolUseId).length > 0) return;
|
|
98
|
+
announced.add(toolUseId);
|
|
99
|
+
setTimeout(() => announced.delete(toolUseId), 10 * 60 * 1000).unref?.();
|
|
100
|
+
|
|
101
|
+
// Only the chat that started this turn is in a conversation with it.
|
|
102
|
+
const origin = liveTurn(chatSessionId);
|
|
103
|
+
const link = origin ? channelLinkQueries.getById(origin.linkId) : null;
|
|
104
|
+
if (!link || !channelLinkQueries.isActive(link) || !channelRuntime.get(link.account_id)) return;
|
|
105
|
+
|
|
106
|
+
const context = resolveContext(projectId, chatSessionId);
|
|
107
|
+
const openUrl = sessionUrl(projectId, chatSessionId);
|
|
108
|
+
|
|
109
|
+
for (const [index, question] of questions.entries()) {
|
|
110
|
+
const id = newChannelMessageId();
|
|
111
|
+
const payload: QuestionPayload = { question, index, total: questions.length, context, selected: [], openUrl };
|
|
112
|
+
try {
|
|
113
|
+
const sent = await channelRuntime.send(link.account_id, link.conversation_id, questionCard(id, payload));
|
|
114
|
+
if (!sent.platform_message_id) continue;
|
|
115
|
+
channelMessageQueries.create({
|
|
116
|
+
id,
|
|
117
|
+
linkId: link.id,
|
|
118
|
+
kind: 'question',
|
|
119
|
+
projectId,
|
|
120
|
+
chatSessionId,
|
|
121
|
+
toolUseId,
|
|
122
|
+
questionIndex: index,
|
|
123
|
+
platformMessageId: sent.platform_message_id,
|
|
124
|
+
payload
|
|
125
|
+
});
|
|
126
|
+
} catch (error) {
|
|
127
|
+
debug.warn('chat-apps', 'Sending a question to a channel failed:', error);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Close every still-open message for these questions, saying why. */
|
|
133
|
+
async function closeQuestions(rows: ChannelMessageRow[], reason: 'answered-elsewhere' | 'run-ended'): Promise<void> {
|
|
134
|
+
for (const row of rows) {
|
|
135
|
+
if (row.state !== 'open' || !channelMessageQueries.settle(row.id, 'closed')) continue;
|
|
136
|
+
const link = channelLinkQueries.getById(row.link_id);
|
|
137
|
+
if (!link) continue;
|
|
138
|
+
await channelRuntime.edit(link.account_id, link.conversation_id, row.platform_message_id, questionClosedCard(parsePayload<QuestionPayload>(row), reason));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Tool results arrived — any question they answer is settled, wherever it was answered. */
|
|
143
|
+
export async function settleToolUses(toolUseIds: string[]): Promise<void> {
|
|
144
|
+
for (const toolUseId of toolUseIds) {
|
|
145
|
+
await closeQuestions(channelMessageQueries.forToolUse(toolUseId), 'answered-elsewhere');
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
let lastPruneAt = 0;
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* The chat that started this turn gets its answer — in full, formatted, split
|
|
153
|
+
* as needed, as a reply to the message that asked when there is one. Each
|
|
154
|
+
* message is recorded against the turn's end, so replying to any of them
|
|
155
|
+
* continues from here.
|
|
156
|
+
*/
|
|
157
|
+
async function deliverAnswer(
|
|
158
|
+
link: ChannelLinkRow,
|
|
159
|
+
input: { status: 'completed' | 'error' | 'cancelled'; projectId: string; chatSessionId: string; replyTo: string | null; reason?: string }
|
|
160
|
+
): Promise<void> {
|
|
161
|
+
const { status, projectId, chatSessionId } = input;
|
|
162
|
+
const context = resolveContext(projectId, chatSessionId);
|
|
163
|
+
// Inside the conversation the chat is already in, a header on every reply is
|
|
164
|
+
// noise; it is shown only when the answer is about some other session.
|
|
165
|
+
const showHeader = link.active_session_id !== chatSessionId;
|
|
166
|
+
const answer = lastTurnAnswer(chatSessionId);
|
|
167
|
+
|
|
168
|
+
// Pictures the answer shows go out after its text, and their paths leave it.
|
|
169
|
+
const project = projectQueries.getById(projectId);
|
|
170
|
+
const root = project ? resolveSessionPath(chatSessionId, project.path) : null;
|
|
171
|
+
const { markdown, images } = answer.text ? await answerImages(answer.text, root) : { markdown: '', images: [] };
|
|
172
|
+
|
|
173
|
+
let runs;
|
|
174
|
+
if (status === 'cancelled') {
|
|
175
|
+
// Stopped from this chat with nothing said: "Stopped" was already the reply.
|
|
176
|
+
const stoppedHere = takeStoppedByChat(chatSessionId);
|
|
177
|
+
if (!markdown.trim()) {
|
|
178
|
+
if (!stoppedHere) await channelRuntime.send(link.account_id, link.conversation_id, textCard('⏹ Stopped.'), input.replyTo).catch(() => {});
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
runs = stoppedRuns({ context, showHeader, partial: markdown });
|
|
182
|
+
} else if (status === 'error') {
|
|
183
|
+
runs = failedRuns({ context, showHeader, reason: input.reason ?? answer.error, partial: markdown });
|
|
184
|
+
} else {
|
|
185
|
+
runs = answerRuns({ markdown, context, showHeader });
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
try {
|
|
189
|
+
const results = await channelRuntime.sendLong(link.account_id, link.conversation_id, runs, { replyTo: input.replyTo });
|
|
190
|
+
for (const image of images) {
|
|
191
|
+
try {
|
|
192
|
+
results.push(await channelRuntime.sendFile(link.account_id, link.conversation_id, image));
|
|
193
|
+
} catch (error) {
|
|
194
|
+
debug.log('chat-apps', 'An image of an answer could not be sent:', error);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
for (const result of results) {
|
|
198
|
+
if (!result.platform_message_id) continue;
|
|
199
|
+
channelMessageQueries.create({
|
|
200
|
+
linkId: link.id,
|
|
201
|
+
kind: 'answer',
|
|
202
|
+
projectId,
|
|
203
|
+
chatSessionId,
|
|
204
|
+
clopenMessageId: answer.endMessageId,
|
|
205
|
+
platformMessageId: result.platform_message_id,
|
|
206
|
+
state: 'closed'
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
} catch (error) {
|
|
210
|
+
debug.warn('chat-apps', 'Delivering an answer to a channel failed:', error);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export async function announceRunEnded(input: {
|
|
215
|
+
status: 'completed' | 'error' | 'cancelled';
|
|
216
|
+
projectId: string;
|
|
217
|
+
chatSessionId: string;
|
|
218
|
+
reason?: string;
|
|
219
|
+
}): Promise<void> {
|
|
220
|
+
const { status, projectId, chatSessionId, reason } = input;
|
|
221
|
+
|
|
222
|
+
// Whatever is still asking for an answer will never get one now.
|
|
223
|
+
await closeQuestions(channelMessageQueries.openQuestionsForSession(chatSessionId), 'run-ended');
|
|
224
|
+
|
|
225
|
+
if (Date.now() - lastPruneAt > 60 * 60 * 1000) {
|
|
226
|
+
lastPruneAt = Date.now();
|
|
227
|
+
channelMessageQueries.pruneBefore(new Date(Date.now() - MESSAGE_RETENTION_MS).toISOString());
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const origin = endLiveTurn(chatSessionId);
|
|
231
|
+
if (reason === 'session-deleted' || !origin) return;
|
|
232
|
+
const link = channelLinkQueries.getById(origin.linkId);
|
|
233
|
+
if (link && channelLinkQueries.isActive(link) && channelRuntime.get(link.account_id)) {
|
|
234
|
+
await deliverAnswer(link, { status, projectId, chatSessionId, replyTo: origin.platformMessageId, reason });
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** A deleted session leaves nothing to reply to, and nothing to continue. */
|
|
239
|
+
export function forgetSession(chatSessionId: string): void {
|
|
240
|
+
endLiveTurn(chatSessionId);
|
|
241
|
+
channelMessageQueries.deleteForSession(chatSessionId);
|
|
242
|
+
channelLinkQueries.clearActiveSession(chatSessionId);
|
|
243
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach, setSystemTime, afterEach } from 'bun:test';
|
|
2
|
+
import { issuePairingCode, redeemPairingCode, revokePairingCode, resetPairingCodes, PAIRING_TTL_MS } from './pairing';
|
|
3
|
+
|
|
4
|
+
beforeEach(() => resetPairingCodes());
|
|
5
|
+
afterEach(() => setSystemTime());
|
|
6
|
+
|
|
7
|
+
describe('pairing codes', () => {
|
|
8
|
+
it('fit a Telegram start parameter', () => {
|
|
9
|
+
const { code } = issuePairingCode('user-1', 'acct-1');
|
|
10
|
+
expect(code).toMatch(/^[A-Za-z0-9_-]{1,64}$/);
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
it('work once, for the bot they were issued for', () => {
|
|
14
|
+
const { code } = issuePairingCode('user-1', 'acct-1');
|
|
15
|
+
expect(redeemPairingCode(code, 'acct-1')).toEqual({ userId: 'user-1' });
|
|
16
|
+
expect(redeemPairingCode(code, 'acct-1')).toBeNull();
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('are burned when they reach the wrong bot', () => {
|
|
20
|
+
const { code } = issuePairingCode('user-1', 'acct-1');
|
|
21
|
+
expect(redeemPairingCode(code, 'acct-2')).toBeNull();
|
|
22
|
+
expect(redeemPairingCode(code, 'acct-1')).toBeNull();
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('expire', () => {
|
|
26
|
+
const { code } = issuePairingCode('user-1', 'acct-1');
|
|
27
|
+
setSystemTime(new Date(Date.now() + PAIRING_TTL_MS + 1000));
|
|
28
|
+
expect(redeemPairingCode(code, 'acct-1')).toBeNull();
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('asking again invalidates the previous link', () => {
|
|
32
|
+
const first = issuePairingCode('user-1', 'acct-1');
|
|
33
|
+
const second = issuePairingCode('user-1', 'acct-1');
|
|
34
|
+
expect(redeemPairingCode(first.code, 'acct-1')).toBeNull();
|
|
35
|
+
expect(redeemPairingCode(second.code, 'acct-1')).toEqual({ userId: 'user-1' });
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('a closed link stops working, and only that user’s link for that bot', () => {
|
|
39
|
+
const mine = issuePairingCode('user-1', 'acct-1');
|
|
40
|
+
const theirs = issuePairingCode('user-2', 'acct-1');
|
|
41
|
+
revokePairingCode('user-1', 'acct-1');
|
|
42
|
+
expect(redeemPairingCode(mine.code, 'acct-1')).toBeNull();
|
|
43
|
+
expect(redeemPairingCode(theirs.code, 'acct-1')).toEqual({ userId: 'user-2' });
|
|
44
|
+
});
|
|
45
|
+
});
|