Files
Codeman/test/render-index-html.test.ts
T
Codeman maintainer 4cda150493 feat(deepseek): add DeepSeek Harness (dsh) as a ninth CLI run mode
Adds `mode: 'deepseek'` alongside claude/shell/opencode/codex/gemini/
antigravity/pi/grok, plus a shortcut that opens the harness's own browser UI
as a Codeman web tab.

DeepSeek is wired unlike its siblings in three ways, each of which is the
reason for a design decision rather than an accident:

1. The agent is a PROFILE, not the binary. `dsh` is a launcher over
   $DSH_HOME/profiles/<name>, and DeepSeek ships only `web`, `headless` and
   `base` -- the interactive terminal front door is always a third-party
   plugin. So availability is two questions: `isDeepSeekAvailable()` (binary)
   and `isDeepSeekRunnable()` (binary AND a pane-capable profile). The Run
   button gates on the latter, because reporting only the binary would spawn a
   pane that dies on arrival. When the binary is present but no profile is,
   the run menu offers to install one (POST /api/deepseek/install-profile).

2. The permission switch is an env var, not a flag. The harness has no
   command-line permission option; its sandbox/approval rows read
   DSH_PERMISSION_MODE (read-only / workspace-write / danger-full-access).
   Exported via `tmux setenv`, never on the spawn line. Absent = the harness's
   own workspace-write, which still asks, so the multi-user clamp is the
   only-if-sent branch and clamps to workspace-write, never read-only.

3. It is the only non-claude mode that passes hooksAvailableForMode(), and it
   earned that. The terminal front door reports idle/working/blocked to a
   supervising process over a generic env-gated contract; a generated shim
   (deepseek-status-shim.ts) makes Codeman that supervisor and forwards each
   report to /api/hook-event as stop / agent_working / permission_prompt. So a
   dsh session gets definitive respawn triggers, real wait-endpoint signals and
   real Approvals Inbox items instead of output-stabilization guesswork.
   `agent_working` is new (157th SSE constant) and joins
   APPROVAL_RESOLVING_EVENTS so a dialog answered in the terminal clears its
   alert at once.

The resolver needs the strictest identity probe of the family: `dsh` is not
merely a squattable npm name, Debian ships an unrelated `dsh` (dancer's shell),
so `dsh --help` must print the harness's own banner before a candidate is
handed a spawn line.

Model is deliberately not a session field -- it is a composition entry in the
profile's config tree. Env allowlist gains DSH_* and DEEPSEEK_* only; provider
keys named by a settings-file `apiKeyEnv` stay out, which is pi's
34-provider-key problem in a new shape.

Verified live against dsh 0.1.1-rc.2 and @deepseek-harness-tui/dsh-tui: the
status endpoint's two-part answer, the no-profile refusal, the profile
bootstrap, a real session whose pane runs `dsh --profile dsh-tui` with the
permission mode injected via setenv, and the full status bridge -- a
send-and-wait returned signal "stop" from a real turn, and blocked/working
created and cleared an Approvals Inbox item.

Docs: docs/deepseek-integration.md (guide), docs/deepseek-integration-plan.md
(decisions + honest gaps). Tests: test/deepseek-mode.test.ts,
test/deepseek-cli-resolver.test.ts.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-24 03:37:56 +02:00

221 lines
9.3 KiB
TypeScript

/**
* WebServer.renderIndexHtml — server-side gating of the index shell:
* - multi-monitor button reveal (stable class-marker, not brittle copy match)
* - solo (/session/:id) global injection + escaping, and settings skipped
* - gesture overlay availability vs. enablement (CODEMAN_GESTURE + setting)
* - settings read FRESH so a post-save reload doesn't render stale state
*
* WebServer's constructor only assigns fields (no port bind), so we construct it
* directly, swap in a tiny indexHtmlTemplate, and stub readSettings to avoid disk.
*
* Port: N/A (no server start).
*/
import { describe, it, expect, afterEach, vi } from 'vitest';
import { WebServer } from '../src/web/server.js';
import { isClaudeAvailable } from '../src/utils/claude-cli-resolver.js';
import { isOpenCodeAvailable } from '../src/utils/opencode-cli-resolver.js';
import { isCodexAvailable } from '../src/utils/codex-cli-resolver.js';
import { isGeminiAvailable } from '../src/utils/gemini-cli-resolver.js';
import { isAntigravityAvailable } from '../src/utils/antigravity-cli-resolver.js';
import { isPiAvailable } from '../src/utils/pi-cli-resolver.js';
import { isGrokAvailable } from '../src/utils/grok-cli-resolver.js';
import { isDeepSeekAvailable, isDeepSeekRunnable } from '../src/utils/deepseek-cli-resolver.js';
import { isCloudflaredAvailable } from '../src/utils/cloudflared-resolver.js';
import { isGitAvailable } from '../src/git-clone.js';
// renderIndexHtml probes the real PATH for every CLI, which would make the
// assertions below depend on whatever happens to be installed on the machine
// running the suite. Default them all to "not installed" and opt in per test.
vi.mock('../src/utils/claude-cli-resolver.js', () => ({
isClaudeAvailable: vi.fn(() => false),
findClaudeDir: vi.fn(() => null),
}));
vi.mock('../src/utils/opencode-cli-resolver.js', () => ({
isOpenCodeAvailable: vi.fn(() => false),
resolveOpenCodeDir: vi.fn(() => null),
}));
vi.mock('../src/utils/codex-cli-resolver.js', () => ({
isCodexAvailable: vi.fn(() => false),
resolveCodexDir: vi.fn(() => null),
}));
vi.mock('../src/utils/gemini-cli-resolver.js', () => ({
isGeminiAvailable: vi.fn(() => false),
resolveGeminiDir: vi.fn(() => null),
}));
vi.mock('../src/utils/antigravity-cli-resolver.js', () => ({
isAntigravityAvailable: vi.fn(() => false),
resolveAntigravityDir: vi.fn(() => null),
}));
vi.mock('../src/utils/pi-cli-resolver.js', () => ({
isPiAvailable: vi.fn(() => false),
resolvePiDir: vi.fn(() => null),
getPiCliVersion: vi.fn(() => null),
}));
vi.mock('../src/utils/grok-cli-resolver.js', () => ({
isGrokAvailable: vi.fn(() => false),
resolveGrokDir: vi.fn(() => null),
getGrokCliVersion: vi.fn(() => null),
}));
// DeepSeek is the one mode with a two-part availability answer (binary AND a
// pane-capable profile), so both probes are mocked independently.
vi.mock('../src/utils/deepseek-cli-resolver.js', () => ({
isDeepSeekAvailable: vi.fn(() => false),
isDeepSeekRunnable: vi.fn(() => false),
resolveDeepSeekDir: vi.fn(() => null),
getDeepSeekCliVersion: vi.fn(() => null),
listDeepSeekProfiles: vi.fn(() => []),
resolveDefaultDeepSeekProfile: vi.fn(() => null),
}));
vi.mock('../src/utils/cloudflared-resolver.js', () => ({
isCloudflaredAvailable: vi.fn(() => false),
resolveCloudflaredPath: vi.fn(() => null),
}));
// git gates the Add Case -> Clone Repo tab (#236), so it rides in the same object.
vi.mock('../src/git-clone.js', () => ({
isGitAvailable: vi.fn(() => false),
}));
const TEMPLATE = [
'<head>',
'<title>Codeman</title>',
'</head>',
'<body>',
'<button class="btn-icon-header btn-multimonitor btn-multimonitor--hidden" aria-label="Open Codeman across all displays"></button>',
'</body>',
].join('\n');
function makeServer(settings: Record<string, unknown> = {}) {
const server = new WebServer(0, false, true);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(server as any).indexHtmlTemplate = TEMPLATE;
const readSettings = vi.fn(async () => settings);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(server as any).readSettings = readSettings;
return { server, readSettings };
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const render = (server: WebServer, solo?: string): Promise<string> => (server as any).renderIndexHtml(solo);
const ORIG_GESTURE = process.env.CODEMAN_GESTURE;
afterEach(() => {
if (ORIG_GESTURE === undefined) delete process.env.CODEMAN_GESTURE;
else process.env.CODEMAN_GESTURE = ORIG_GESTURE;
});
describe('WebServer.renderIndexHtml', () => {
it('keeps the multi-monitor button hidden by default and reads settings FRESH', async () => {
const { server, readSettings } = makeServer({});
const html = await render(server);
expect(html).toContain('btn-multimonitor--hidden');
// forceFresh=true — fixes the post-save reload race against the 2s cache.
expect(readSettings).toHaveBeenCalledWith(true);
});
it('reveals the multi-monitor button when showMultiMonitorButton is set', async () => {
const { server } = makeServer({ showMultiMonitorButton: true });
const html = await render(server);
expect(html).not.toContain('btn-multimonitor--hidden');
expect(html).toContain('btn-multimonitor"'); // class list still present, only the marker stripped
});
it('injects the solo global and skips settings for a /session/:id window', async () => {
const { server, readSettings } = makeServer({ showMultiMonitorButton: true });
const html = await render(server, 'sess-123');
expect(html).toContain('window.__CODEMAN_SOLO__="sess-123"');
expect(readSettings).not.toHaveBeenCalled();
// Solo skips settings, so the button is NOT revealed even though the setting is on.
expect(html).toContain('btn-multimonitor--hidden');
});
it('escapes the solo id so it cannot break out of the inline <script>', async () => {
const { server } = makeServer({});
const html = await render(server, 'a</script><b>');
expect(html).not.toContain('</script><b>');
expect(html).toContain('\\u003c');
});
it('exposes gesture availability but injects the bundle only when enabled', async () => {
process.env.CODEMAN_GESTURE = '1';
let { server } = makeServer({ gestureControlEnabled: false });
let html = await render(server);
expect(html).toContain('window.__codemanGestureAvailable=true');
expect(html).not.toContain('gesture-codeman.js');
({ server } = makeServer({ gestureControlEnabled: true }));
html = await render(server);
expect(html).toContain('window.__codemanGestureAvailable=true');
expect(html).toContain('gesture-codeman.js');
});
it('reports every tool the welcome buttons, run menu and Codex tab gate on', async () => {
vi.mocked(isClaudeAvailable).mockReturnValue(true);
vi.mocked(isOpenCodeAvailable).mockReturnValue(false);
vi.mocked(isCodexAvailable).mockReturnValue(true);
vi.mocked(isGeminiAvailable).mockReturnValue(false);
vi.mocked(isAntigravityAvailable).mockReturnValue(false);
vi.mocked(isPiAvailable).mockReturnValue(true);
vi.mocked(isGrokAvailable).mockReturnValue(false);
vi.mocked(isCloudflaredAvailable).mockReturnValue(true);
vi.mocked(isGitAvailable).mockReturnValue(true);
const { server } = makeServer({});
const html = await render(server);
const flags = JSON.parse(html.match(/window\.__codemanCliAvailable=(\{.*?\});/)![1]);
// Every key must be PRESENT, not merely truthy where installed: the client
// treats a missing key as available, so a dropped key silently un-gates.
expect(flags).toEqual({
claude: true,
opencode: false,
codex: true,
gemini: false,
antigravity: false,
pi: true,
grok: false,
deepseek: false,
deepseekBinary: false,
cloudflared: true,
git: true,
});
});
it('still emits the object when nothing at all is installed', async () => {
// The all-false case is the one that matters most and the easiest to get
// wrong by only injecting when something resolves.
for (const probe of [
isClaudeAvailable,
isOpenCodeAvailable,
isCodexAvailable,
isGeminiAvailable,
isAntigravityAvailable,
isPiAvailable,
isGrokAvailable,
isDeepSeekAvailable,
isDeepSeekRunnable,
isCloudflaredAvailable,
isGitAvailable,
]) {
vi.mocked(probe).mockReturnValue(false);
}
const { server } = makeServer({});
const html = await render(server);
expect(html).toContain('window.__codemanCliAvailable=');
const flags = JSON.parse(html.match(/window\.__codemanCliAvailable=(\{.*?\});/)![1]);
expect(Object.values(flags).every((v) => v === false)).toBe(true);
});
it('skips the probe for a solo window, which has no welcome screen or run menu', async () => {
vi.mocked(isCodexAvailable).mockReturnValue(true);
const { server } = makeServer({});
const html = await render(server, 'sess-123');
expect(html).not.toContain('__codemanCliAvailable');
});
it('does not expose gesture at all when CODEMAN_GESTURE is unset', async () => {
delete process.env.CODEMAN_GESTURE;
const { server } = makeServer({ gestureControlEnabled: true });
const html = await render(server);
expect(html).not.toContain('__codemanGestureAvailable');
expect(html).not.toContain('gesture-codeman.js');
});
});