mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-16 03:09:33 +01:00
fix(custom-model): create missing dsh home dirs before linking, rebuild restore bookkeeping, dedicated custom key var, schema guards for the real-home recipe
- linkFromRealHomeDirs marks directory entries: missing dirs are created (0700) instead of leaving a dangling link that failed every prompt with ENOENT; missing file targets are skipped - _restoreCustomModel rebuilds the bookkeeping from the CURRENT recipe (configDir + env-key union) so a selection saved under the old env recipe can still be cleared after upgrade; drop the dead session-home recovery lookup - deepseek's patch now references CODEMAN_CUSTOM_MODEL_API_KEY, so an in-session /model switch back to the official route cannot carry the custom key to api.deepseek.com (privilegedEnvKeys updated) - schema: realHomeFallback must be one relative segment; linkFromRealHome requires it and must not collide with fileName - docs: maintainer-verified real-dsh run replaces the outstanding-verification wording; shares-vs-isolates note; plan table row refreshed
This commit is contained in:
1 parent
c646613c56
commit
1464332e91
14 files changed
+335
-75
No files matched your search
@@ -55,6 +55,47 @@ describe('customModelInjection.launchModel', () => {
|
||||
});
|
||||
});
|
||||
|
||||
/** Mutates the shipped deepseek configDir recipe (the one real-home-linking entry) and expects rejection. */
|
||||
function expectRejectedOnDeepSeek(mutate: (recipe: Record<string, unknown>) => void, because: string): void {
|
||||
const entry = baseEntry('deepseek');
|
||||
const recipe = (entry.capabilities as Record<string, unknown>).customModelInjection as Record<string, unknown>;
|
||||
mutate(recipe);
|
||||
const result = CliEntrySchema.safeParse(entry);
|
||||
expect(result.success, `expected rejection: ${because}`).toBe(false);
|
||||
}
|
||||
|
||||
describe('configDir real-home linking (linkFromRealHome / realHomeFallback)', () => {
|
||||
it('rejects a realHomeFallback that is not a single relative path segment', () => {
|
||||
// The consumer joins it under the user's home, so any of these escapes that home.
|
||||
for (const bad of ['../x', '.dsh/evil', '/.dsh', '..']) {
|
||||
expectRejectedOnDeepSeek((r) => {
|
||||
r.realHomeFallback = bad;
|
||||
}, `realHomeFallback ${JSON.stringify(bad)}`);
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts a shipped-style dot-prefixed segment', () => {
|
||||
const entry = baseEntry('deepseek');
|
||||
expect(CliEntrySchema.safeParse(entry).success).toBe(true); // ships as `.dsh`
|
||||
const recipe = (entry.capabilities as Record<string, unknown>).customModelInjection as Record<string, unknown>;
|
||||
recipe.realHomeFallback = '.dsh-relocated';
|
||||
expect(CliEntrySchema.safeParse(entry).success).toBe(true);
|
||||
});
|
||||
|
||||
it('requires realHomeFallback whenever linkFromRealHome is declared', () => {
|
||||
expectRejectedOnDeepSeek((r) => {
|
||||
delete r.realHomeFallback;
|
||||
}, 'without it the consumer would have to hardcode a per-CLI home default');
|
||||
});
|
||||
|
||||
it('rejects a linked entry that collides with fileName', () => {
|
||||
// A symlink at the generated file's own name would write THROUGH into the user's real config.
|
||||
expectRejectedOnDeepSeek((r) => {
|
||||
r.linkFromRealHome = ['cordis.patch.yml', 'profiles'];
|
||||
}, 'linkFromRealHome containing fileName');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the shipped catalog', () => {
|
||||
it('validates every stock entry exactly as shipped', () => {
|
||||
// If this fails, the catalog cannot load at all — every other test here is downstream.
|
||||
|
||||
@@ -57,7 +57,7 @@ describe('applyCustomModelInjection: context length', () => {
|
||||
const sessionId = 'sess-deepseek-context';
|
||||
sessionsToClean.push(sessionId);
|
||||
const applied = applyCustomModelInjection(entryOrThrow('deepseek'), endpoint, 'qwen3', sessionId, 32768);
|
||||
expect(Object.keys(applied?.envOverrides ?? {}).sort()).toEqual(['DEEPSEEK_API_KEY', 'DSH_HOME']);
|
||||
expect(Object.keys(applied?.envOverrides ?? {}).sort()).toEqual(['CODEMAN_CUSTOM_MODEL_API_KEY', 'DSH_HOME']);
|
||||
expect(readFileSync(join(applied!.configDir!, 'cordis.patch.yml'), 'utf8')).toContain('"contextWindow": 32768');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -194,12 +194,12 @@ describe('custom-model-injection contract (mock server)', () => {
|
||||
const injection = buildCustomModelInjection(entryOrThrow('deepseek'), endpointFor(mock), 'qwen3');
|
||||
if (injection.kind !== 'configDir') throw new Error('unreachable');
|
||||
expect(injection.dirEnvVar).toBe('DSH_HOME');
|
||||
expect(Object.keys(injection.extraEnv ?? {})).toEqual(['DEEPSEEK_API_KEY']);
|
||||
expect(Object.keys(injection.extraEnv ?? {})).toEqual(['CODEMAN_CUSTOM_MODEL_API_KEY']);
|
||||
const provider = JSON.parse(injection.files[0].content)[0].config.providers['codeman-custom'];
|
||||
expect(provider.baseURL).toBe(`${mock.baseUrl}/v1`);
|
||||
expect(provider.models[0].id).toBe('qwen3');
|
||||
|
||||
await callOpenAiCompat(provider.baseURL, injection.extraEnv!.DEEPSEEK_API_KEY, 'qwen3');
|
||||
await callOpenAiCompat(provider.baseURL, injection.extraEnv!.CODEMAN_CUSTOM_MODEL_API_KEY, 'qwen3');
|
||||
|
||||
expect(mock.requests[0].path).toBe('/v1/chat/completions');
|
||||
expect(mock.requests[0].headers.authorization).toBe('Bearer contract-test-key');
|
||||
|
||||
@@ -183,9 +183,16 @@ describe('buildCustomModelInjection', () => {
|
||||
const result = buildCustomModelInjection(entryOrThrow('deepseek'), endpoint, 'qwen3');
|
||||
if (result.kind !== 'configDir') throw new Error('Expected isolated DeepSeek config');
|
||||
expect(result.dirEnvVar).toBe('DSH_HOME');
|
||||
expect(result.extraEnv).toEqual({ DEEPSEEK_API_KEY: 'my-key' });
|
||||
expect(result.extraEnv).toEqual({ CODEMAN_CUSTOM_MODEL_API_KEY: 'my-key' });
|
||||
expect(result.files[0].content).not.toContain('my-key');
|
||||
const patch = JSON.parse(result.files[0].content);
|
||||
// The patch references the DEDICATED var by name, never dsh's own DEEPSEEK_API_KEY —
|
||||
// dsh's llm-deepseek/web-search rows read that too and would leak this key to
|
||||
// api.deepseek.com on an in-session /model switch back to the official route.
|
||||
expect(patch.find((row: { id: string }) => row.id === 'llm-pi-ai').config.providers['codeman-custom'].apiKeyEnv).toBe(
|
||||
'CODEMAN_CUSTOM_MODEL_API_KEY'
|
||||
);
|
||||
expect(result.files[0].content).not.toContain('DEEPSEEK_API_KEY');
|
||||
expect(patch.find((row: { id: string }) => row.id === 'dsh-tui').config.model).toBe('qwen3');
|
||||
});
|
||||
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
/**
|
||||
* @fileoverview Boot recovery re-derives a saved custom-model selection through
|
||||
* `_rebuildCustomModelEnv`, and the `linkFromRealHome` recipe must resolve the CLI's
|
||||
* real home from the SESSION's own env overrides first: the user who relocated dsh
|
||||
* (allowlisted `DSH_HOME`) runs their CLI against THAT home, and recovery must link the
|
||||
* regenerated config dir back to it, not to whatever the server's environment says.
|
||||
* `_rebuildCustomModelEnv` and rebuilds the BOOKKEEPING from what the CURRENT recipe
|
||||
* applied — not from the saved record. A selection persisted while deepseek still used
|
||||
* the old env redirect comes back env-shaped (envKeys `DEEPSEEK_BASE_URL`/
|
||||
* `DEEPSEEK_API_KEY`, no `configDir`) although the recipe now writes a per-session patch
|
||||
* home: restoring the saved record unchanged left `DSH_HOME` on a generated config dir
|
||||
* that clearing could never delete.
|
||||
*
|
||||
* `_rebuildCustomModelEnv` reads no `this` state (it re-derives everything from the endpoint
|
||||
* store and the Session it is handed), so it is driven straight off the prototype with an
|
||||
* empty receiver — `restoreMuxSessions()` itself cannot be reached under vitest, the same
|
||||
* constraint recorded in test/session-model-recovery.test.ts.
|
||||
* Real-home resolution is NOT recovered from the session's env overrides any more:
|
||||
* `getEnvOverridesForPersist()` keeps only `CLAUDE_CODE_*`/`CLAUDE_CONFIG_DIR`, so a
|
||||
* session's own `DSH_HOME` never survives a real restart and the lookup only ever hit on
|
||||
* the first apply in-process. Recovery falls back to the server's `DSH_HOME` or the
|
||||
* recipe's `realHomeFallback` (~/.dsh) — see `_rebuildCustomModelEnv`'s comment.
|
||||
*
|
||||
* `_restoreCustomModel` reads no `this` state beyond the rebuild helper (it re-derives
|
||||
* everything from the endpoint store and the Session it is handed), so it is driven off
|
||||
* the prototype with a minimal receiver — `restoreMuxSessions()` itself cannot be
|
||||
* reached under vitest, the same constraint recorded in test/session-model-recovery.test.ts.
|
||||
*/
|
||||
import { mkdirSync, realpathSync, rmSync } from 'node:fs';
|
||||
import { mkdirSync, rmSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -21,13 +29,14 @@ import { Session } from '../src/session.js';
|
||||
import { WebServer } from '../src/web/server.js';
|
||||
import type { CustomModelBookkeeping } from '../src/types/session.js';
|
||||
|
||||
type RebuildFn = (session: Session, saved: CustomModelBookkeeping) => Promise<Record<string, string> | undefined>;
|
||||
|
||||
/** The real method, with an empty receiver — see the file header for why that is sound. */
|
||||
function rebuildCustomModelEnv(session: Session, saved: CustomModelBookkeeping) {
|
||||
const fn = (WebServer.prototype as unknown as { _rebuildCustomModelEnv: RebuildFn })._rebuildCustomModelEnv;
|
||||
expect(typeof fn, '_rebuildCustomModelEnv vanished from WebServer.prototype').toBe('function');
|
||||
return fn.call({}, session, saved);
|
||||
/** The real pair, on a receiver that only carries the rebuild helper — see the header. */
|
||||
async function restoreCustomModel(session: Session, saved: CustomModelBookkeeping): Promise<void> {
|
||||
const proto = WebServer.prototype as unknown as {
|
||||
_rebuildCustomModelEnv: (session: Session, saved: CustomModelBookkeeping) => Promise<unknown>;
|
||||
_restoreCustomModel: (session: Session, saved: CustomModelBookkeeping) => Promise<void>;
|
||||
};
|
||||
expect(typeof proto._restoreCustomModel, '_restoreCustomModel vanished from WebServer.prototype').toBe('function');
|
||||
await proto._restoreCustomModel.call({ _rebuildCustomModelEnv: proto._rebuildCustomModelEnv }, session, saved);
|
||||
}
|
||||
|
||||
function endpoint(): CustomModelHost {
|
||||
@@ -40,7 +49,7 @@ function endpoint(): CustomModelHost {
|
||||
};
|
||||
}
|
||||
|
||||
describe('_rebuildCustomModelEnv: real-home resolution for linkFromRealHome', () => {
|
||||
describe('_restoreCustomModel: bookkeeping rebuilt from the current recipe', () => {
|
||||
const configs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
@@ -48,23 +57,46 @@ describe('_rebuildCustomModelEnv: real-home resolution for linkFromRealHome', ()
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it('links an isolated deepseek home from the SESSION’s own DSH_HOME, not the server’s', async () => {
|
||||
// The user who relocated dsh runs their CLI against THAT home; recovery must re-link
|
||||
// the session's generated config dir back to it even though the value never persists
|
||||
// into the server's environment. The server's DSH_HOME is emptied deliberately: with
|
||||
// the session lookup working, the fallback home is never consulted, and with it
|
||||
// broken this test gets a link into ~/.dsh rather than a pass.
|
||||
const sessionHome = join(homedir(), 'codeman-recovery-dsh-home');
|
||||
mkdirSync(join(sessionHome, 'profiles'), { recursive: true });
|
||||
vi.stubEnv('DSH_HOME', '');
|
||||
it('carries the configDir and env-key union for a selection saved by the old env recipe', async () => {
|
||||
// Saved exactly as 1.31.0-1.47.0 persisted a deepseek selection: the env recipe's two
|
||||
// keys, no configDir. The rebuilt record must carry the per-session config dir the
|
||||
// CURRENT recipe wrote (so clearing deletes it) while KEEPING the saved keys, which
|
||||
// the tmux session may still carry `setenv`s for (the union is what a clear unsets).
|
||||
const dshHome = join(homedir(), 'codeman-recovery-dsh-home');
|
||||
mkdirSync(join(dshHome, 'profiles'), { recursive: true });
|
||||
vi.stubEnv('DSH_HOME', dshHome);
|
||||
await writeCustomModelHosts(getDataDir(), [endpoint()]);
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'deepseek', envOverrides: { DSH_HOME: sessionHome } });
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'deepseek' });
|
||||
configs.push(session.id);
|
||||
|
||||
const env = await rebuildCustomModelEnv(session, { endpointId: 'ep', modelId: 'qwen3', envKeys: [] });
|
||||
await restoreCustomModel(session, {
|
||||
endpointId: 'ep',
|
||||
modelId: 'qwen3',
|
||||
label: 'Ep',
|
||||
envKeys: ['DEEPSEEK_BASE_URL', 'DEEPSEEK_API_KEY'],
|
||||
});
|
||||
|
||||
expect(env?.DSH_HOME).toBe(customModelConfigDir(session.id));
|
||||
expect(realpathSync(join(env!.DSH_HOME, 'profiles'))).toBe(join(sessionHome, 'profiles'));
|
||||
rmSync(sessionHome, { recursive: true, force: true });
|
||||
const persisted = session.getCustomModelForPersist();
|
||||
expect(persisted?.configDir).toBe(customModelConfigDir(session.id));
|
||||
expect(persisted?.launchModel).toBeUndefined();
|
||||
expect(new Set(persisted?.envKeys)).toEqual(
|
||||
new Set(['DEEPSEEK_BASE_URL', 'DEEPSEEK_API_KEY', 'DSH_HOME', 'CODEMAN_CUSTOM_MODEL_API_KEY'])
|
||||
);
|
||||
rmSync(dshHome, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('restores an env-shaped record unchanged when the endpoint is gone, so a clear still works', async () => {
|
||||
await writeCustomModelHosts(getDataDir(), []);
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'deepseek' });
|
||||
const saved: CustomModelBookkeeping = {
|
||||
endpointId: 'gone',
|
||||
modelId: 'qwen3',
|
||||
label: 'Gone',
|
||||
envKeys: ['DEEPSEEK_BASE_URL', 'DEEPSEEK_API_KEY'],
|
||||
};
|
||||
|
||||
await restoreCustomModel(session, saved);
|
||||
|
||||
expect(session.getCustomModelForPersist()).toEqual(saved);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { mkdirSync, readFileSync, readlinkSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { homedir, tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { getCli } from '../src/config/cli-registry/index.js';
|
||||
@@ -32,7 +32,11 @@ describe('DeepSeek custom endpoint isolation', () => {
|
||||
if (!applied?.configDir) throw new Error('Missing isolated profile');
|
||||
const content = readFileSync(join(applied.configDir, 'cordis.patch.yml'), 'utf8');
|
||||
expect(content).not.toContain(endpoint.apiKey);
|
||||
expect(applied.envOverrides.DEEPSEEK_API_KEY).toBe(endpoint.apiKey);
|
||||
// The dedicated key var, never DEEPSEEK_API_KEY: dsh's own llm-deepseek/web-search
|
||||
// rows read that too, and an in-session /model switch back to the official route must
|
||||
// not take the custom endpoint's key to api.deepseek.com with it.
|
||||
expect(applied.envOverrides.CODEMAN_CUSTOM_MODEL_API_KEY).toBe(endpoint.apiKey);
|
||||
expect(applied.envOverrides.DEEPSEEK_API_KEY).toBeUndefined();
|
||||
const patch = JSON.parse(content);
|
||||
const provider = patch.find((row: { id: string }) => row.id === 'llm-pi-ai').config.providers['codeman-custom'];
|
||||
expect(provider.api).toBe('openai-completions');
|
||||
@@ -50,15 +54,65 @@ describe('DeepSeek custom endpoint isolation', () => {
|
||||
// must keep applying through the redirect.
|
||||
expect(realpathSync(join(applied.configDir, 'sessions'))).toBe(join(realHome, 'sessions'));
|
||||
expect(realpathSync(join(applied.configDir, 'settings.yaml'))).toBe(join(realHome, 'settings.yaml'));
|
||||
// Re-apply onto the same config dir (boot recovery re-runs this every restart) with one
|
||||
// link dangling: the lstat guard must skip every existing link, broken ones included,
|
||||
// which the old existsSync check missed — recreating them would raise EEXIST.
|
||||
rmSync(join(realHome, 'sessions'), { recursive: true, force: true });
|
||||
// Re-apply onto the same config dir (boot recovery re-runs this every restart): the
|
||||
// lstat guard must skip every existing link, which the old existsSync check missed —
|
||||
// recreating them would raise EEXIST.
|
||||
const reapplied = applyCustomModelInjection(entry, endpoint, 'chosen-model', 'deepseek-probe', 131072);
|
||||
expect(reapplied?.envOverrides.DSH_HOME).toBe(applied.configDir);
|
||||
expect(readlinkSync(join(applied.configDir, 'sessions'))).toBe(join(realHome, 'sessions'));
|
||||
expect(readFileSync(original, 'utf8')).toBe('original profile');
|
||||
removeConfigDir(applied.configDir);
|
||||
expect(readFileSync(original, 'utf8')).toBe('original profile');
|
||||
});
|
||||
|
||||
it('creates missing directory targets before linking, skips a missing file target, stays fine on re-apply', () => {
|
||||
// A fresh install (or relocated DSH_HOME) has never run a turn, so the real home
|
||||
// carries none of the linked entries. Linking a missing DIRECTORY left a dangling
|
||||
// symlink whose every write dsh attempts THROUGH it failed with ENOENT on EVERY turn,
|
||||
// and the lstat guard kept that dangling link forever. Directories are now created
|
||||
// (0700, what dsh itself does on a first turn) before linking; a missing FILE
|
||||
// (`settings.yaml`) is simply skipped. A stubbed HOME and CODEMAN_DATA_DIR keep both
|
||||
// the fake real home and the generated dir off the developer's own dotfiles.
|
||||
const sandbox = mkdtempSync(join(tmpdir(), 'dsh-fresh-home-'));
|
||||
const realHome = join(sandbox, '.dsh');
|
||||
mkdirSync(realHome, { recursive: true }); // exists, but no sessions/, no profiles/, no settings.yaml
|
||||
vi.stubEnv('HOME', sandbox);
|
||||
vi.stubEnv('CODEMAN_DATA_DIR', join(sandbox, 'data'));
|
||||
vi.stubEnv('DSH_HOME', ''); // force resolution down to the recipe's `realHomeFallback`
|
||||
try {
|
||||
const entry = getCli('deepseek');
|
||||
if (!entry) throw new Error('Missing DeepSeek entry');
|
||||
const endpoint = { id: 'local', label: 'Local', baseUrl: 'http://box:8080', apiKey: 'private-probe-key' };
|
||||
const applied = applyCustomModelInjection(entry, endpoint, 'chosen-model', 'deepseek-probe', 131072);
|
||||
if (!applied?.configDir) throw new Error('Missing isolated profile');
|
||||
|
||||
expect(realpathSync(join(applied.configDir, 'sessions'))).toBe(join(realHome, 'sessions'));
|
||||
expect(realpathSync(join(applied.configDir, 'profiles'))).toBe(join(realHome, 'profiles'));
|
||||
expect(statSync(join(realHome, 'sessions')).mode & 0o777).toBe(0o700);
|
||||
// The missing FILE target is skipped outright: not a dangling link either — lstat
|
||||
// must find nothing, so a later apply (once the file exists for real) links it.
|
||||
expect(existsSync(join(realHome, 'settings.yaml'))).toBe(false);
|
||||
expect(readlinkSafe(join(applied.configDir, 'settings.yaml'))).toBeUndefined();
|
||||
|
||||
// Re-apply stays fine (boot recovery re-runs it every restart): idempotent...
|
||||
const reapplied = applyCustomModelInjection(entry, endpoint, 'chosen-model', 'deepseek-probe', 131072);
|
||||
expect(reapplied?.envOverrides.DSH_HOME).toBe(applied.configDir);
|
||||
// ...and a target deleted AFTER linking keeps the existing link untouched (the
|
||||
// lstat guard), rather than recreating it and throwing EEXIST.
|
||||
rmSync(join(realHome, 'sessions'), { recursive: true, force: true });
|
||||
expect(
|
||||
applyCustomModelInjection(entry, endpoint, 'chosen-model', 'deepseek-probe', 131072)?.envOverrides.DSH_HOME
|
||||
).toBe(applied.configDir);
|
||||
expect(readlinkSync(join(applied.configDir, 'sessions'))).toBe(join(realHome, 'sessions'));
|
||||
} finally {
|
||||
rmSync(sandbox, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/** readlinkSync without the throw an absent link causes (ENOENT -> undefined). */
|
||||
function readlinkSafe(path: string): string | undefined {
|
||||
try {
|
||||
return readlinkSync(path);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user