@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,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Files in a chat: what a message turns into for the prompt, and which
|
|
3
|
+
* images of an answer are sent — only from the session's own folder.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
|
|
7
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
|
|
8
|
+
import { homedir, tmpdir } from 'os';
|
|
9
|
+
import { join } from 'path';
|
|
10
|
+
import { answerImages, promptContent, textOf } from './media';
|
|
11
|
+
|
|
12
|
+
let root: string;
|
|
13
|
+
|
|
14
|
+
beforeAll(() => {
|
|
15
|
+
root = mkdtempSync(join(tmpdir(), 'clopen-media-'));
|
|
16
|
+
writeFileSync(join(root, 'chart.png'), Buffer.from([0x89, 0x50, 0x4e, 0x47]));
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
afterAll(() => rmSync(root, { recursive: true, force: true }));
|
|
20
|
+
|
|
21
|
+
describe('a message from a chat', () => {
|
|
22
|
+
it('reads text, a caption, a location and a contact as prompt text', () => {
|
|
23
|
+
expect(textOf({ type: 'text', text: 'hi' })).toBe('hi');
|
|
24
|
+
expect(textOf({ type: 'media', media_type: 'image', caption: 'look' })).toBe('look');
|
|
25
|
+
expect(textOf({ type: 'location', lat: 1.5, lng: 2.5 })).toContain('1.5, 2.5');
|
|
26
|
+
expect(textOf({ type: 'contact', name: 'Ana', phone: '+62' })).toContain('Ana +62');
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('puts files before the text, like the web composer, and keeps a file-only message', () => {
|
|
30
|
+
const file = { type: 'image' as const, mediaType: 'image/png', data: 'AAAA', title: 'a.png' };
|
|
31
|
+
expect(promptContent('what is it', [file]).map((block) => (block as { type: string }).type)).toEqual(['image', 'text']);
|
|
32
|
+
expect(promptContent('', [file]).map((block) => (block as { type: string }).type)).toEqual(['image']);
|
|
33
|
+
expect(promptContent('only text', [])).toEqual([{ type: 'text', text: 'only text' }]);
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
describe('images in an answer', () => {
|
|
38
|
+
it('sends a local image from the session folder and replaces its path with a marker', async () => {
|
|
39
|
+
const { markdown, images } = await answerImages('Here it is:\n\n\n\nDone.', root);
|
|
40
|
+
expect(images).toHaveLength(1);
|
|
41
|
+
expect(images[0]).toMatchObject({ filename: 'chart.png', mime: 'image/png', caption: 'Revenue' });
|
|
42
|
+
expect(markdown).toContain('🖼️ Revenue');
|
|
43
|
+
expect(markdown).not.toContain('chart.png)');
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('decodes a data URI', async () => {
|
|
47
|
+
const { images } = await answerImages('', root);
|
|
48
|
+
expect(images[0]?.mime).toBe('image/png');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('never reads an image from outside the session folder or the temp folder', async () => {
|
|
52
|
+
const outside = join(homedir(), 'definitely-not-here.png');
|
|
53
|
+
const { markdown, images } = await answerImages(` `, root);
|
|
54
|
+
expect(images).toHaveLength(0);
|
|
55
|
+
expect(markdown).toContain(outside);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('leaves a missing or non-image file as written', async () => {
|
|
59
|
+
const { images } = await answerImages(' ', root);
|
|
60
|
+
expect(images).toHaveLength(0);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Files in a chat — both ways.
|
|
3
|
+
*
|
|
4
|
+
* IN: whatever a chat sends (a photo, an album, a PDF, a voice note, any
|
|
5
|
+
* file) becomes the same image/document blocks the web composer produces.
|
|
6
|
+
* What happens to them next is not decided here: the stream's one attachment
|
|
7
|
+
* rule (`backend/chat/attachments.ts`) keeps what the model reads inline and
|
|
8
|
+
* saves the rest into the session's folder, exactly as for the web.
|
|
9
|
+
*
|
|
10
|
+
* OUT: images an answer shows (`` or `<img src>`) are sent as
|
|
11
|
+
* photos after its text, so a chart or a screenshot arrives as a picture
|
|
12
|
+
* instead of a path. Local images are only read from the session's own
|
|
13
|
+
* folder (or the system temp folder agents write screenshots to) — an answer
|
|
14
|
+
* cannot be used to pull an arbitrary file off the machine.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { existsSync, readFileSync, statSync } from 'fs';
|
|
18
|
+
import { tmpdir } from 'os';
|
|
19
|
+
import { basename, extname, isAbsolute, resolve } from 'path';
|
|
20
|
+
import type { MessageContent, UniversalMessage } from '@myrialabs/chatkit';
|
|
21
|
+
import { isPathInside } from '$backend/worktrees';
|
|
22
|
+
import { formatBytes } from '$backend/chat/attachments';
|
|
23
|
+
import { MAX_ATTACHMENT_BYTES } from '$shared/constants/attachments';
|
|
24
|
+
import { debug } from '$shared/utils/logger';
|
|
25
|
+
import { channelRuntime, type ActiveChannel } from './runtime';
|
|
26
|
+
import type { ChannelFile } from './platforms';
|
|
27
|
+
|
|
28
|
+
/** A file from a chat, shaped like a web composer attachment. */
|
|
29
|
+
export interface PromptAttachment {
|
|
30
|
+
type: 'image' | 'document';
|
|
31
|
+
mediaType: string;
|
|
32
|
+
/** base64 */
|
|
33
|
+
data: string;
|
|
34
|
+
title: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type MediaContent = Extract<MessageContent, { type: 'media' }>;
|
|
38
|
+
|
|
39
|
+
/** What a platform's own media kinds are when it does not say. */
|
|
40
|
+
const DEFAULT_MIME: Record<string, string> = {
|
|
41
|
+
image: 'image/jpeg',
|
|
42
|
+
sticker: 'image/webp',
|
|
43
|
+
video: 'video/mp4',
|
|
44
|
+
audio: 'audio/mpeg',
|
|
45
|
+
voice: 'audio/ogg',
|
|
46
|
+
document: 'application/octet-stream'
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const DEFAULT_NAME: Record<string, string> = {
|
|
50
|
+
image: 'photo.jpg',
|
|
51
|
+
sticker: 'sticker.webp',
|
|
52
|
+
video: 'video.mp4',
|
|
53
|
+
audio: 'audio.mp3',
|
|
54
|
+
voice: 'voice-note.ogg',
|
|
55
|
+
document: 'file'
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** At most this many images go out with one answer. */
|
|
59
|
+
const MAX_ANSWER_IMAGES = 10;
|
|
60
|
+
|
|
61
|
+
/** How long fetching a remote image may take before it is skipped. */
|
|
62
|
+
const FETCH_TIMEOUT_MS = 15_000;
|
|
63
|
+
|
|
64
|
+
const IMAGE_EXTENSIONS: Record<string, string> = {
|
|
65
|
+
'.png': 'image/png',
|
|
66
|
+
'.jpg': 'image/jpeg',
|
|
67
|
+
'.jpeg': 'image/jpeg',
|
|
68
|
+
'.gif': 'image/gif',
|
|
69
|
+
'.webp': 'image/webp',
|
|
70
|
+
'.bmp': 'image/bmp',
|
|
71
|
+
'.svg': 'image/svg+xml'
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export function isMedia(content: MessageContent): content is MediaContent {
|
|
75
|
+
return content.type === 'media';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Read every file of `messages` out of ChatKit and into prompt blocks. A file
|
|
80
|
+
* that never arrived (too big for the platform to hand a bot, a failed
|
|
81
|
+
* download) is reported, not silently dropped.
|
|
82
|
+
*/
|
|
83
|
+
export async function collectAttachments(
|
|
84
|
+
channel: ActiveChannel,
|
|
85
|
+
messages: UniversalMessage[]
|
|
86
|
+
): Promise<{ attachments: PromptAttachment[]; problems: string[] }> {
|
|
87
|
+
const attachments: PromptAttachment[] = [];
|
|
88
|
+
const problems: string[] = [];
|
|
89
|
+
for (const message of messages) {
|
|
90
|
+
if (!isMedia(message.content)) continue;
|
|
91
|
+
const content = message.content;
|
|
92
|
+
const name = content.filename || DEFAULT_NAME[content.media_type] || 'file';
|
|
93
|
+
const file = await channelRuntime.takeMedia(content.url);
|
|
94
|
+
if (!file) {
|
|
95
|
+
const size = content.size_bytes ?? 0;
|
|
96
|
+
problems.push(
|
|
97
|
+
size > channel.platform.maxInboundFileBytes
|
|
98
|
+
? `${name} is ${formatBytes(size)}, and a bot can only receive files up to ${formatBytes(channel.platform.maxInboundFileBytes)}.`
|
|
99
|
+
: `${name} could not be downloaded.`
|
|
100
|
+
);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (file.data.byteLength > MAX_ATTACHMENT_BYTES) {
|
|
104
|
+
problems.push(`${name} is ${formatBytes(file.data.byteLength)}, over the limit of ${formatBytes(MAX_ATTACHMENT_BYTES)}.`);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const mediaType = content.mime || file.mime || DEFAULT_MIME[content.media_type] || 'application/octet-stream';
|
|
108
|
+
attachments.push({
|
|
109
|
+
type: mediaType.startsWith('image/') ? 'image' : 'document',
|
|
110
|
+
mediaType,
|
|
111
|
+
data: Buffer.from(file.data).toString('base64'),
|
|
112
|
+
title: file.filename || name
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return { attachments, problems };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The text a chat message carries: its text, or a file's caption. */
|
|
119
|
+
export function textOf(content: MessageContent): string {
|
|
120
|
+
if (content.type === 'text') return content.text;
|
|
121
|
+
if (content.type === 'media') return content.caption ?? '';
|
|
122
|
+
if (content.type === 'location') return `📍 Location: ${content.lat}, ${content.lng}${content.name ? ` (${content.name})` : ''}`;
|
|
123
|
+
if (content.type === 'contact') return `👤 Contact: ${content.name} ${content.phone}`.trim();
|
|
124
|
+
return '';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Prompt content in the web composer's order: files first, then the text. */
|
|
128
|
+
export function promptContent(text: string, attachments: PromptAttachment[]): unknown[] {
|
|
129
|
+
const blocks: unknown[] = attachments.map((file) => ({ type: file.type, mediaType: file.mediaType, data: file.data, title: file.title }));
|
|
130
|
+
if (text.trim() || blocks.length === 0) blocks.push({ type: 'text', text });
|
|
131
|
+
return blocks;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// ── Images in an answer ─────────────────────────────────────────────────────
|
|
135
|
+
|
|
136
|
+
const MARKDOWN_IMAGE = /!\[([^\]]*)\]\(\s*<?([^)\s>]+)>?(?:\s+["'][^"']*["'])?\s*\)/g;
|
|
137
|
+
const HTML_IMAGE = /<img\b[^>]*?\bsrc\s*=\s*["']([^"']+)["'][^>]*?(?:\balt\s*=\s*["']([^"']*)["'])?[^>]*>/gi;
|
|
138
|
+
|
|
139
|
+
interface ImageRef {
|
|
140
|
+
match: string;
|
|
141
|
+
alt: string;
|
|
142
|
+
src: string;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function imageRefs(markdown: string): ImageRef[] {
|
|
146
|
+
const refs: ImageRef[] = [];
|
|
147
|
+
for (const match of markdown.matchAll(MARKDOWN_IMAGE)) refs.push({ match: match[0], alt: match[1], src: match[2] });
|
|
148
|
+
for (const match of markdown.matchAll(HTML_IMAGE)) refs.push({ match: match[0], alt: match[2] ?? '', src: match[1] });
|
|
149
|
+
return refs;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function fetchImage(url: string): Promise<{ data: Uint8Array; mime: string } | null> {
|
|
153
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
|
154
|
+
if (!response.ok) return null;
|
|
155
|
+
const mime = (response.headers.get('content-type') ?? '').split(';')[0].trim();
|
|
156
|
+
if (!mime.startsWith('image/')) return null;
|
|
157
|
+
const length = Number(response.headers.get('content-length') ?? 0);
|
|
158
|
+
if (length > MAX_ATTACHMENT_BYTES) return null;
|
|
159
|
+
const data = new Uint8Array(await response.arrayBuffer());
|
|
160
|
+
return data.byteLength > MAX_ATTACHMENT_BYTES ? null : { data, mime };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function readLocalImage(src: string, root: string): { data: Uint8Array; mime: string; name: string } | null {
|
|
164
|
+
let path = src;
|
|
165
|
+
try {
|
|
166
|
+
if (src.startsWith('file://')) path = decodeURIComponent(new URL(src).pathname);
|
|
167
|
+
else path = decodeURIComponent(src);
|
|
168
|
+
} catch {
|
|
169
|
+
// Not URI-encoded: use it as written.
|
|
170
|
+
}
|
|
171
|
+
const full = isAbsolute(path) ? resolve(path) : resolve(root, path);
|
|
172
|
+
if (!isPathInside(root, full) && !isPathInside(tmpdir(), full)) return null;
|
|
173
|
+
const mime = IMAGE_EXTENSIONS[extname(full).toLowerCase()];
|
|
174
|
+
if (!mime || !existsSync(full)) return null;
|
|
175
|
+
const stats = statSync(full);
|
|
176
|
+
if (!stats.isFile() || stats.size > MAX_ATTACHMENT_BYTES) return null;
|
|
177
|
+
return { data: readFileSync(full), mime, name: basename(full) };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function decodeDataUri(src: string): { data: Uint8Array; mime: string } | null {
|
|
181
|
+
const match = /^data:(image\/[\w.+-]+);base64,(.+)$/i.exec(src);
|
|
182
|
+
return match ? { data: Buffer.from(match[2], 'base64'), mime: match[1].toLowerCase() } : null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* The images `markdown` shows, as files to send, and the markdown with each
|
|
187
|
+
* one that was found replaced by a short marker — the picture follows, so the
|
|
188
|
+
* path would only be noise. Images that cannot be had are left as written.
|
|
189
|
+
*/
|
|
190
|
+
export async function answerImages(markdown: string, root: string | null): Promise<{ markdown: string; images: ChannelFile[] }> {
|
|
191
|
+
const images: ChannelFile[] = [];
|
|
192
|
+
let text = markdown;
|
|
193
|
+
for (const ref of imageRefs(markdown).slice(0, MAX_ANSWER_IMAGES)) {
|
|
194
|
+
try {
|
|
195
|
+
let found: { data: Uint8Array; mime: string; name?: string } | null = null;
|
|
196
|
+
if (/^data:/i.test(ref.src)) found = decodeDataUri(ref.src);
|
|
197
|
+
else if (/^https?:\/\//i.test(ref.src)) found = await fetchImage(ref.src);
|
|
198
|
+
else if (root) found = readLocalImage(ref.src, root);
|
|
199
|
+
if (!found) continue;
|
|
200
|
+
const filename = found.name ?? (basename(ref.src.split('?')[0]) || 'image');
|
|
201
|
+
images.push({ data: found.data, mime: found.mime, filename, caption: ref.alt.trim() || undefined });
|
|
202
|
+
text = text.replace(ref.match, `🖼️ ${ref.alt.trim() || filename}`);
|
|
203
|
+
} catch (error) {
|
|
204
|
+
debug.log('chat-apps', 'An image in an answer could not be sent:', error);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return { markdown: text, images };
|
|
208
|
+
}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The wording and the button protocol — the two things a phone sees.
|
|
3
|
+
*
|
|
4
|
+
* The answer shape matters most: the engine receives exactly what the web UI's
|
|
5
|
+
* form produces, so it cannot tell (and must not care) which side answered.
|
|
6
|
+
* And cards are runs, not Markdown: a project or session name full of
|
|
7
|
+
* asterisks is shown as typed.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { describe, it, expect } from 'bun:test';
|
|
11
|
+
import type { TextRun } from '@myrialabs/chatkit';
|
|
12
|
+
import type { AskUserQuestion } from '$shared/types/unified';
|
|
13
|
+
import type { ChannelCard } from './platforms';
|
|
14
|
+
import { excerptMarkdown } from '$backend/chat/turn-answer';
|
|
15
|
+
import {
|
|
16
|
+
answerFromSelection,
|
|
17
|
+
answerRuns,
|
|
18
|
+
confirmCard,
|
|
19
|
+
decodeButtonData,
|
|
20
|
+
describeToolUse,
|
|
21
|
+
encodeButtonData,
|
|
22
|
+
failedRuns,
|
|
23
|
+
stoppedRuns,
|
|
24
|
+
formatDuration,
|
|
25
|
+
headerLine,
|
|
26
|
+
menuCard,
|
|
27
|
+
progressCard,
|
|
28
|
+
questionAnsweredCard,
|
|
29
|
+
questionCard,
|
|
30
|
+
questionClosedCard,
|
|
31
|
+
type QuestionPayload
|
|
32
|
+
} from './messages';
|
|
33
|
+
|
|
34
|
+
const text = (runs: TextRun[]) => runs.map((run) => run.text).join('');
|
|
35
|
+
const cardText = (card: ChannelCard) => text(card.runs);
|
|
36
|
+
|
|
37
|
+
const single: AskUserQuestion = {
|
|
38
|
+
question: 'Which database should the migration target?',
|
|
39
|
+
header: 'Database',
|
|
40
|
+
multiSelect: false,
|
|
41
|
+
options: [
|
|
42
|
+
{ label: 'Postgres', description: 'The production engine' },
|
|
43
|
+
{ label: 'SQLite', description: 'The local fallback' }
|
|
44
|
+
]
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const multi: AskUserQuestion = {
|
|
48
|
+
...single,
|
|
49
|
+
question: 'Which environments?',
|
|
50
|
+
multiSelect: true,
|
|
51
|
+
options: [
|
|
52
|
+
{ label: 'Staging', description: '' },
|
|
53
|
+
{ label: 'Production', description: '' },
|
|
54
|
+
{ label: 'Preview', description: '' }
|
|
55
|
+
]
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
function payload(question: AskUserQuestion, extra: Partial<QuestionPayload> = {}): QuestionPayload {
|
|
59
|
+
return { question, index: 0, total: 1, context: { projectName: 'shop', sessionTitle: 'Migrate orders' }, selected: [], ...extra };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function buttonData(card: ChannelCard): string[] {
|
|
63
|
+
return (card.buttons ?? []).flat().flatMap((button) => ('data' in button ? [button.data] : []));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
describe('button data', () => {
|
|
67
|
+
it('round-trips every action', () => {
|
|
68
|
+
expect(decodeButtonData(encodeButtonData('AbC123xyZ9', { type: 'option', index: 2 }))).toEqual({ rowId: 'AbC123xyZ9', action: { type: 'option', index: 2 } });
|
|
69
|
+
expect(decodeButtonData(encodeButtonData('AbC123xyZ9', { type: 'submit' }))?.action).toEqual({ type: 'submit' });
|
|
70
|
+
expect(decodeButtonData(encodeButtonData('AbC123xyZ9', { type: 'other' }))?.action).toEqual({ type: 'other' });
|
|
71
|
+
expect(decodeButtonData(encodeButtonData('AbC123xyZ9', { type: 'confirm' }))?.action).toEqual({ type: 'confirm' });
|
|
72
|
+
expect(decodeButtonData(encodeButtonData('AbC123xyZ9', { type: 'cancel' }))?.action).toEqual({ type: 'cancel' });
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('rejects anything that is not one of ours', () => {
|
|
76
|
+
for (const data of ['', 'a:1', 'AbC123xyZ9', 'AbC123xyZ9:x', 'AbC123xyZ9:1:2', '../../etc:1', 'AbC123xyZ9:-1']) {
|
|
77
|
+
expect(decodeButtonData(data)).toBeNull();
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('stays inside a Telegram button even for a long option list', () => {
|
|
82
|
+
const many: AskUserQuestion = { ...single, options: Array.from({ length: 120 }, (_, i) => ({ label: `Option ${i}`, description: '' })) };
|
|
83
|
+
for (const data of buttonData(questionCard('AbC123xyZ9', payload(many)))) {
|
|
84
|
+
expect(new TextEncoder().encode(data).byteLength).toBeLessThanOrEqual(64);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
describe('answers', () => {
|
|
90
|
+
it('match the web form: labels joined by a comma, a custom answer winning on single-select', () => {
|
|
91
|
+
expect(answerFromSelection(single, [1])).toBe('SQLite');
|
|
92
|
+
expect(answerFromSelection(single, [], 'MySQL please')).toBe('MySQL please');
|
|
93
|
+
expect(answerFromSelection(single, [0], 'MySQL please')).toBe('MySQL please');
|
|
94
|
+
expect(answerFromSelection(multi, [2, 0])).toBe('Staging, Preview');
|
|
95
|
+
expect(answerFromSelection(multi, [0], 'QA')).toBe('Staging, QA');
|
|
96
|
+
expect(answerFromSelection(multi, [])).toBe('');
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('ignores an option index that does not exist', () => {
|
|
100
|
+
expect(answerFromSelection(single, [7, 0])).toBe('Postgres');
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
describe('header', () => {
|
|
105
|
+
it('leads with the project, then the session', () => {
|
|
106
|
+
expect(text(headerLine({ projectName: 'shop', sessionTitle: 'Migrate orders' }))).toBe('📁 shop · Migrate orders');
|
|
107
|
+
expect(headerLine({ projectName: 'shop', sessionTitle: 'x' })[1]).toMatchObject({ text: 'shop', bold: true });
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('shows names as typed — never parsed as Markdown', () => {
|
|
111
|
+
const runs = headerLine({ projectName: '**not bold**', sessionTitle: '_raw_' });
|
|
112
|
+
expect(text(runs)).toBe('📁 **not bold** · _raw_');
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('keeps a long title to one line', () => {
|
|
116
|
+
expect(text(headerLine({ projectName: 'p', sessionTitle: 'x'.repeat(300) })).length).toBeLessThan(80);
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
describe('question cards', () => {
|
|
121
|
+
it('a single-select question is one button per option, then Other to type an answer, no submit', () => {
|
|
122
|
+
const card = questionCard('AbC123xyZ9', payload(single));
|
|
123
|
+
expect(cardText(card)).toContain('Which database should the migration target?');
|
|
124
|
+
expect(cardText(card)).toContain('📁 shop · Migrate orders');
|
|
125
|
+
expect(cardText(card)).toContain('1. Postgres: The production engine');
|
|
126
|
+
expect(buttonData(card)).toEqual(['AbC123xyZ9:0', 'AbC123xyZ9:1', 'AbC123xyZ9:o']);
|
|
127
|
+
expect((card.buttons ?? []).flat().at(-1)?.label).toBe('✏️ Other…');
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('a multi-select question is checkboxes, an Other box, and Submit counting both', () => {
|
|
131
|
+
const card = questionCard('AbC123xyZ9', payload(multi, { selected: [1] }));
|
|
132
|
+
expect((card.buttons ?? []).flat().map((button) => button.label)).toEqual(['⬜ Staging', '☑️ Production', '⬜ Preview', '⬜ Other…', 'Submit (1)']);
|
|
133
|
+
expect(buttonData(card).at(-1)).toBe('AbC123xyZ9:s');
|
|
134
|
+
|
|
135
|
+
const withOther = questionCard('AbC123xyZ9', payload(multi, { selected: [1], custom: 'Canary' }));
|
|
136
|
+
expect((withOther.buttons ?? []).flat().map((button) => button.label).slice(-2)).toEqual(['☑️ Other: Canary', 'Submit (2)']);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it('says when it is waiting for a typed answer', () => {
|
|
140
|
+
const card = questionCard('AbC123xyZ9', payload(single), { typing: true });
|
|
141
|
+
expect(cardText(card)).toContain('Type your answer');
|
|
142
|
+
expect((card.buttons ?? []).flat().at(-1)?.label).toBe('✏️ Other (typing…)');
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it('counts sibling questions and offers a way back into Clopen when there is one', () => {
|
|
146
|
+
const card = questionCard('AbC123xyZ9', payload(single, { index: 1, total: 3, openUrl: 'https://x.trycloudflare.com/#session/p/s' }));
|
|
147
|
+
expect(cardText(card)).toContain('(2 of 3)');
|
|
148
|
+
expect((card.buttons ?? []).flat().some((button) => 'url' in button)).toBe(true);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it('settled cards keep the question but lose every option button', () => {
|
|
152
|
+
for (const card of [
|
|
153
|
+
questionAnsweredCard(payload(single), 'SQLite', 1),
|
|
154
|
+
questionClosedCard(payload(single), 'answered-elsewhere'),
|
|
155
|
+
questionClosedCard(payload(single), 'run-ended')
|
|
156
|
+
]) {
|
|
157
|
+
expect(cardText(card)).toContain('Which database');
|
|
158
|
+
expect(buttonData(card)).toEqual([]);
|
|
159
|
+
}
|
|
160
|
+
expect(cardText(questionAnsweredCard(payload(single), 'SQLite', 1))).toContain('1 more question to go');
|
|
161
|
+
});
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
describe('turn output', () => {
|
|
165
|
+
it('an answer is formatted Markdown, not literal asterisks', () => {
|
|
166
|
+
const runs = answerRuns({ markdown: 'Done — **3 files** changed:\n\n```ts\nconst a = 1;\n```', context: {}, showHeader: false });
|
|
167
|
+
expect(text(runs)).toBe('Done — 3 files changed:\n\nconst a = 1;');
|
|
168
|
+
expect(runs.find((run) => run.bold)?.text).toBe('3 files');
|
|
169
|
+
expect(runs.find((run) => run.pre)).toMatchObject({ language: 'ts' });
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('an answer carries the header only when asked to', () => {
|
|
173
|
+
expect(text(answerRuns({ markdown: 'hi', context: { projectName: 'shop' }, showHeader: true }))).toBe('📁 shop\n\nhi');
|
|
174
|
+
expect(text(answerRuns({ markdown: 'hi', context: { projectName: 'shop' }, showHeader: false }))).toBe('hi');
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it('an excerpt never ends inside a code block', () => {
|
|
178
|
+
const long = `Intro\n\n\`\`\`ts\n${'line\n'.repeat(400)}\`\`\``;
|
|
179
|
+
const excerpt = excerptMarkdown(long, 300);
|
|
180
|
+
expect((excerpt.match(/```/g) ?? []).length % 2).toBe(0);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it('the progress line names what the turn is doing', () => {
|
|
184
|
+
expect(cardText(progressCard({ elapsedMs: 65_000, activity: 'Edit src/app.ts', steps: 3 }))).toBe('⏳ Working · 1m 5s · 3 steps\nEdit src/app.ts');
|
|
185
|
+
expect(describeToolUse('Bash', { command: 'bun test\nmore' })).toBe('Bash bun test');
|
|
186
|
+
expect(describeToolUse('TodoWrite', {})).toBe('TodoWrite');
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it('formats durations at every scale', () => {
|
|
190
|
+
expect(formatDuration(4_000)).toBe('4s');
|
|
191
|
+
expect(formatDuration(61_000)).toBe('1m 1s');
|
|
192
|
+
expect(formatDuration(3_725_000)).toBe('1h 2m');
|
|
193
|
+
});
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
describe('menus and confirmations', () => {
|
|
197
|
+
it('a menu is one button per item, marking the current one', () => {
|
|
198
|
+
const card = menuCard('AbC123xyZ9', [{ text: 'Pick' }], [{ label: 'Home' }, { label: 'shop', current: true }]);
|
|
199
|
+
expect((card.buttons ?? []).flat().map((button) => button.label)).toEqual(['Home', '✓ shop']);
|
|
200
|
+
expect(buttonData(card)).toEqual(['AbC123xyZ9:0', 'AbC123xyZ9:1']);
|
|
201
|
+
expect(cardText(card)).toContain('2. shop ✓');
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it('a long menu lists its items only as buttons', () => {
|
|
205
|
+
const items = Array.from({ length: 30 }, (_, i) => ({ label: `model-${i}` }));
|
|
206
|
+
const card = menuCard('AbC123xyZ9', [{ text: 'Models' }], items);
|
|
207
|
+
expect(cardText(card)).toBe('Models');
|
|
208
|
+
expect(card.buttons).toHaveLength(30);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it('a confirmation has a go and a cancel', () => {
|
|
212
|
+
expect(buttonData(confirmCard('AbC123xyZ9', { title: 't', detail: 'd', confirmLabel: 'Go' }))).toEqual(['AbC123xyZ9:y', 'AbC123xyZ9:n']);
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
describe('a turn that did not finish', () => {
|
|
217
|
+
const text = (runs: TextRun[]) => runs.map((run) => run.text).join('');
|
|
218
|
+
|
|
219
|
+
it('shows what it said before failing, then the failure — never as a finished answer', () => {
|
|
220
|
+
const out = text(failedRuns({ context: {}, showHeader: false, reason: 'rate limited', partial: 'Half of the work' }));
|
|
221
|
+
expect(out.indexOf('Half of the work')).toBeLessThan(out.indexOf('failed before it finished'));
|
|
222
|
+
expect(out).toContain('rate limited');
|
|
223
|
+
expect(text(failedRuns({ context: {}, showHeader: false }))).toContain('The run failed.');
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it('marks a stopped answer as stopped', () => {
|
|
227
|
+
expect(text(stoppedRuns({ context: {}, showHeader: false, partial: 'So far' }))).toMatch(/So far[\s\S]*Stopped/);
|
|
228
|
+
});
|
|
229
|
+
});
|