@datagrok/grokky 1.0.4 → 1.1.0
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/.claude/skills/deploy-grokky/SKILL.md +193 -0
- package/.grokignore +2 -0
- package/.turbo/turbo-build.log +24 -0
- package/.vscode/settings.json +16 -0
- package/CHANGELOG.md +151 -8
- package/CLAUDE.md +284 -0
- package/CREDITS.md +173 -0
- package/LICENSE.md +16 -0
- package/README.md +24 -0
- package/bdd/bdd.config.json +1 -0
- package/bdd/bindings/elements.ts +9 -0
- package/bdd/bindings/steps.ts +787 -0
- package/bdd/features/ai-panel/platform-work.feature +63 -0
- package/bdd/features/ai-panel/session.feature +69 -0
- package/bdd/features/ai-panel/table-work.feature +99 -0
- package/bdd/generated/ai-panel/platform-work.test.ts +103 -0
- package/bdd/generated/ai-panel/session.test.ts +100 -0
- package/bdd/generated/ai-panel/table-work.test.ts +150 -0
- package/bdd/package.json +1 -0
- package/bdd/tsconfig.json +13 -0
- package/css/ai.css +637 -49
- package/dist/package-test.js +4 -1707
- package/dist/package-test.js.map +1 -1
- package/dist/package.js +742 -92317
- package/dist/package.js.map +1 -1
- package/dockerfiles/claude-runtime/.dockerignore +1 -0
- package/{.eslintrc.json → dockerfiles/claude-runtime/.eslintrc.json} +7 -16
- package/dockerfiles/claude-runtime/Dockerfile +73 -13
- package/dockerfiles/claude-runtime/agent/grokky_agent/__init__.py +0 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/__main__.py +80 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py +180 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/config.py +26 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/formats.py +155 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/guard.py +87 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.py +212 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.yaml +45 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/__init__.py +8 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/plugin.yaml +3 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/protocol.py +174 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/__init__.py +21 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/anthropic.py +21 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/azure.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/base.py +127 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/bedrock.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/custom.py +40 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/databricks.py +54 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openai_platform.py +41 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openrouter.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/session.py +471 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/skills.py +44 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/structured.py +40 -0
- package/dockerfiles/claude-runtime/container.json +2 -2
- package/dockerfiles/claude-runtime/entrypoint.sh +20 -0
- package/dockerfiles/claude-runtime/package-lock.json +1721 -306
- package/dockerfiles/claude-runtime/package.json +20 -5
- package/dockerfiles/claude-runtime/plugin/.claude-plugin/plugin.json +5 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-calc-column/SKILL.md +92 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-data/SKILL.md +250 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-toolkit/SKILL.md +395 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-df-and-columns/SKILL.md +454 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-entities/SKILL.md +38 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-exec/SKILL.md +209 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-filtering/SKILL.md +185 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-grid-customization/SKILL.md +270 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-projects/SKILL.md +100 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-selection/SKILL.md +344 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-undo/SKILL.md +78 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-viewers/SKILL.md +303 -0
- package/dockerfiles/claude-runtime/pyproject.toml +18 -0
- package/dockerfiles/claude-runtime/src/agent/pool.ts +411 -0
- package/dockerfiles/claude-runtime/src/agent/turn.ts +153 -0
- package/dockerfiles/claude-runtime/src/constants.ts +20 -0
- package/dockerfiles/claude-runtime/src/credentials.ts +45 -0
- package/dockerfiles/claude-runtime/src/grounding.ts +104 -0
- package/dockerfiles/claude-runtime/src/help-index.ts +118 -0
- package/dockerfiles/claude-runtime/src/privileges.ts +8 -0
- package/dockerfiles/claude-runtime/src/prompts.ts +211 -0
- package/dockerfiles/claude-runtime/src/server.ts +134 -234
- package/dockerfiles/claude-runtime/src/session.ts +328 -0
- package/dockerfiles/claude-runtime/src/shared-api-client.ts +112 -0
- package/dockerfiles/claude-runtime/src/stream-filter.ts +80 -0
- package/dockerfiles/claude-runtime/src/sync/home-files.ts +80 -0
- package/dockerfiles/claude-runtime/src/sync/orchestrator.ts +214 -0
- package/dockerfiles/claude-runtime/src/sync/packages.ts +145 -0
- package/dockerfiles/claude-runtime/src/sync/shared-connections.ts +87 -0
- package/dockerfiles/claude-runtime/src/sync/workspace.ts +68 -0
- package/dockerfiles/claude-runtime/src/tasks.ts +124 -0
- package/dockerfiles/claude-runtime/src/tool-summary.ts +66 -0
- package/dockerfiles/claude-runtime/src/types.ts +142 -23
- package/dockerfiles/claude-runtime/src/user/installed-packages.ts +17 -0
- package/dockerfiles/claude-runtime/src/user/staged-workspace.ts +80 -0
- package/dockerfiles/claude-runtime/src/user/user-dir.ts +108 -0
- package/dockerfiles/claude-runtime/src/verify.ts +136 -0
- package/dockerfiles/claude-runtime/src/watchdog.ts +115 -0
- package/dockerfiles/claude-runtime/test/credentials.test.js +43 -0
- package/dockerfiles/claude-runtime/test/grounding.test.js +191 -0
- package/dockerfiles/claude-runtime/test/help-index.test.js +115 -0
- package/dockerfiles/claude-runtime/test/plugin-skills.test.js +57 -0
- package/dockerfiles/claude-runtime/test/prompts.test.js +62 -0
- package/dockerfiles/claude-runtime/test/reaper.test.js +60 -0
- package/dockerfiles/claude-runtime/test/stream-filter.test.js +132 -0
- package/dockerfiles/claude-runtime/test/tasks.test.js +74 -0
- package/dockerfiles/claude-runtime/test/user-dir.test.js +71 -0
- package/dockerfiles/claude-runtime/test/verify.test.js +187 -0
- package/dockerfiles/claude-runtime/test/watchdog.test.js +43 -0
- package/dockerfiles/mcp-server/.eslintrc.json +39 -0
- package/dockerfiles/mcp-server/Dockerfile +10 -2
- package/dockerfiles/mcp-server/package-lock.json +1743 -98
- package/dockerfiles/mcp-server/package.json +27 -5
- package/dockerfiles/mcp-server/src/api-client.ts +123 -66
- package/dockerfiles/mcp-server/src/format.ts +51 -0
- package/dockerfiles/mcp-server/src/index.ts +44 -113
- package/dockerfiles/mcp-server/src/ops.ts +325 -0
- package/dockerfiles/mcp-server/src/shared-api-client.ts +81 -0
- package/dockerfiles/mcp-server/test/format.test.js +62 -0
- package/dockerfiles/mcp-server/test/ops.test.js +84 -0
- package/dockerfiles/mcp-server/test/shared-api-client.test.js +35 -0
- package/dockerfiles/queue/Dockerfile +2 -0
- package/dockerfiles/queue/container.json +7 -0
- package/docs/AUDIT-2026-08-03.md +1064 -0
- package/docs/BENCHMARK.md +292 -0
- package/docs/CLAUDE_CODE_FLOW.md +746 -0
- package/docs/EXAMPLES.md +82 -0
- package/docs/FEATURES.md +71 -0
- package/docs/IMPLEMENTATION.md +128 -0
- package/docs/LATENCY.md +170 -0
- package/docs/VISION.md +36 -0
- package/files/benchmark/suite.yaml +404 -0
- package/files/scripts/process-cro-results.md +14 -0
- package/files/suggestions.yaml +344 -0
- package/package.json +39 -97
- package/src/ai/ai-window.ts +157 -0
- package/src/ai/benchmark/benchmark.ts +737 -0
- package/src/ai/db-view-functions.ts +56 -0
- package/src/ai/engine.ts +98 -0
- package/src/ai/gemma-engine.ts +81 -0
- package/src/ai/panel.ts +1385 -0
- package/src/ai/prompt-suggestions.ts +209 -0
- package/src/ai/search/combined-search.ts +244 -0
- package/src/{llm-utils → ai/search}/query-matching.ts +46 -167
- package/src/{llm-utils → ai}/storage.ts +0 -1
- package/src/ai/table-tools.ts +145 -0
- package/src/ai/ui.ts +720 -0
- package/src/ai/usage-limiter.ts +105 -0
- package/src/ai/view-tools.ts +352 -0
- package/src/claude/ai-feature.ts +16 -0
- package/src/claude/exec-blocks.ts +176 -0
- package/src/claude/queue-task.ts +84 -0
- package/src/claude/runtime-client.ts +310 -0
- package/src/claude/turn-log.ts +114 -0
- package/src/claude/undoable.ts +105 -0
- package/src/{llm-utils → db}/db-index-tools.ts +24 -32
- package/src/db/sql-tools.ts +336 -0
- package/src/depr/LLM-client.ts +251 -0
- package/src/depr/ai-panel.ts +174 -0
- package/src/depr/chatgpt-assistant.ts +257 -0
- package/src/depr/creds.ts +30 -0
- package/src/depr/deepwikiclient.ts +118 -0
- package/src/depr/indexes/dg-repository-index.ts +266 -0
- package/src/depr/interfaces.ts +170 -0
- package/src/depr/is-help-request.ts +39 -0
- package/src/depr/prompt-engine.ts +52 -0
- package/src/depr/rendering-tools.ts +103 -0
- package/src/depr/script-tools.ts +785 -0
- package/src/depr/tableview-tools.ts +746 -0
- package/src/depr/viewers-ai.ts +67 -0
- package/src/package-api.ts +87 -28
- package/src/package-test.ts +1 -0
- package/src/package.g.ts +98 -48
- package/src/package.ts +211 -157
- package/src/polyfills.ts +12 -0
- package/src/utils.ts +128 -0
- package/tsconfig.json +8 -70
- package/webpack.config.js +3 -49
- package/.eslintignore +0 -2
- package/src/ai-panel.ts +0 -174
- package/src/claude-code/claude-panel.ts +0 -34
- package/src/claude-code/claude-runtime-client.ts +0 -148
- package/src/llm-utils/LLM-client.ts +0 -251
- package/src/llm-utils/combined-search.ts +0 -162
- package/src/llm-utils/creds.ts +0 -30
- package/src/llm-utils/deepwikiclient.ts +0 -118
- package/src/llm-utils/indexes/dg-repository-index.ts +0 -266
- package/src/llm-utils/panel.ts +0 -866
- package/src/llm-utils/script-tools.ts +0 -784
- package/src/llm-utils/sql-tools.ts +0 -840
- package/src/llm-utils/tableview-tools.ts +0 -704
- package/src/llm-utils/ui.ts +0 -315
- package/src/prompt-engine/chatgpt-assistant.ts +0 -257
- package/src/prompt-engine/interfaces.ts +0 -170
- package/src/prompt-engine/prompt-engine.ts +0 -52
- package/src/prompt-engine/rendering-tools.ts +0 -103
- package/src/prompts/is-help-request.ts +0 -26
- package/src/viewers-ai.ts +0 -67
- /package/src/{llm-utils → db}/indexes/biologics-index.ts +0 -0
- /package/src/{llm-utils → db}/indexes/chembl-index.ts +0 -0
- /package/src/{llm-utils → db}/query-meta-utils.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-chat-completions-provider.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-responses-provider.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/types.ts +0 -0
- /package/src/{llm-utils/depr → depr}/depr.ts +0 -0
- /package/src/{llm-utils/depr → depr}/embeddings.ts +0 -0
- /package/src/{llm-utils/depr → depr}/sql-utils.ts +0 -0
|
@@ -0,0 +1,787 @@
|
|
|
1
|
+
/* The AI panel's chat as a user drives it, against a live claude-runtime container and a real model.
|
|
2
|
+
A turn ends on the runtime's own terminal event (final, error or aborted) for the panel's session,
|
|
3
|
+
read from the runtime WebSocket, and the panel leaving its busy state; the socket closing first loses
|
|
4
|
+
the turn. The tap keeps each frame's type, socket, session and tool, a tool's one-line summary and an
|
|
5
|
+
error's text (both written by the runtime from the model's calls, key-shaped text redacted), a prompt's
|
|
6
|
+
mode and whether it carried the panel's saved transcript; not the prompt or the answer. */
|
|
7
|
+
import * as fs from 'node:fs';
|
|
8
|
+
import * as path from 'node:path';
|
|
9
|
+
import {randomUUID} from 'node:crypto';
|
|
10
|
+
import {execFileSync} from 'node:child_process';
|
|
11
|
+
import {fileURLToPath} from 'node:url';
|
|
12
|
+
import {type Page, type WebSocket, test} from '@playwright/test';
|
|
13
|
+
import {Given, Then, When} from '@datagrok-libraries/bdd';
|
|
14
|
+
import {atFeatureEnd, escapeRegExp, exactText, expect, pollMs, serverRequests} from '@datagrok-libraries/bdd/runtime';
|
|
15
|
+
import {AI_PANEL, AI_PROMPT_BOX} from './elements.js';
|
|
16
|
+
|
|
17
|
+
declare const grok: any;
|
|
18
|
+
|
|
19
|
+
const RUNTIME_WS = /\/docker\/containers\/proxy(-ws)?\/[^/]+\/ws\b/;
|
|
20
|
+
const TERMINAL = ['final', 'error', 'aborted'];
|
|
21
|
+
// A turn is a scenario's work, not a check: unlike pollMs, its budget is not narrowed in a @known-failure scenario.
|
|
22
|
+
const TURN_MS = Number(process.env.GROKKY_BDD_TURN_MS ?? 300000);
|
|
23
|
+
const SECRET_RE = /sk-(?:ant|proj|svcacct)-[\w-]{20,}|dapi[0-9a-f]{20}|Bearer\s+\S{20}/;
|
|
24
|
+
const SECRET_TEXT = /(sk-(?:ant|proj|svcacct)-|dapi[0-9a-f]{20}|Bearer\s+)\S*/g;
|
|
25
|
+
const RESTORED_TRANSCRIPT = '[Conversation restored from saved history';
|
|
26
|
+
const AGENT_PROCESS = /-m grokky_agent\b/;
|
|
27
|
+
const CANARY_DIRS = '/users/00000000-0000-4bdd-8000-';
|
|
28
|
+
const SHOTS = process.env.GROKKY_BDD_SHOTS ?? fileURLToPath(new URL('../test-results/screenshots', import.meta.url));
|
|
29
|
+
|
|
30
|
+
/* The terminal commands an agent ran for a turn, from its Hermes session store: the runtime's activity
|
|
31
|
+
summary of a terminal call is "Run a command". Arguments: the turn's start in the container's epoch
|
|
32
|
+
seconds, and the start of its prompt, which the store keeps in the user message. */
|
|
33
|
+
const TURN_COMMANDS = `
|
|
34
|
+
import glob, json, sqlite3, sys
|
|
35
|
+
since, prompt = float(sys.argv[1]), sys.argv[2]
|
|
36
|
+
for db in glob.glob('/var/lib/grokky/hermes/*/state.db') + glob.glob('/var/lib/grokky/hermes/parked/*/state.db'):
|
|
37
|
+
try:
|
|
38
|
+
c = sqlite3.connect('file:' + db + '?mode=ro', uri=True)
|
|
39
|
+
sessions = [r[0] for r in c.execute("select distinct session_id from messages where role = 'user' and timestamp >= ? and instr(content, ?) > 0", (since, prompt))]
|
|
40
|
+
calls = [r[0] for s in sessions for r in c.execute("select tool_calls from messages where session_id = ? and timestamp >= ? and tool_calls is not null", (s, since))]
|
|
41
|
+
except sqlite3.Error:
|
|
42
|
+
continue
|
|
43
|
+
for call in (x for listed in calls for x in json.loads(listed)):
|
|
44
|
+
f = call.get('function') or {}
|
|
45
|
+
if f.get('name') == 'terminal':
|
|
46
|
+
print(json.dumps(json.loads(f.get('arguments') or '{}').get('command', '')))
|
|
47
|
+
`;
|
|
48
|
+
|
|
49
|
+
interface Frame {
|
|
50
|
+
dir: 'in' | 'out';
|
|
51
|
+
type: string;
|
|
52
|
+
socket: number;
|
|
53
|
+
sessionId?: string;
|
|
54
|
+
tool?: string;
|
|
55
|
+
summary?: string;
|
|
56
|
+
error?: string;
|
|
57
|
+
mode?: string;
|
|
58
|
+
restored?: boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface PanelState {
|
|
62
|
+
busy: boolean;
|
|
63
|
+
responses: number;
|
|
64
|
+
lastText: string;
|
|
65
|
+
systemMessages: string[];
|
|
66
|
+
handledNatively: number;
|
|
67
|
+
question: boolean;
|
|
68
|
+
confirmCards: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
interface Turn {
|
|
72
|
+
prompt: string;
|
|
73
|
+
startedAt: number;
|
|
74
|
+
from: number;
|
|
75
|
+
before: PanelState;
|
|
76
|
+
sessionId?: string;
|
|
77
|
+
socket?: number;
|
|
78
|
+
native?: boolean;
|
|
79
|
+
end?: string;
|
|
80
|
+
error?: string;
|
|
81
|
+
answer: string;
|
|
82
|
+
question?: {options: string[]; picked: string};
|
|
83
|
+
confirmations: string[];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
interface Process {
|
|
87
|
+
pid: number;
|
|
88
|
+
cmd: string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
interface Canary {
|
|
92
|
+
note: string;
|
|
93
|
+
dir: string;
|
|
94
|
+
accessed: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
interface PageColumn {
|
|
98
|
+
name: string;
|
|
99
|
+
type: string;
|
|
100
|
+
isNumerical: boolean;
|
|
101
|
+
get(row: number): number | string;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interface PageTable {
|
|
105
|
+
name: string;
|
|
106
|
+
rowCount: number;
|
|
107
|
+
dart: unknown;
|
|
108
|
+
columns: {names(): string[]; toList(): PageColumn[]};
|
|
109
|
+
get(column: string, row: number): number;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const taps = new WeakMap<Page, Frame[]>();
|
|
113
|
+
const turns = new WeakMap<Page, Turn[]>();
|
|
114
|
+
const containers = new WeakMap<Page, string>();
|
|
115
|
+
const canaries = new WeakMap<Page, Canary>();
|
|
116
|
+
|
|
117
|
+
function tapOf(page: Page): Frame[] {
|
|
118
|
+
const frames = taps.get(page);
|
|
119
|
+
if (!frames)
|
|
120
|
+
throw new Error('the runtime WebSocket is not recorded: put "Given the AI runtime traffic is recorded" in the Background, before "user is logged in"');
|
|
121
|
+
return frames;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function turnsOf(page: Page): Turn[] {
|
|
125
|
+
const list = turns.get(page) ?? [];
|
|
126
|
+
turns.set(page, list);
|
|
127
|
+
return list;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function lastTurn(page: Page): Turn {
|
|
131
|
+
const list = turnsOf(page);
|
|
132
|
+
if (list.length === 0)
|
|
133
|
+
throw new Error('no prompt was sent to the AI panel in this scenario');
|
|
134
|
+
return list[list.length - 1];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const panel = (page: Page): Promise<PanelState> => page.evaluate((sel) => {
|
|
138
|
+
const roots = Array.from(document.querySelectorAll(sel)) as HTMLElement[];
|
|
139
|
+
const root = roots.find((p) => p.offsetParent !== null) ?? roots[0];
|
|
140
|
+
if (!root)
|
|
141
|
+
throw new Error('the AI panel is not on the page');
|
|
142
|
+
const responses = Array.from(root.querySelectorAll('.d4-ai-panel-output-area .d4-ai-assistant-response-container')) as HTMLElement[];
|
|
143
|
+
const submit = (Array.from(root.querySelectorAll('.d4-ai-panel-output-area button')) as HTMLButtonElement[])
|
|
144
|
+
.find((b) => b.textContent!.trim().toLowerCase() === 'submit' && !b.disabled);
|
|
145
|
+
return {
|
|
146
|
+
busy: !!root.querySelector('.d4-ai-panel-run-controls .fa-stop'),
|
|
147
|
+
responses: responses.length,
|
|
148
|
+
lastText: responses.length ? responses[responses.length - 1].innerText.trim() : '',
|
|
149
|
+
systemMessages: (Array.from(root.querySelectorAll('.grokky-system-message')) as HTMLElement[]).map((e) => e.innerText.trim()),
|
|
150
|
+
handledNatively: root.querySelectorAll('.d4-ai-handled-natively-icon').length,
|
|
151
|
+
question: !!submit,
|
|
152
|
+
confirmCards: root.querySelectorAll('.d4-ai-panel-output-area .grokky-confirm-card').length,
|
|
153
|
+
};
|
|
154
|
+
}, AI_PANEL);
|
|
155
|
+
|
|
156
|
+
function framesOf(page: Page, turn: Turn): Frame[] {
|
|
157
|
+
const frames = tapOf(page).slice(turn.from);
|
|
158
|
+
const sent = frames.find((f) => f.dir === 'out' && f.type === 'user_message');
|
|
159
|
+
turn.sessionId ??= sent?.sessionId;
|
|
160
|
+
turn.socket ??= sent?.socket;
|
|
161
|
+
return turn.sessionId ? frames.filter((f) => f.sessionId === turn.sessionId) : [];
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const toolsOf = (page: Page, turn: Turn): string[] => framesOf(page, turn)
|
|
165
|
+
.filter((f) => f.dir === 'in' && (f.type === 'tool_activity' || f.type === 'input_request')).map((f) => f.tool ?? '?');
|
|
166
|
+
|
|
167
|
+
async function sendPrompt(page: Page, prompt: string): Promise<Turn> {
|
|
168
|
+
test.info().setTimeout(test.info().timeout + TURN_MS);
|
|
169
|
+
const turn: Turn = {prompt, startedAt: Date.now(), from: tapOf(page).length, before: await panel(page), answer: '', confirmations: []};
|
|
170
|
+
turnsOf(page).push(turn);
|
|
171
|
+
const box = page.locator(AI_PROMPT_BOX).filter({visible: true}).first();
|
|
172
|
+
await box.fill(prompt);
|
|
173
|
+
await box.press('Enter');
|
|
174
|
+
await expect.poll(async () => {
|
|
175
|
+
turn.native = (await panel(page)).handledNatively > turn.before.handledNatively;
|
|
176
|
+
return turn.native || framesOf(page, turn).length > 0;
|
|
177
|
+
}, {message: 'the panel handed the prompt to the platform\'s interpreter or to the runtime', timeout: 30000}).toBe(true);
|
|
178
|
+
return turn;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function requireRuntime(turn: Turn): Turn {
|
|
182
|
+
if (turn.native)
|
|
183
|
+
throw new Error('the platform\'s own prompt interpreter handled the prompt, so the runtime was never called; reword it');
|
|
184
|
+
return turn;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function turnStatus(page: Page, turn: Turn): Promise<'pending' | 'question' | 'confirm' | 'done' | 'lost'> {
|
|
188
|
+
const s = await panel(page);
|
|
189
|
+
if (s.question)
|
|
190
|
+
return 'question';
|
|
191
|
+
if (s.confirmCards - turn.before.confirmCards > turn.confirmations.length)
|
|
192
|
+
return 'confirm';
|
|
193
|
+
const end = framesOf(page, turn).find((f) => f.dir === 'in' && TERMINAL.includes(f.type));
|
|
194
|
+
if (end && !s.busy) {
|
|
195
|
+
turn.end = end.type;
|
|
196
|
+
turn.error = end.error;
|
|
197
|
+
turn.answer = s.responses > turn.before.responses || s.lastText !== turn.before.lastText ? s.lastText : '';
|
|
198
|
+
return 'done';
|
|
199
|
+
}
|
|
200
|
+
return !end && tapOf(page).slice(turn.from).some((f) => f.type === 'close' && f.socket === turn.socket) ? 'lost' : 'pending';
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
interface Answers {
|
|
204
|
+
question?: () => Promise<void>;
|
|
205
|
+
confirm?: () => Promise<void>;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function waitTurn(page: Page, turn: Turn, answers: Answers = {}): Promise<void> {
|
|
209
|
+
while (!turn.native) {
|
|
210
|
+
let status = 'pending';
|
|
211
|
+
await expect.poll(async () => (status = await turnStatus(page, turn)),
|
|
212
|
+
{message: `the AI turn "${turn.prompt.slice(0, 60)}" ended`, timeout: TURN_MS}).not.toBe('pending');
|
|
213
|
+
if (status === 'lost')
|
|
214
|
+
throw new Error('the runtime WebSocket closed before the turn ended: the runtime drops the turns of a closed connection');
|
|
215
|
+
if (status === 'done' && turn.end === 'error')
|
|
216
|
+
throw new Error(`the AI turn ended in an error: ${turn.error}`);
|
|
217
|
+
if (status === 'done')
|
|
218
|
+
return;
|
|
219
|
+
const answer = status === 'question' ? answers.question : answers.confirm;
|
|
220
|
+
if (!answer)
|
|
221
|
+
throw new Error(`the AI asked for ${status === 'question' ? 'an answer (AskUserQuestion form)' : 'a confirmation (confirm card)'} that this step does not give`);
|
|
222
|
+
await answer();
|
|
223
|
+
if (status === 'question')
|
|
224
|
+
answers.question = undefined;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Every question of the form is answered: the option matching the pattern where one does, else its first. */
|
|
229
|
+
async function answerQuestion(page: Page, turn: Turn, option: RegExp): Promise<void> {
|
|
230
|
+
const form = page.locator(`${AI_PANEL} .d4-ai-panel-output-area`).filter({visible: true}).first();
|
|
231
|
+
const offered: string[][] = [];
|
|
232
|
+
for (const select of await form.locator('select').filter({visible: true}).all()) {
|
|
233
|
+
const options = (await select.locator('option').allTextContents()).map((o) => o.trim());
|
|
234
|
+
offered.push(options);
|
|
235
|
+
const picked = options.find((o) => option.test(o));
|
|
236
|
+
turn.question ??= picked ? {options, picked} : undefined;
|
|
237
|
+
await select.selectOption({label: picked ?? options[0]});
|
|
238
|
+
}
|
|
239
|
+
if (!turn.question)
|
|
240
|
+
throw new Error(`the AI's questions offer no option matching ${option}; they offer: ${offered.map((o) => o.join(', ')).join(' | ')}`);
|
|
241
|
+
await form.locator('button', {hasText: /^\s*submit\s*$/i}).filter({visible: true}).last().click();
|
|
242
|
+
await expect.poll(async () => (await panel(page)).question, {message: 'the question form was submitted'}).toBe(false);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function answerConfirmation(page: Page, turn: Turn, button: string): Promise<void> {
|
|
246
|
+
const card = page.locator(`${AI_PANEL} .grokky-confirm-card`).filter({visible: true}).last();
|
|
247
|
+
turn.confirmations.push((await card.innerText()).trim());
|
|
248
|
+
await card.locator('button', {hasText: exactText(button)}).click();
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function answerOf(turn: Turn): string {
|
|
252
|
+
if (turn.native)
|
|
253
|
+
throw new Error('the platform\'s own prompt interpreter took the prompt: the AI never answered it');
|
|
254
|
+
expect(turn.end, 'how the turn ended').toBe('final');
|
|
255
|
+
return turn.answer;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Some number of the answer within the tolerance: a model shows its working even when asked for the number alone. */
|
|
259
|
+
function expectNumberIn(answer: string, want: number, tolerance: number, what: string): void {
|
|
260
|
+
const numbers = (answer.match(/-?\d+(?:\.\d+)?/g) ?? []).map(Number);
|
|
261
|
+
expect(numbers.some((n) => Math.abs(n - want) < tolerance),
|
|
262
|
+
`${what}, ${want.toFixed(3)}, among the numbers of the answer: ${numbers.join(', ') || 'none'}`).toBe(true);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function median(xs: number[]): number {
|
|
266
|
+
xs.sort((a, b) => a - b);
|
|
267
|
+
const n = xs.length;
|
|
268
|
+
return n % 2 ? xs[(n - 1) / 2] : (xs[n / 2 - 1] + xs[n / 2]) / 2;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Missing values left out. */
|
|
272
|
+
const columnMedian = async (page: Page, column: string): Promise<number> => median(await page.evaluate((name) => {
|
|
273
|
+
const c = grok.shell.t?.col(name);
|
|
274
|
+
if (!c)
|
|
275
|
+
throw new Error(`the current table has no "${name}" column`);
|
|
276
|
+
const values: number[] = [];
|
|
277
|
+
for (let i = 0; i < c.length; i++) {
|
|
278
|
+
if (!c.isNone(i))
|
|
279
|
+
values.push(c.get(i));
|
|
280
|
+
}
|
|
281
|
+
return values;
|
|
282
|
+
}, column));
|
|
283
|
+
|
|
284
|
+
/** The stand's runtime container in this machine's Docker: the one the platform runs as the service the panel uses. */
|
|
285
|
+
async function runtimeContainer(page: Page): Promise<string> {
|
|
286
|
+
const known = containers.get(page);
|
|
287
|
+
if (known)
|
|
288
|
+
return known;
|
|
289
|
+
const id: string = await page.evaluate(async () =>
|
|
290
|
+
(await grok.dapi.docker.dockerContainers.filter('name = "grokky-claude-runtime"').list())[0]?.id ?? '');
|
|
291
|
+
if (!id)
|
|
292
|
+
throw new Error('no grokky-claude-runtime container on the stand');
|
|
293
|
+
const {serviceName} = await (await serverRequests(page)).get<{serviceName: string}>(`/docker/containers/${id}`);
|
|
294
|
+
const name = execFileSync('docker', ['ps', '--filter', `label=service=${serviceName}`, '--format', '{{.Names}}'],
|
|
295
|
+
{encoding: 'utf8'}).trim();
|
|
296
|
+
if (!name)
|
|
297
|
+
throw new Error(`no container labelled service=${serviceName} in this machine's Docker: the stand's runtime runs elsewhere`);
|
|
298
|
+
containers.set(page, name);
|
|
299
|
+
return name;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const inRuntime = (container: string, script: string): string =>
|
|
303
|
+
execFileSync('docker', ['exec', container, 'sh', '-c', script], {encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']});
|
|
304
|
+
|
|
305
|
+
function runtimeProcesses(container: string): Process[] {
|
|
306
|
+
const listing = inRuntime(container,
|
|
307
|
+
'for p in /proc/[0-9]*; do printf "%s %s\\n" "${p#/proc/}" "$(tr "\\0" " " 2>/dev/null < "$p/cmdline")"; done');
|
|
308
|
+
return listing.split('\n').flatMap((line) => {
|
|
309
|
+
const m = /^(\d+) (.+)$/.exec(line.trim());
|
|
310
|
+
return m && !m[2].includes('/proc/[0-9]') ? [{pid: Number(m[1]), cmd: m[2].trim()}] : [];
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const sandboxFiles = (container: string, dir: string): string[] =>
|
|
315
|
+
inRuntime(container, `find ${dir} -path ${dir}/agents -prune -o -type f -print 2>/dev/null || true`).split('\n').filter((f) => f !== '');
|
|
316
|
+
|
|
317
|
+
function removeFiles(container: string, files: string[]): void {
|
|
318
|
+
if (files.length)
|
|
319
|
+
execFileSync('docker', ['exec', container, 'rm', '-f', '--', ...files]);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Key-shaped text and the session's own token, on the page or in its inputs; the token never leaves the page. */
|
|
323
|
+
const secretsOnPage = (page: Page): Promise<string[]> => page.evaluate(([re, sel]) => {
|
|
324
|
+
let text = document.body.innerText + '\n' + (document.querySelector(sel)?.textContent ?? '');
|
|
325
|
+
for (const el of Array.from(document.querySelectorAll('textarea, input')) as HTMLInputElement[])
|
|
326
|
+
text += '\n' + (el.value || '');
|
|
327
|
+
const token = String(grok.dapi.token ?? '');
|
|
328
|
+
return [new RegExp(re).test(text) ? 'key-shaped text' : '', token.length > 8 && text.includes(token) ? 'the session token' : '']
|
|
329
|
+
.filter((s) => s !== '');
|
|
330
|
+
}, [SECRET_RE.source, AI_PANEL] as [string, string]);
|
|
331
|
+
|
|
332
|
+
function canaryOf(page: Page): Canary {
|
|
333
|
+
const canary = canaries.get(page);
|
|
334
|
+
if (!canary)
|
|
335
|
+
throw new Error('no note was planted: "Given another user\'s folder in the AI\'s sandbox holds a private note" comes first');
|
|
336
|
+
return canary;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// --- the chat ---------------------------------------------------------------------------------------
|
|
340
|
+
|
|
341
|
+
export const trafficRecorded = Given('the AI runtime traffic is recorded', async (page: Page) => {
|
|
342
|
+
if (taps.has(page))
|
|
343
|
+
return;
|
|
344
|
+
const frames: Frame[] = [];
|
|
345
|
+
taps.set(page, frames);
|
|
346
|
+
let sockets = 0;
|
|
347
|
+
page.on('websocket', (ws: WebSocket) => {
|
|
348
|
+
if (!RUNTIME_WS.test(ws.url()))
|
|
349
|
+
return;
|
|
350
|
+
const socket = ++sockets;
|
|
351
|
+
const record = (dir: 'in' | 'out') => (data: {payload: string | Buffer}) => {
|
|
352
|
+
let d: any;
|
|
353
|
+
try {
|
|
354
|
+
d = JSON.parse(String(data.payload));
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if (!d?.type)
|
|
360
|
+
return;
|
|
361
|
+
frames.push({dir, type: d.type, socket, sessionId: d.sessionId, tool: d.name ?? d.toolName,
|
|
362
|
+
summary: d.type === 'tool_activity' ? String(d.summary ?? '').replace(SECRET_TEXT, '$1<redacted>') : undefined,
|
|
363
|
+
error: d.type === 'error' ? String(d.message ?? '').replace(SECRET_TEXT, '$1<redacted>') : undefined,
|
|
364
|
+
mode: d.type === 'user_message' ? String(d.systemPromptMode ?? 'full') : undefined,
|
|
365
|
+
restored: d.type === 'user_message' ? String(d.message ?? '').startsWith(RESTORED_TRANSCRIPT) : undefined});
|
|
366
|
+
};
|
|
367
|
+
ws.on('framereceived', record('in'));
|
|
368
|
+
ws.on('framesent', record('out'));
|
|
369
|
+
ws.on('close', () => frames.push({dir: 'in', type: 'close', socket}));
|
|
370
|
+
});
|
|
371
|
+
}, {tier: 'api', description: 'records the frames of every claude-runtime WebSocket and its close, across reloads; must precede the first page load that may open one'});
|
|
372
|
+
|
|
373
|
+
export const liveModelGate = Given('live AI model calls are allowed', async (_page: Page) => {
|
|
374
|
+
test.skip(process.env.GROKKY_BDD_LIVE !== '1',
|
|
375
|
+
'set GROKKY_BDD_LIVE=1: the rest of this test sends prompts through the claude-runtime container to a paid model');
|
|
376
|
+
}, {description: 'a gate: every scenario after it calls the model provider, so a plain suite run skips them'});
|
|
377
|
+
|
|
378
|
+
export const runtimeHealthy = Given('the AI runtime container is healthy', async (page: Page) => {
|
|
379
|
+
await expect.poll(() => page.evaluate(async () => {
|
|
380
|
+
try {
|
|
381
|
+
const c = (await grok.dapi.docker.dockerContainers.filter('name = "grokky-claude-runtime"').list())[0];
|
|
382
|
+
if (!c)
|
|
383
|
+
return 'no grokky-claude-runtime container on the stand';
|
|
384
|
+
const r = await grok.dapi.docker.dockerContainers.fetchProxy(c.id, '/health');
|
|
385
|
+
return r.ok ? String((await r.json()).status) : `HTTP ${r.status}`;
|
|
386
|
+
}
|
|
387
|
+
catch (e) {
|
|
388
|
+
return String(e);
|
|
389
|
+
}
|
|
390
|
+
}), {message: 'the runtime\'s /health through the stand\'s docker proxy', timeout: pollMs(120000)}).toBe('ok');
|
|
391
|
+
}, {tier: 'api', description: '/health of the grokky-claude-runtime container through grok.dapi.docker, polled while an on-demand container starts'});
|
|
392
|
+
|
|
393
|
+
export const aiPanelNewChat = Given('the AI panel is open on a new chat', async (page: Page) => {
|
|
394
|
+
await page.evaluate(() => { grok.shell.windows.showAI = true; });
|
|
395
|
+
await expect(page.locator(AI_PROMPT_BOX).filter({visible: true}).first(), 'the AI panel\'s prompt box').toBeVisible({timeout: pollMs(30000)});
|
|
396
|
+
const root = page.locator(AI_PANEL).filter({visible: true}).first();
|
|
397
|
+
const messages = root.locator('.d4-ai-assistant-response-container, .d4-ai-user-prompt-container');
|
|
398
|
+
if (await messages.count() > 0)
|
|
399
|
+
await root.locator('i.fa-plus').filter({visible: true}).first().click();
|
|
400
|
+
await expect(messages, 'the messages of the panel\'s chat').toHaveCount(0);
|
|
401
|
+
turns.set(page, []);
|
|
402
|
+
}, {tier: 'ui', description: 'shows the AI panel and starts a new chat with its + icon when the current one has messages'});
|
|
403
|
+
|
|
404
|
+
export const askAI = When('user asks the AI panel {string}', async (page: Page, prompt: string) => {
|
|
405
|
+
await waitTurn(page, requireRuntime(await sendPrompt(page, prompt)));
|
|
406
|
+
}, {tier: 'ui', description: 'types the prompt, presses Enter and waits for the runtime\'s final, error or aborted event for the panel\'s session and the panel to go idle'});
|
|
407
|
+
|
|
408
|
+
export const askAIAndAnswer = When('user asks the AI panel {string} and picks the option matching {string} in its question',
|
|
409
|
+
async (page: Page, prompt: string, option: string) => {
|
|
410
|
+
const turn = requireRuntime(await sendPrompt(page, prompt));
|
|
411
|
+
await waitTurn(page, turn, {question: () => answerQuestion(page, turn, new RegExp(option, 'i'))});
|
|
412
|
+
if (!turn.question)
|
|
413
|
+
throw new Error(`the AI ended the turn without asking a question; it answered: "${turn.answer.slice(0, 200)}"`);
|
|
414
|
+
}, {tier: 'ui', description: 'answers every question of the AskUserQuestion form the turn shows (the option matching the pattern, case-insensitive, where one does), then Submit'});
|
|
415
|
+
|
|
416
|
+
export const askAIAndConfirm = When('user asks the AI panel {string} and clicks {string} on its confirmation card',
|
|
417
|
+
async (page: Page, prompt: string, button: string) => {
|
|
418
|
+
const turn = requireRuntime(await sendPrompt(page, prompt));
|
|
419
|
+
await waitTurn(page, turn, {confirm: () => answerConfirmation(page, turn, button)});
|
|
420
|
+
if (turn.confirmations.length === 0)
|
|
421
|
+
throw new Error(`the AI ended the turn without asking for a confirmation; it answered: "${turn.answer.slice(0, 200)}"`);
|
|
422
|
+
}, {tier: 'ui', description: 'clicks the button (OK or CANCEL) on every confirm card the turn shows, and waits for the turn to end'});
|
|
423
|
+
|
|
424
|
+
export const sendToAI = When('user sends {string} to the AI panel', async (page: Page, prompt: string) => {
|
|
425
|
+
requireRuntime(await sendPrompt(page, prompt));
|
|
426
|
+
}, {tier: 'ui', description: 'types the prompt and presses Enter; done once the runtime has the prompt, while the turn runs'});
|
|
427
|
+
|
|
428
|
+
export const submitToAI = When('user submits {string} in the AI panel', async (page: Page, prompt: string) => {
|
|
429
|
+
await waitTurn(page, await sendPrompt(page, prompt));
|
|
430
|
+
}, {tier: 'ui', description: 'whoever takes it, the platform\'s own prompt interpreter or the runtime; done when that one is — for a claim on the outcome alone'});
|
|
431
|
+
|
|
432
|
+
export const reopenChat = When('user reopens the AI chat from the chat history', async (page: Page) => {
|
|
433
|
+
const first = turnsOf(page)[0];
|
|
434
|
+
if (!first)
|
|
435
|
+
throw new Error('no chat was held in this scenario to reopen');
|
|
436
|
+
await page.evaluate(() => { grok.shell.windows.showAI = true; });
|
|
437
|
+
await page.locator(`${AI_PANEL} .d4-ai-panel-run-controls .fa-history`).filter({visible: true}).first().click();
|
|
438
|
+
await page.locator('.d4-menu-popup .d4-menu-item').filter({visible: true, hasText: first.prompt.slice(0, 40)}).first().click();
|
|
439
|
+
await expect(page.locator(`${AI_PANEL} .d4-ai-user-prompt-container`).filter({visible: true}).first(),
|
|
440
|
+
'the reopened chat\'s first prompt').toContainText(first.prompt.slice(0, 40));
|
|
441
|
+
}, {tier: 'ui', description: 'the panel\'s Chat History icon, then the entry the chat\'s first prompt names'});
|
|
442
|
+
|
|
443
|
+
// --- what the turns did -----------------------------------------------------------------------------
|
|
444
|
+
|
|
445
|
+
export const turnStopped = Then('the AI turn should have been stopped', async (page: Page) => {
|
|
446
|
+
const turn = lastTurn(page);
|
|
447
|
+
await expect.poll(async () => {
|
|
448
|
+
const ends = framesOf(page, turn).filter((f) => f.dir === 'in' && TERMINAL.includes(f.type)).map((f) => f.type);
|
|
449
|
+
return `${ends.join(', ') || 'no terminal event'}; panel ${(await panel(page)).busy ? 'busy' : 'idle'}`;
|
|
450
|
+
}, {message: 'how the runtime ended the stopped turn, and the panel', timeout: pollMs(15000)}).toBe('aborted; panel idle');
|
|
451
|
+
turn.end = 'aborted';
|
|
452
|
+
}, {description: 'the runtime\'s aborted event for the turn\'s session, and the panel idle again'});
|
|
453
|
+
|
|
454
|
+
export const nothingAfterStop = Then('the stopped AI turn should have sent nothing after it was aborted', async (page: Page) => {
|
|
455
|
+
const list = turnsOf(page);
|
|
456
|
+
const stopped = list.findIndex((t) => t.end === 'aborted');
|
|
457
|
+
if (stopped < 0 || stopped === list.length - 1)
|
|
458
|
+
throw new Error('claim it after a stopped turn and the turn that followed it');
|
|
459
|
+
const all = tapOf(page);
|
|
460
|
+
const {from, sessionId} = list[stopped];
|
|
461
|
+
const abortedAt = all.findIndex((f, i) => i >= from && f.sessionId === sessionId && f.type === 'aborted');
|
|
462
|
+
const late = all.slice(abortedAt + 1, list[stopped + 1].from)
|
|
463
|
+
.filter((f) => f.dir === 'in' && f.sessionId === sessionId && (f.type === 'chunk' || f.type === 'final'));
|
|
464
|
+
expect(late.length, 'chunk or final events for the session after its aborted event, until the next prompt').toBe(0);
|
|
465
|
+
}, {description: 'read after the next turn: no chunk or final arrived for the stopped turn after its aborted event'});
|
|
466
|
+
|
|
467
|
+
export const toolRan = Then('the AI should have used the {string} tool', async (page: Page, tool: string) => {
|
|
468
|
+
expect(toolsOf(page, lastTurn(page)), 'the tools of the last turn, as tool_activity and input_request events name them').toContain(tool);
|
|
469
|
+
}, {description: 'a tool_activity or input_request of the last turn names the tool (bare name)'});
|
|
470
|
+
|
|
471
|
+
export const oneOfToolsRan = Then('the AI should have used one of the tools {string}', async (page: Page, list: string) => {
|
|
472
|
+
const used = toolsOf(page, lastTurn(page));
|
|
473
|
+
expect(list.split(/\s*,\s*/).filter((t) => used.includes(t)), `the tools of the last turn: ${used.join(', ')}`).not.toEqual([]);
|
|
474
|
+
}, {description: 'comma-separated bare tool names; the last turn used at least one'});
|
|
475
|
+
|
|
476
|
+
export const terminalRan = Then('a terminal command of the AI should have run {word}', async (page: Page, program: string) => {
|
|
477
|
+
const turn = lastTurn(page);
|
|
478
|
+
const container = await runtimeContainer(page);
|
|
479
|
+
const since = Number(inRuntime(container, 'date +%s.%N')) - (Date.now() - turn.startedAt) / 1000 - 1;
|
|
480
|
+
const commands = execFileSync('docker', ['exec', container, 'python3', '-c', TURN_COMMANDS, String(since), turn.prompt.slice(0, 60)],
|
|
481
|
+
{encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']}).split('\n').filter((l) => l !== '').map((l) => String(JSON.parse(l)));
|
|
482
|
+
expect(commands.some((c) => new RegExp(`\\b${escapeRegExp(program)}\\b`).test(c)),
|
|
483
|
+
`the terminal commands of the last turn, from its agent's session store: ${commands.join(' | ') || 'none'}`).toBe(true);
|
|
484
|
+
}, {description: 'one of the terminal commands the last turn\'s agent ran names the program, read from its Hermes session store in the container (the activity summary does not carry the command)'});
|
|
485
|
+
|
|
486
|
+
export const confirmationAsked = Then('the AI should have asked to confirm with a card naming {string}', async (page: Page, name: string) => {
|
|
487
|
+
const turn = lastTurn(page);
|
|
488
|
+
expect(toolsOf(page, turn), 'the tools of the last turn').toContain('datagrok_confirm');
|
|
489
|
+
expect(turn.confirmations.some((c) => c.includes(name)), `the confirm cards the turn showed: ${turn.confirmations.join(' | ')}`).toBe(true);
|
|
490
|
+
}, {description: 'a datagrok_confirm round trip of the last turn, whose card names the entity'});
|
|
491
|
+
|
|
492
|
+
export const promptMode = Then('the last prompt should have reached the runtime in {word} mode', async (page: Page, mode: string) => {
|
|
493
|
+
const modes = framesOf(page, lastTurn(page)).filter((f) => f.dir === 'out' && f.type === 'user_message').map((f) => f.mode);
|
|
494
|
+
expect([...new Set(modes)], 'the systemPromptMode of the last turn\'s user_message frames (full when none)').toEqual([mode]);
|
|
495
|
+
}, {description: 'bash, none or full (no systemPromptMode): the mode the panel sent the last prompt in'});
|
|
496
|
+
|
|
497
|
+
export const questionAsked = Then('the AI should have asked a question offering {int} or more options', async (page: Page, n: number) => {
|
|
498
|
+
const q = lastTurn(page).question;
|
|
499
|
+
expect(q, 'the question the AI asked in the panel').toBeTruthy();
|
|
500
|
+
expect(q!.options.length, `the options it offered: ${q!.options.join(', ')}`).toBeGreaterThanOrEqual(n);
|
|
501
|
+
}, {description: 'the AskUserQuestion question whose option was picked, as answered'});
|
|
502
|
+
|
|
503
|
+
export const systemMessage = Then('the AI panel should show the message {string}', async (page: Page, text: string) => {
|
|
504
|
+
await expect.poll(async () => (await panel(page)).systemMessages.join(' | '),
|
|
505
|
+
{message: `the panel's system messages include "${text}"`}).toContain(text);
|
|
506
|
+
}, {description: 'one of the panel\'s system messages (grokky-system-message) contains the text'});
|
|
507
|
+
|
|
508
|
+
export const earlierTurnsShown = Then('the AI panel should show the earlier turns of the chat', async (page: Page) => {
|
|
509
|
+
const shown = (await page.locator(AI_PANEL).filter({visible: true}).first()
|
|
510
|
+
.locator('.d4-ai-user-prompt-container, .d4-ai-assistant-response-container').allInnerTexts()).map((t) => t.trim());
|
|
511
|
+
for (const turn of turnsOf(page)) {
|
|
512
|
+
const answer = answerOf(turn);
|
|
513
|
+
expect(shown.some((t) => t.includes(turn.prompt)), `the prompt "${turn.prompt.slice(0, 60)}" among: ${shown.join(' | ').slice(0, 300)}`).toBe(true);
|
|
514
|
+
expect(answer !== '' && shown.some((t) => t.includes(answer)), `the answer "${answer.slice(0, 60)}"`).toBe(true);
|
|
515
|
+
}
|
|
516
|
+
}, {description: 'every prompt the chat held so far and its answer, as the panel shows them'});
|
|
517
|
+
|
|
518
|
+
export const sameSession = Then('every turn of the chat should have used the same AI session', async (page: Page) => {
|
|
519
|
+
const ids = turnsOf(page).map((t) => t.sessionId);
|
|
520
|
+
expect(ids.length, 'turns in the chat').toBeGreaterThanOrEqual(2);
|
|
521
|
+
expect(new Set(ids).size, `the session ids of the turns: ${ids.join(', ')}`).toBe(1);
|
|
522
|
+
}, {description: 'the user_message frames of all the scenario\'s turns carry one sessionId, so the runtime continued it'});
|
|
523
|
+
|
|
524
|
+
export const historyKept = Then('the AI runtime should have kept the chat\'s history itself', async (page: Page) => {
|
|
525
|
+
const frames = framesOf(page, lastTurn(page));
|
|
526
|
+
const resets = frames.filter((f) => f.type === 'session_reset').length;
|
|
527
|
+
const replays = frames.filter((f) => f.dir === 'out' && f.type === 'user_message' && f.restored).length;
|
|
528
|
+
expect(`${resets} session_reset, ${replays} prompt(s) replaying the panel's transcript`,
|
|
529
|
+
'how the last turn got the chat\'s history').toBe('0 session_reset, 0 prompt(s) replaying the panel\'s transcript');
|
|
530
|
+
}, {description: 'the last turn ran on the history the runtime holds: no session_reset, no prompt carrying the panel\'s saved transcript'});
|
|
531
|
+
|
|
532
|
+
// --- answers against the data -----------------------------------------------------------------------
|
|
533
|
+
|
|
534
|
+
export const highestMeanNamed = Then('the AI answer should name the {string} with the highest mean {string} where {string} is {string}',
|
|
535
|
+
async (page: Page, group: string, value: string, filterColumn: string, filterValue: string) => {
|
|
536
|
+
const answer = answerOf(lastTurn(page));
|
|
537
|
+
const means: Record<string, number> = await page.evaluate(([g, v, fc, fv]) => {
|
|
538
|
+
const df = grok.shell.t;
|
|
539
|
+
const sums: Record<string, [number, number]> = {};
|
|
540
|
+
for (let i = 0; i < df.rowCount; i++) {
|
|
541
|
+
if (String(df.get(fc, i)) !== fv || df.col(v).isNone(i))
|
|
542
|
+
continue;
|
|
543
|
+
const key = String(df.get(g, i));
|
|
544
|
+
sums[key] ??= [0, 0];
|
|
545
|
+
sums[key][0] += df.get(v, i);
|
|
546
|
+
sums[key][1]++;
|
|
547
|
+
}
|
|
548
|
+
return Object.fromEntries(Object.entries(sums).map(([k, [sum, n]]) => [k, sum / n]));
|
|
549
|
+
}, [group, value, filterColumn, filterValue]);
|
|
550
|
+
const [top, mean] = Object.entries(means).sort((a, b) => b[1] - a[1])[0];
|
|
551
|
+
const named = Object.keys(means).filter((k) => new RegExp(`\\b${escapeRegExp(k)}\\b`).test(answer));
|
|
552
|
+
expect(named, `the ${group} values the answer names: "${answer.slice(0, 200)}"`).toEqual([top]);
|
|
553
|
+
expectNumberIn(answer, mean, 0.051, `the mean ${value} of ${top}`);
|
|
554
|
+
}, {description: 'computed from the current table: the answer names the top group alone and gives its mean to one decimal'});
|
|
555
|
+
|
|
556
|
+
export const medianGiven = Then('the AI answer should be the median of {string}', async (page: Page, column: string) => {
|
|
557
|
+
expectNumberIn(answerOf(lastTurn(page)), await columnMedian(page, column), 0.051, `the median ${column}`);
|
|
558
|
+
}, {description: 'a number of the answer, to one decimal, against the median computed from the current table'});
|
|
559
|
+
|
|
560
|
+
export const medianDivided = Then('the AI answer should be the median of {string} divided by {float}', async (page: Page, column: string, divisor: number) => {
|
|
561
|
+
expectNumberIn(answerOf(lastTurn(page)), await columnMedian(page, column) / divisor, 0.06, `the median ${column} over ${divisor}`);
|
|
562
|
+
}, {description: 'a number of the answer, to one decimal, against the median computed from the current table over the divisor'});
|
|
563
|
+
|
|
564
|
+
export const groupMedians = Then('the AI answer should give the median {string} of each {string} in {string}',
|
|
565
|
+
async (page: Page, value: string, group: string, file: string) => {
|
|
566
|
+
const answer = answerOf(lastTurn(page));
|
|
567
|
+
const groups: Record<string, number[]> = await page.evaluate(async ([v, g, f]) => {
|
|
568
|
+
const df = await grok.dapi.files.readCsv(f);
|
|
569
|
+
const byGroup: Record<string, number[]> = {};
|
|
570
|
+
for (let i = 0; i < df.rowCount; i++) {
|
|
571
|
+
if (!df.col(v).isNone(i))
|
|
572
|
+
(byGroup[String(df.get(g, i))] ??= []).push(df.get(v, i));
|
|
573
|
+
}
|
|
574
|
+
return byGroup;
|
|
575
|
+
}, [value, group, file]);
|
|
576
|
+
for (const [key, xs] of Object.entries(groups)) {
|
|
577
|
+
const want = median(xs);
|
|
578
|
+
const after = new RegExp(`\\b${escapeRegExp(key)}\\b\\D*?(-?\\d+(?:\\.\\d+)?)`, 'i').exec(answer);
|
|
579
|
+
if (!after)
|
|
580
|
+
throw new Error(`the answer gives no number after "${key}": "${answer.slice(0, 300)}"`);
|
|
581
|
+
expect(Math.abs(Number(after[1]) - want), `the number after "${key}" against its median ${want}`).toBeLessThan(0.051);
|
|
582
|
+
}
|
|
583
|
+
}, {description: 'computed from the file: for every group, the first number after its name is its median to one decimal'});
|
|
584
|
+
|
|
585
|
+
export const numericColumnsNamed = Then('the AI answer should name every numeric column of the table', async (page: Page) => {
|
|
586
|
+
const answer = answerOf(lastTurn(page));
|
|
587
|
+
const numeric: string[] = await page.evaluate(() => (grok.shell.t as PageTable).columns.toList()
|
|
588
|
+
.filter((c) => c.isNumerical && c.type !== 'datetime').map((c) => c.name));
|
|
589
|
+
expect(numeric.filter((c) => !new RegExp(`\\b${escapeRegExp(c)}\\b`, 'i').test(answer)),
|
|
590
|
+
`numeric columns of the table the answer leaves out: "${answer.slice(0, 300)}"`).toEqual([]);
|
|
591
|
+
}, {description: 'every numerical column of the current table, dates aside (core counts them numerical), by name in any case, in the last answer'});
|
|
592
|
+
|
|
593
|
+
export const hostNameAnswered = Then('the AI answer should be exactly the host name of the AI runtime container', async (page: Page) => {
|
|
594
|
+
const host = inRuntime(await runtimeContainer(page), 'hostname').trim();
|
|
595
|
+
expect(answerOf(lastTurn(page)), 'the answer, against `hostname` run in the container').toBe(host);
|
|
596
|
+
}, {description: 'the raw stdout of the command and nothing else, compared with `hostname` run through docker exec'});
|
|
597
|
+
|
|
598
|
+
export const helpPageCited = Then('the AI answer should link to the help page {string} it read', async (page: Page, helpPage: string) => {
|
|
599
|
+
const turn = lastTurn(page);
|
|
600
|
+
const read = framesOf(page, turn).filter((f) => f.tool === 'read_file').map((f) => f.summary ?? '');
|
|
601
|
+
expect(read, 'the files the turn read').toContain(`Read workspace/help/${helpPage}.md`);
|
|
602
|
+
const hrefs = await page.locator(AI_PANEL).filter({visible: true}).first().locator('.d4-ai-assistant-response-container').last()
|
|
603
|
+
.locator('a').evaluateAll((links) => links.map((a) => a.getAttribute('href') ?? ''));
|
|
604
|
+
expect(hrefs.map((h) => h.replace(/(\.md)?\/?([?#].*)?$/, '')), 'the links of the answer').toContain(`https://datagrok.ai/help/${helpPage}`);
|
|
605
|
+
}, {description: 'the turn read workspace/help/<page>.md (its read_file activity) and the last answer links to https://datagrok.ai/help/<page>'});
|
|
606
|
+
|
|
607
|
+
// --- the table and the grid -------------------------------------------------------------------------
|
|
608
|
+
|
|
609
|
+
export const bmiValues = Then('every value of {string} column should be the BMI of {string} in kg and {string} in cm',
|
|
610
|
+
async (page: Page, bmi: string, weight: string, height: string) => {
|
|
611
|
+
await expect.poll(() => page.evaluate(([b, w, h]) => {
|
|
612
|
+
const df = grok.shell.t;
|
|
613
|
+
const [cb, cw, ch] = [df.col(b), df.col(w), df.col(h)];
|
|
614
|
+
if (!cb)
|
|
615
|
+
return `no "${b}" column; the table has: ${df.columns.names().join(', ')}`;
|
|
616
|
+
const wrong: string[] = [];
|
|
617
|
+
for (let i = 0; i < df.rowCount; i++) {
|
|
618
|
+
const want = cw.isNone(i) || ch.isNone(i) ? null : cw.get(i) / (ch.get(i) / 100) ** 2;
|
|
619
|
+
const got = cb.isNone(i) ? null : cb.get(i);
|
|
620
|
+
if (want === null ? got !== null : got === null || Math.abs(got - want) > 0.051)
|
|
621
|
+
wrong.push(`row ${i + 1}: ${got} for ${want?.toFixed(2)}`);
|
|
622
|
+
}
|
|
623
|
+
return wrong.length ? `${wrong.length} of ${df.rowCount} rows off, e.g. ${wrong.slice(0, 3).join('; ')}` : 'every row';
|
|
624
|
+
}, [bmi, weight, height]), {message: `${bmi} against ${weight} / (${height} / 100)², to one decimal`}).toBe('every row');
|
|
625
|
+
}, {tier: 'api', description: 'every row of the current table, to one decimal; empty where the weight or the height is'});
|
|
626
|
+
|
|
627
|
+
export const groupSummary = Then('the current table should hold the count and the mean {string} of every {string} group of table {string}',
|
|
628
|
+
async (page: Page, values: string, group: string, source: string) => {
|
|
629
|
+
await expect.poll(() => page.evaluate(([vs, g, src]) => {
|
|
630
|
+
const from = (grok.shell.tables as PageTable[]).find((t) => t.name === src);
|
|
631
|
+
const df: PageTable = grok.shell.t;
|
|
632
|
+
if (!from)
|
|
633
|
+
return [`no table "${src}" is open`];
|
|
634
|
+
if (df.dart === from.dart || grok.shell.tv?.dataFrame?.dart !== df.dart)
|
|
635
|
+
return [`the current view shows ${grok.shell.tv?.dataFrame?.name ?? 'no table'}, not a new summary table`];
|
|
636
|
+
const means = vs.split(/\s*,\s*/);
|
|
637
|
+
const truth: Record<string, number[]> = {};
|
|
638
|
+
for (let i = 0; i < from.rowCount; i++) {
|
|
639
|
+
const sums = truth[String(from.get(g, i))] ??= new Array(means.length + 1).fill(0);
|
|
640
|
+
sums[0]++;
|
|
641
|
+
for (const [j, m] of means.entries())
|
|
642
|
+
sums[j + 1] += from.get(m, i);
|
|
643
|
+
}
|
|
644
|
+
const groups = Object.keys(truth).sort().join(', ');
|
|
645
|
+
const columns = df.columns.toList();
|
|
646
|
+
const numbers = columns.filter((c) => c.isNumerical && c.type !== 'datetime');
|
|
647
|
+
const groupCol = columns.find((c) => !c.isNumerical &&
|
|
648
|
+
Array.from({length: df.rowCount}, (_, i) => String(c.get(i))).sort().join(', ') === groups);
|
|
649
|
+
if (!groupCol)
|
|
650
|
+
return [`no column of ${df.name} lists the ${g} groups ${groups} once each; its columns: ${df.columns.names().join(', ')}`];
|
|
651
|
+
const problems: string[] = [];
|
|
652
|
+
for (let i = 0; i < df.rowCount; i++) {
|
|
653
|
+
const sums = truth[String(groupCol.get(i))];
|
|
654
|
+
const row = numbers.map((c) => Number(c.get(i)));
|
|
655
|
+
for (const [j, want] of [sums[0], ...means.map((_, k) => sums[k + 1] / sums[0])].entries()) {
|
|
656
|
+
if (!row.some((x) => Math.abs(x - want) <= (j === 0 ? 0 : 0.051)))
|
|
657
|
+
problems.push(`${groupCol.get(i)}: no ${j === 0 ? 'count' : `mean ${means[j - 1]}`} ${want.toFixed(j === 0 ? 0 : 2)} among ${row.join(', ')}`);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
return problems;
|
|
661
|
+
}, [values, group, source] as [string, string, string]), {message: `the current table against the ${group} groups of ${source}`}).toEqual([]);
|
|
662
|
+
}, {tier: 'api', description: 'a new table, current in its own view: one row per group of the source table, each holding the group\'s row count and the means (to one decimal) of the comma-separated columns, computed from the source'});
|
|
663
|
+
|
|
664
|
+
export const onlyGrid = Then('the current table view should show nothing but its grid', async (page: Page) => {
|
|
665
|
+
await expect.poll(() => page.evaluate(() => Array.from(grok.shell.tv.viewers as Iterable<{type: string}>).map((v) => v.type)),
|
|
666
|
+
{message: 'the viewers of the current table view'}).toEqual(['Grid']);
|
|
667
|
+
}, {tier: 'api', description: 'grok.shell.tv.viewers holds the grid alone'});
|
|
668
|
+
|
|
669
|
+
export const hiddenInGrid = Then('the {string} column should be hidden in the grid', async (page: Page, column: string) => {
|
|
670
|
+
await expect.poll(() => page.evaluate((c) => {
|
|
671
|
+
const gc = grok.shell.tv.grid.col(c);
|
|
672
|
+
return gc ? (gc.visible ? 'shown' : 'hidden') : `the grid has no "${c}" column`;
|
|
673
|
+
}, column), {message: `the "${column}" column of the current table view's grid`}).toBe('hidden');
|
|
674
|
+
}, {tier: 'api', description: 'the grid column of the current table view is not visible; the table keeps the column'});
|
|
675
|
+
|
|
676
|
+
// --- the server -------------------------------------------------------------------------------------
|
|
677
|
+
|
|
678
|
+
export const fileCards = Then('the AI panel should show the files of {string} as cards', async (page: Page, folder: string) => {
|
|
679
|
+
await expect.poll(() => page.evaluate(async ([sel, f]) => {
|
|
680
|
+
const listed: {name: string; isDirectory: boolean}[] = await grok.dapi.files.list(f);
|
|
681
|
+
const root = Array.from(document.querySelectorAll(sel)).find((p) => (p as HTMLElement).offsetParent !== null) as HTMLElement;
|
|
682
|
+
const lists = root.querySelectorAll('.grokky-entity-cards');
|
|
683
|
+
const items = Array.from(lists[lists.length - 1]?.children ?? []) as HTMLElement[];
|
|
684
|
+
const cards = items.map((e) => e.querySelector('.grok-file-info label')?.textContent?.trim() ?? '').filter((n) => n !== '');
|
|
685
|
+
const shown = items.map((e) => e.querySelector('.grok-file-info label')?.textContent?.trim() ?? e.innerText.trim());
|
|
686
|
+
const files = listed.filter((x) => !x.isDirectory).map((x) => x.name);
|
|
687
|
+
const entries = listed.map((x) => x.name);
|
|
688
|
+
return [
|
|
689
|
+
...files.filter((n) => !cards.includes(n)).map((n) => `no card for ${n}`),
|
|
690
|
+
...shown.filter((n) => !entries.includes(n)).map((n) => `"${n}" is not in ${f}`),
|
|
691
|
+
...shown.filter((n, i) => shown.indexOf(n) !== i).map((n) => `${n} shown twice`),
|
|
692
|
+
];
|
|
693
|
+
}, [AI_PANEL, folder] as [string, string]), {message: `the entity cards of the last answer against the server's listing of ${folder}`})
|
|
694
|
+
.toEqual([]);
|
|
695
|
+
}, {tier: 'api', description: 'every file the server lists in the folder has a rendered file card in the last cards block, and nothing else shown is missing from the folder (its subfolders may show)'});
|
|
696
|
+
|
|
697
|
+
// --- the runtime container --------------------------------------------------------------------------
|
|
698
|
+
|
|
699
|
+
export const runsHermes = Then('the AI runtime container should run the Hermes agent and not the Claude Agent SDK', async (page: Page) => {
|
|
700
|
+
const container = await runtimeContainer(page);
|
|
701
|
+
const sdk = inRuntime(container, 'ls -d /app/node_modules/@anthropic-ai/claude-agent-sdk 2>/dev/null || echo none').trim();
|
|
702
|
+
expect(runtimeProcesses(container).filter((p) => AGENT_PROCESS.test(p.cmd)).length,
|
|
703
|
+
`Hermes agent processes (python -m grokky_agent) in ${container}`).toBeGreaterThanOrEqual(1);
|
|
704
|
+
expect(sdk, `@anthropic-ai/claude-agent-sdk in ${container}'s /app/node_modules`).toBe('none');
|
|
705
|
+
}, {description: 'docker exec into the stand\'s runtime container (same machine): a Hermes agent process runs and the SDK is not installed'});
|
|
706
|
+
|
|
707
|
+
export const runningInRuntime = Then('the AI runtime container should be running {string}', async (page: Page, command: string) => {
|
|
708
|
+
const container = await runtimeContainer(page);
|
|
709
|
+
await expect.poll(() => runtimeProcesses(container).some((p) => p.cmd.includes(command)),
|
|
710
|
+
{message: `a process "${command}" in ${container}`, timeout: pollMs(TURN_MS)}).toBe(true);
|
|
711
|
+
}, {description: 'polled over docker exec: a process whose command line contains the text'});
|
|
712
|
+
|
|
713
|
+
export const notRunningInRuntime = Then('the AI runtime container should not be running {string}', async (page: Page, command: string) => {
|
|
714
|
+
const container = await runtimeContainer(page);
|
|
715
|
+
await expect.poll(() => runtimeProcesses(container).filter((p) => p.cmd.includes(command)).map((p) => `${p.pid} ${p.cmd}`),
|
|
716
|
+
{message: `processes "${command}" left in ${container}`, timeout: pollMs(15000)}).toEqual([]);
|
|
717
|
+
}, {description: 'polled over docker exec until no process\'s command line contains the text'});
|
|
718
|
+
|
|
719
|
+
export const sandboxSwept = Given('no file named {string} is in the AI\'s sandbox', async (page: Page, names: string) => {
|
|
720
|
+
const container = await runtimeContainer(page);
|
|
721
|
+
const dir = `/users/${await page.evaluate(() => String(grok.shell.user.id))}`;
|
|
722
|
+
const wanted = names.split(/\s*,\s*/);
|
|
723
|
+
const named = (): string[] => sandboxFiles(container, dir).filter((f) => wanted.includes(path.basename(f)));
|
|
724
|
+
removeFiles(container, named());
|
|
725
|
+
expect(named(), `files named ${names} in ${dir}`).toEqual([]);
|
|
726
|
+
const before = new Set(sandboxFiles(container, dir));
|
|
727
|
+
atFeatureEnd(page, async () => {
|
|
728
|
+
removeFiles(container, sandboxFiles(container, dir).filter((f) => !before.has(f)));
|
|
729
|
+
expect(sandboxFiles(container, dir).filter((f) => !before.has(f)), `files the AI left in ${dir}`).toEqual([]);
|
|
730
|
+
});
|
|
731
|
+
}, {tier: 'api', description: 'the named files go from the user\'s runtime directory now, and every file added there after this step goes when the feature ends, read back gone; the synced agents/ folder is left alone'});
|
|
732
|
+
|
|
733
|
+
export const otherUsersNote = Given('another user\'s folder in the AI\'s sandbox holds a private note', async (page: Page) => {
|
|
734
|
+
const container = await runtimeContainer(page);
|
|
735
|
+
const sweep = (): string => inRuntime(container, `rm -rf ${CANARY_DIRS}*; ls -d ${CANARY_DIRS}* 2>/dev/null || true`).trim();
|
|
736
|
+
expect(sweep(), 'canary folders an earlier run left').toBe('');
|
|
737
|
+
const run = randomUUID();
|
|
738
|
+
const dir = `${CANARY_DIRS}${run.slice(-12)}`;
|
|
739
|
+
const note = `private-note-${run}`;
|
|
740
|
+
// no chown -R: its own listing of the folder could keep relatime from recording the agent's
|
|
741
|
+
inRuntime(container, `mkdir ${dir} && printf %s ${note} > ${dir}/notes.txt && chown --reference=/users ${dir} ${dir}/notes.txt`);
|
|
742
|
+
canaries.set(page, {note, dir, accessed: inRuntime(container, `stat -c %x ${dir} ${dir}/notes.txt`).trim()});
|
|
743
|
+
atFeatureEnd(page, async () => {
|
|
744
|
+
canaries.delete(page);
|
|
745
|
+
expect(sweep(), 'canary folders left in the runtime').toBe('');
|
|
746
|
+
});
|
|
747
|
+
}, {tier: 'api', description: 'a folder under the runtime\'s /users, owned as the users\' folders are, holding a note with a random text; its access times are kept; removed at feature end and read back gone, a killed run\'s swept first'});
|
|
748
|
+
|
|
749
|
+
export const agentsKilled = When('the AI runtime\'s agent processes are killed', async (page: Page) => {
|
|
750
|
+
const container = await runtimeContainer(page);
|
|
751
|
+
const pids = runtimeProcesses(container).filter((p) => AGENT_PROCESS.test(p.cmd)).map((p) => p.pid);
|
|
752
|
+
expect(pids.length, `agent processes (python -m grokky_agent) in ${container}`).toBeGreaterThanOrEqual(1);
|
|
753
|
+
inRuntime(container, `kill -9 ${pids.join(' ')}`);
|
|
754
|
+
await expect.poll(() => runtimeProcesses(container).filter((p) => pids.includes(p.pid)).length,
|
|
755
|
+
{message: `the killed agent processes ${pids.join(', ')} still in ${container}`}).toBe(0);
|
|
756
|
+
}, {tier: 'api', description: 'docker exec … kill -9 on every python -m grokky_agent of the stand\'s runtime container (the chat\'s own and the warm spares), then waits until they are gone'});
|
|
757
|
+
|
|
758
|
+
export const canaryUnopened = Then('the other user\'s folder should not have been opened', async (page: Page) => {
|
|
759
|
+
const {dir, accessed} = canaryOf(page);
|
|
760
|
+
expect(inRuntime(await runtimeContainer(page), `stat -c %x ${dir} ${dir}/notes.txt`).trim(),
|
|
761
|
+
`the access times of ${dir} and its note, against when it was planted (relatime moves them on the first listing or read)`).toBe(accessed);
|
|
762
|
+
}, {description: 'the folder was never listed and the note never read, by any process: their access times are as planted'});
|
|
763
|
+
|
|
764
|
+
// --- what reaches the page --------------------------------------------------------------------------
|
|
765
|
+
|
|
766
|
+
export const noSecrets = Then('no key-shaped text or session token should be on the page', async (page: Page) => {
|
|
767
|
+
expect(await secretsOnPage(page), 'secrets on the page, in the AI panel or in an input').toEqual([]);
|
|
768
|
+
}, {description: 'API-key- and bearer-shaped text, and the session\'s own token, over the page text, the whole AI panel and every input'});
|
|
769
|
+
|
|
770
|
+
export const noteNotShown = Then('the other user\'s note should not be on the page', async (page: Page) => {
|
|
771
|
+
const {note} = canaryOf(page);
|
|
772
|
+
expect(await page.evaluate(([n, sel]) => (document.body.innerText + (document.querySelector(sel)?.textContent ?? '')).includes(n),
|
|
773
|
+
[note, AI_PANEL] as [string, string]), 'the note\'s text on the page or in the AI panel').toBe(false);
|
|
774
|
+
}, {description: 'the random text of the note the canary folder holds, over the page text and the whole AI panel'});
|
|
775
|
+
|
|
776
|
+
export const screenshot = Then('a screenshot {string} of the AI panel is saved', async (page: Page, name: string) => {
|
|
777
|
+
const secrets = await secretsOnPage(page);
|
|
778
|
+
if (secrets.length)
|
|
779
|
+
throw new Error(`${secrets.join(' and ')} on the page: screenshot ${name} not written`);
|
|
780
|
+
fs.mkdirSync(SHOTS, {recursive: true});
|
|
781
|
+
const full = path.join(SHOTS, `${name}.png`);
|
|
782
|
+
const crop = path.join(SHOTS, `${name}-panel.png`);
|
|
783
|
+
await page.screenshot({path: full});
|
|
784
|
+
await page.locator(AI_PANEL).filter({visible: true}).first().screenshot({path: crop});
|
|
785
|
+
await test.info().attach(`${name}.png`, {path: full, contentType: 'image/png'});
|
|
786
|
+
await test.info().attach(`${name}-panel.png`, {path: crop, contentType: 'image/png'});
|
|
787
|
+
}, {description: 'the page and a crop of the AI panel to GROKKY_BDD_SHOTS (default bdd/test-results/screenshots), refused while a secret is shown'});
|