Merge branch 'main' into fix/imessage-groupish-threads
This commit is contained in:
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
const MINIMAX_KEY = process.env.MINIMAX_API_KEY ?? "";
|
||||
const MINIMAX_BASE_URL =
|
||||
process.env.MINIMAX_BASE_URL?.trim() || "https://api.minimax.io/v1";
|
||||
process.env.MINIMAX_BASE_URL?.trim() || "https://api.minimax.io/anthropic";
|
||||
const MINIMAX_MODEL = process.env.MINIMAX_MODEL?.trim() || "MiniMax-M2.1";
|
||||
const LIVE = process.env.MINIMAX_LIVE_TEST === "1" || process.env.LIVE === "1";
|
||||
|
||||
@@ -11,15 +11,16 @@ const describeLive = LIVE && MINIMAX_KEY ? describe : describe.skip;
|
||||
|
||||
describeLive("minimax live", () => {
|
||||
it("returns assistant text", async () => {
|
||||
const model: Model<"openai-completions"> = {
|
||||
const model: Model<"anthropic-messages"> = {
|
||||
id: MINIMAX_MODEL,
|
||||
name: `MiniMax ${MINIMAX_MODEL}`,
|
||||
api: "openai-completions",
|
||||
api: "anthropic-messages",
|
||||
provider: "minimax",
|
||||
baseUrl: MINIMAX_BASE_URL,
|
||||
reasoning: false,
|
||||
reasoning: MINIMAX_MODEL === "MiniMax-M2",
|
||||
input: ["text"],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
// Pricing: placeholder values (per 1M tokens, multiplied by 1000 for display)
|
||||
cost: { input: 15, output: 60, cacheRead: 2, cacheWrite: 10 },
|
||||
contextWindow: 200000,
|
||||
maxTokens: 8192,
|
||||
};
|
||||
|
||||
@@ -304,6 +304,19 @@ describe("sanitizeSessionMessagesImages", () => {
|
||||
expect(out[0]?.role).toBe("user");
|
||||
});
|
||||
|
||||
it("drops empty assistant error messages", async () => {
|
||||
const input = [
|
||||
{ role: "user", content: "hello" },
|
||||
{ role: "assistant", stopReason: "error", content: [] },
|
||||
{ role: "assistant", stopReason: "error" },
|
||||
] satisfies AgentMessage[];
|
||||
|
||||
const out = await sanitizeSessionMessagesImages(input, "test");
|
||||
|
||||
expect(out).toHaveLength(1);
|
||||
expect(out[0]?.role).toBe("user");
|
||||
});
|
||||
|
||||
it("leaves non-assistant messages unchanged", async () => {
|
||||
const input = [
|
||||
{ role: "user", content: "hello" },
|
||||
|
||||
@@ -61,6 +61,27 @@ export async function ensureSessionHeader(params: {
|
||||
|
||||
type ContentBlock = AgentToolResult<unknown>["content"][number];
|
||||
|
||||
export function isEmptyAssistantMessageContent(
|
||||
message: Extract<AgentMessage, { role: "assistant" }>,
|
||||
): boolean {
|
||||
const content = message.content;
|
||||
if (content == null) return true;
|
||||
if (!Array.isArray(content)) return false;
|
||||
return content.every((block) => {
|
||||
if (!block || typeof block !== "object") return true;
|
||||
const rec = block as { type?: unknown; text?: unknown };
|
||||
if (rec.type !== "text") return false;
|
||||
return typeof rec.text !== "string" || rec.text.trim().length === 0;
|
||||
});
|
||||
}
|
||||
|
||||
function isEmptyAssistantErrorMessage(
|
||||
message: Extract<AgentMessage, { role: "assistant" }>,
|
||||
): boolean {
|
||||
if (message.stopReason !== "error") return false;
|
||||
return isEmptyAssistantMessageContent(message);
|
||||
}
|
||||
|
||||
export async function sanitizeSessionMessagesImages(
|
||||
messages: AgentMessage[],
|
||||
label: string,
|
||||
@@ -101,6 +122,9 @@ export async function sanitizeSessionMessagesImages(
|
||||
|
||||
if (role === "assistant") {
|
||||
const assistantMsg = msg as Extract<AgentMessage, { role: "assistant" }>;
|
||||
if (isEmptyAssistantErrorMessage(assistantMsg)) {
|
||||
continue;
|
||||
}
|
||||
const content = assistantMsg.content;
|
||||
if (Array.isArray(content)) {
|
||||
const filteredContent = content.filter((block) => {
|
||||
|
||||
@@ -101,6 +101,10 @@ export function buildAuthChoiceOptions(params: {
|
||||
// Token flow is currently Anthropic-only; use CLI for advanced providers.
|
||||
options.push({ value: "minimax-cloud", label: "MiniMax M2.1 (minimax.io)" });
|
||||
options.push({ value: "minimax", label: "Minimax M2.1 (LM Studio)" });
|
||||
options.push({
|
||||
value: "minimax-api",
|
||||
label: "MiniMax API (platform.minimax.io)",
|
||||
});
|
||||
if (params.includeSkip) {
|
||||
options.push({ value: "skip", label: "Skip for now" });
|
||||
}
|
||||
|
||||
@@ -36,6 +36,8 @@ import {
|
||||
} from "./google-gemini-model-default.js";
|
||||
import {
|
||||
applyAuthProfileConfig,
|
||||
applyMinimaxApiConfig,
|
||||
applyMinimaxApiProviderConfig,
|
||||
applyMinimaxConfig,
|
||||
applyMinimaxHostedConfig,
|
||||
applyMinimaxHostedProviderConfig,
|
||||
@@ -629,6 +631,24 @@ export async function applyAuthChoice(params: {
|
||||
agentModelOverride = "lmstudio/minimax-m2.1-gs32";
|
||||
await noteAgentModel("lmstudio/minimax-m2.1-gs32");
|
||||
}
|
||||
} else if (params.authChoice === "minimax-api") {
|
||||
const key = await params.prompter.text({
|
||||
message: "Enter MiniMax API key",
|
||||
validate: (value) => (value?.trim() ? undefined : "Required"),
|
||||
});
|
||||
await setMinimaxApiKey(String(key).trim(), params.agentDir);
|
||||
nextConfig = applyAuthProfileConfig(nextConfig, {
|
||||
profileId: "minimax:default",
|
||||
provider: "minimax",
|
||||
mode: "api_key",
|
||||
});
|
||||
if (params.setDefaultModel) {
|
||||
nextConfig = applyMinimaxApiConfig(nextConfig);
|
||||
} else {
|
||||
nextConfig = applyMinimaxApiProviderConfig(nextConfig);
|
||||
agentModelOverride = "minimax/MiniMax-M2.1";
|
||||
await noteAgentModel("minimax/MiniMax-M2.1");
|
||||
}
|
||||
}
|
||||
|
||||
return { config: nextConfig, agentModelOverride };
|
||||
|
||||
@@ -7,6 +7,8 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
applyAuthProfileConfig,
|
||||
applyMinimaxApiConfig,
|
||||
applyMinimaxApiProviderConfig,
|
||||
writeOAuthCredentials,
|
||||
} from "./onboard-auth.js";
|
||||
|
||||
@@ -105,3 +107,146 @@ describe("applyAuthProfileConfig", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyMinimaxApiConfig", () => {
|
||||
it("adds minimax provider with correct settings", () => {
|
||||
const cfg = applyMinimaxApiConfig({});
|
||||
expect(cfg.models?.providers?.minimax).toMatchObject({
|
||||
baseUrl: "https://api.minimax.io/anthropic",
|
||||
api: "anthropic-messages",
|
||||
});
|
||||
});
|
||||
|
||||
it("sets correct primary model", () => {
|
||||
const cfg = applyMinimaxApiConfig({}, "MiniMax-M2.1-lightning");
|
||||
expect(cfg.agents?.defaults?.model?.primary).toBe(
|
||||
"minimax/MiniMax-M2.1-lightning",
|
||||
);
|
||||
});
|
||||
|
||||
it("sets reasoning flag for MiniMax-M2 model", () => {
|
||||
const cfg = applyMinimaxApiConfig({}, "MiniMax-M2");
|
||||
expect(cfg.models?.providers?.minimax?.models[0]?.reasoning).toBe(true);
|
||||
});
|
||||
|
||||
it("does not set reasoning for non-M2 models", () => {
|
||||
const cfg = applyMinimaxApiConfig({}, "MiniMax-M2.1");
|
||||
expect(cfg.models?.providers?.minimax?.models[0]?.reasoning).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves existing model fallbacks", () => {
|
||||
const cfg = applyMinimaxApiConfig({
|
||||
agents: {
|
||||
defaults: {
|
||||
model: { fallbacks: ["anthropic/claude-opus-4-5"] },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(cfg.agents?.defaults?.model?.fallbacks).toEqual([
|
||||
"anthropic/claude-opus-4-5",
|
||||
]);
|
||||
});
|
||||
|
||||
it("adds model alias", () => {
|
||||
const cfg = applyMinimaxApiConfig({}, "MiniMax-M2.1");
|
||||
expect(cfg.agents?.defaults?.models?.["minimax/MiniMax-M2.1"]?.alias).toBe(
|
||||
"Minimax",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves existing model params when adding alias", () => {
|
||||
const cfg = applyMinimaxApiConfig(
|
||||
{
|
||||
agents: {
|
||||
defaults: {
|
||||
models: {
|
||||
"minimax/MiniMax-M2.1": {
|
||||
alias: "MiniMax",
|
||||
params: { custom: "value" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"MiniMax-M2.1",
|
||||
);
|
||||
expect(
|
||||
cfg.agents?.defaults?.models?.["minimax/MiniMax-M2.1"],
|
||||
).toMatchObject({ alias: "Minimax", params: { custom: "value" } });
|
||||
});
|
||||
|
||||
it("replaces existing minimax provider entirely", () => {
|
||||
const cfg = applyMinimaxApiConfig({
|
||||
models: {
|
||||
providers: {
|
||||
minimax: {
|
||||
baseUrl: "https://old.example.com",
|
||||
apiKey: "old-key",
|
||||
api: "openai-completions",
|
||||
models: [
|
||||
{
|
||||
id: "old-model",
|
||||
name: "Old",
|
||||
reasoning: false,
|
||||
input: ["text"],
|
||||
cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 1000,
|
||||
maxTokens: 100,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(cfg.models?.providers?.minimax?.baseUrl).toBe(
|
||||
"https://api.minimax.io/anthropic",
|
||||
);
|
||||
expect(cfg.models?.providers?.minimax?.api).toBe("anthropic-messages");
|
||||
expect(cfg.models?.providers?.minimax?.models[0]?.id).toBe("MiniMax-M2.1");
|
||||
});
|
||||
|
||||
it("preserves other providers when adding minimax", () => {
|
||||
const cfg = applyMinimaxApiConfig({
|
||||
models: {
|
||||
providers: {
|
||||
anthropic: {
|
||||
baseUrl: "https://api.anthropic.com",
|
||||
apiKey: "anthropic-key",
|
||||
api: "anthropic-messages",
|
||||
models: [
|
||||
{
|
||||
id: "claude-opus-4-5",
|
||||
name: "Claude Opus 4.5",
|
||||
reasoning: false,
|
||||
input: ["text"],
|
||||
cost: { input: 15, output: 75, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 200000,
|
||||
maxTokens: 8192,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(cfg.models?.providers?.anthropic).toBeDefined();
|
||||
expect(cfg.models?.providers?.minimax).toBeDefined();
|
||||
});
|
||||
|
||||
it("preserves existing models mode", () => {
|
||||
const cfg = applyMinimaxApiConfig({
|
||||
models: { mode: "replace", providers: {} },
|
||||
});
|
||||
expect(cfg.models?.mode).toBe("replace");
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyMinimaxApiProviderConfig", () => {
|
||||
it("does not overwrite existing primary model", () => {
|
||||
const cfg = applyMinimaxApiProviderConfig({
|
||||
agents: { defaults: { model: { primary: "anthropic/claude-opus-4-5" } } },
|
||||
});
|
||||
expect(cfg.agents?.defaults?.model?.primary).toBe(
|
||||
"anthropic/claude-opus-4-5",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -263,3 +263,73 @@ export function applyMinimaxHostedConfig(
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// MiniMax Anthropic-compatible API (platform.minimax.io/anthropic)
|
||||
export function applyMinimaxApiProviderConfig(
|
||||
cfg: ClawdbotConfig,
|
||||
modelId: string = "MiniMax-M2.1",
|
||||
): ClawdbotConfig {
|
||||
const providers = { ...cfg.models?.providers };
|
||||
providers.minimax = {
|
||||
baseUrl: "https://api.minimax.io/anthropic",
|
||||
apiKey: "", // Resolved via MINIMAX_API_KEY env var or auth profile
|
||||
api: "anthropic-messages",
|
||||
models: [
|
||||
{
|
||||
id: modelId,
|
||||
name: `MiniMax ${modelId}`,
|
||||
reasoning: modelId === "MiniMax-M2",
|
||||
input: ["text"],
|
||||
// Pricing: MiniMax doesn't publish public rates. Override in models.json for accurate costs.
|
||||
cost: { input: 15, output: 60, cacheRead: 2, cacheWrite: 10 },
|
||||
contextWindow: 200000,
|
||||
maxTokens: 8192,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const models = { ...cfg.agents?.defaults?.models };
|
||||
models[`minimax/${modelId}`] = {
|
||||
...models[`minimax/${modelId}`],
|
||||
alias: "Minimax",
|
||||
};
|
||||
|
||||
return {
|
||||
...cfg,
|
||||
agents: {
|
||||
...cfg.agents,
|
||||
defaults: {
|
||||
...cfg.agents?.defaults,
|
||||
models,
|
||||
},
|
||||
},
|
||||
models: { mode: cfg.models?.mode ?? "merge", providers },
|
||||
};
|
||||
}
|
||||
|
||||
export function applyMinimaxApiConfig(
|
||||
cfg: ClawdbotConfig,
|
||||
modelId: string = "MiniMax-M2.1",
|
||||
): ClawdbotConfig {
|
||||
const next = applyMinimaxApiProviderConfig(cfg, modelId);
|
||||
return {
|
||||
...next,
|
||||
agents: {
|
||||
...next.agents,
|
||||
defaults: {
|
||||
...next.agents?.defaults,
|
||||
model: {
|
||||
...(next.agents?.defaults?.model &&
|
||||
"fallbacks" in (next.agents.defaults.model as Record<string, unknown>)
|
||||
? {
|
||||
fallbacks: (
|
||||
next.agents.defaults.model as { fallbacks?: string[] }
|
||||
).fallbacks,
|
||||
}
|
||||
: undefined),
|
||||
primary: `minimax/${modelId}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import {
|
||||
CLAUDE_CLI_PROFILE_ID,
|
||||
CODEX_CLI_PROFILE_ID,
|
||||
ensureAuthProfileStore,
|
||||
upsertAuthProfile,
|
||||
} from "../agents/auth-profiles.js";
|
||||
import { resolveEnvApiKey } from "../agents/model-auth.js";
|
||||
import { normalizeProviderId } from "../agents/model-selection.js";
|
||||
import { parseDurationMs } from "../cli/parse-duration.js";
|
||||
import {
|
||||
type ClawdbotConfig,
|
||||
CONFIG_PATH_CLAWDBOT,
|
||||
@@ -33,6 +29,7 @@ import { applyGoogleGeminiModelDefault } from "./google-gemini-model-default.js"
|
||||
import { healthCommand } from "./health.js";
|
||||
import {
|
||||
applyAuthProfileConfig,
|
||||
applyMinimaxApiConfig,
|
||||
applyMinimaxConfig,
|
||||
applyMinimaxHostedConfig,
|
||||
setAnthropicApiKey,
|
||||
@@ -177,6 +174,21 @@ export async function runNonInteractiveOnboarding(
|
||||
mode: "api_key",
|
||||
});
|
||||
nextConfig = applyMinimaxHostedConfig(nextConfig);
|
||||
} else if (authChoice === "minimax-api") {
|
||||
const key =
|
||||
opts.minimaxApiKey?.trim() || resolveEnvApiKey("minimax")?.apiKey;
|
||||
if (!key) {
|
||||
runtime.error("Missing --minimax-api-key (or MINIMAX_API_KEY in env).");
|
||||
runtime.exit(1);
|
||||
return;
|
||||
}
|
||||
await setMinimaxApiKey(key);
|
||||
nextConfig = applyAuthProfileConfig(nextConfig, {
|
||||
profileId: "minimax:default",
|
||||
provider: "minimax",
|
||||
mode: "api_key",
|
||||
});
|
||||
nextConfig = applyMinimaxApiConfig(nextConfig);
|
||||
} else if (authChoice === "claude-cli") {
|
||||
const store = ensureAuthProfileStore(undefined, {
|
||||
allowKeychainPrompt: false,
|
||||
@@ -210,82 +222,18 @@ export async function runNonInteractiveOnboarding(
|
||||
nextConfig = applyOpenAICodexModelDefault(nextConfig).next;
|
||||
} else if (authChoice === "minimax") {
|
||||
nextConfig = applyMinimaxConfig(nextConfig);
|
||||
} else if (authChoice === "setup-token" || authChoice === "oauth") {
|
||||
if (!process.stdin.isTTY) {
|
||||
runtime.error("`claude setup-token` requires an interactive TTY.");
|
||||
runtime.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
const res = spawnSync("claude", ["setup-token"], { stdio: "inherit" });
|
||||
if (res.error) throw res.error;
|
||||
if (typeof res.status === "number" && res.status !== 0) {
|
||||
runtime.error(`claude setup-token failed (exit ${res.status})`);
|
||||
runtime.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
const store = ensureAuthProfileStore(undefined, {
|
||||
allowKeychainPrompt: true,
|
||||
});
|
||||
if (!store.profiles[CLAUDE_CLI_PROFILE_ID]) {
|
||||
runtime.error(
|
||||
`No Claude CLI credentials found after setup-token. Expected auth profile ${CLAUDE_CLI_PROFILE_ID}.`,
|
||||
);
|
||||
runtime.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
nextConfig = applyAuthProfileConfig(nextConfig, {
|
||||
profileId: CLAUDE_CLI_PROFILE_ID,
|
||||
provider: "anthropic",
|
||||
mode: "token",
|
||||
});
|
||||
} else if (authChoice === "token") {
|
||||
const providerRaw = opts.tokenProvider?.trim();
|
||||
const tokenRaw = opts.token?.trim();
|
||||
if (!providerRaw) {
|
||||
runtime.error(
|
||||
"Missing --token-provider (required for --auth-choice token).",
|
||||
);
|
||||
runtime.exit(1);
|
||||
return;
|
||||
}
|
||||
if (!tokenRaw) {
|
||||
runtime.error("Missing --token (required for --auth-choice token).");
|
||||
runtime.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
const provider = normalizeProviderId(providerRaw);
|
||||
const profileId = (
|
||||
opts.tokenProfileId?.trim() || `${provider}:manual`
|
||||
).trim();
|
||||
const expires =
|
||||
opts.tokenExpiresIn?.trim() && opts.tokenExpiresIn.trim().length > 0
|
||||
? Date.now() +
|
||||
parseDurationMs(String(opts.tokenExpiresIn).trim(), {
|
||||
defaultUnit: "d",
|
||||
})
|
||||
: undefined;
|
||||
|
||||
upsertAuthProfile({
|
||||
profileId,
|
||||
credential: {
|
||||
type: "token",
|
||||
provider,
|
||||
token: tokenRaw,
|
||||
...(expires ? { expires } : {}),
|
||||
},
|
||||
});
|
||||
nextConfig = applyAuthProfileConfig(nextConfig, {
|
||||
profileId,
|
||||
provider,
|
||||
mode: "token",
|
||||
});
|
||||
} else if (authChoice === "openai-codex" || authChoice === "antigravity") {
|
||||
} else if (
|
||||
authChoice === "token" ||
|
||||
authChoice === "oauth" ||
|
||||
authChoice === "openai-codex" ||
|
||||
authChoice === "antigravity"
|
||||
) {
|
||||
const label =
|
||||
authChoice === "antigravity" ? "Antigravity" : "OpenAI Codex OAuth";
|
||||
authChoice === "antigravity"
|
||||
? "Antigravity"
|
||||
: authChoice === "token"
|
||||
? "Token"
|
||||
: "OAuth";
|
||||
runtime.error(`${label} requires interactive mode.`);
|
||||
runtime.exit(1);
|
||||
return;
|
||||
|
||||
@@ -16,6 +16,7 @@ export type AuthChoice =
|
||||
| "gemini-api-key"
|
||||
| "minimax-cloud"
|
||||
| "minimax"
|
||||
| "minimax-api"
|
||||
| "skip";
|
||||
export type GatewayAuthChoice = "off" | "token" | "password";
|
||||
export type ResetScope = "config" | "config+creds+sessions" | "full";
|
||||
|
||||
@@ -2,119 +2,133 @@ import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import JSZip from "jszip";
|
||||
import sharp from "sharp";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const realOs = await vi.importActual<typeof import("node:os")>("node:os");
|
||||
const HOME = path.join(realOs.tmpdir(), "clawdbot-home-test");
|
||||
|
||||
vi.mock("node:os", () => ({
|
||||
default: { homedir: () => HOME, tmpdir: () => realOs.tmpdir() },
|
||||
homedir: () => HOME,
|
||||
tmpdir: () => realOs.tmpdir(),
|
||||
}));
|
||||
|
||||
const store = await import("./store.js");
|
||||
import { withTempHome } from "../../test/helpers/temp-home.js";
|
||||
|
||||
describe("media store", () => {
|
||||
beforeAll(async () => {
|
||||
await fs.rm(HOME, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await fs.rm(HOME, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("creates and returns media directory", async () => {
|
||||
const dir = await store.ensureMediaDir();
|
||||
expect(dir).toContain("clawdbot-home-test");
|
||||
const stat = await fs.stat(dir);
|
||||
expect(stat.isDirectory()).toBe(true);
|
||||
await withTempHome(async () => {
|
||||
vi.resetModules();
|
||||
const store = await import("./store.js");
|
||||
|
||||
const dir = await store.ensureMediaDir();
|
||||
const normalized = path.normalize(dir);
|
||||
expect(normalized).toContain(`${path.sep}.clawdbot${path.sep}media`);
|
||||
const stat = await fs.stat(dir);
|
||||
expect(stat.isDirectory()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("saves buffers and enforces size limit", async () => {
|
||||
const buf = Buffer.from("hello");
|
||||
const saved = await store.saveMediaBuffer(buf, "text/plain");
|
||||
const savedStat = await fs.stat(saved.path);
|
||||
expect(savedStat.size).toBe(buf.length);
|
||||
expect(saved.contentType).toBe("text/plain");
|
||||
expect(saved.path.endsWith(".txt")).toBe(true);
|
||||
await withTempHome(async () => {
|
||||
vi.resetModules();
|
||||
const store = await import("./store.js");
|
||||
|
||||
const jpeg = await sharp({
|
||||
create: { width: 2, height: 2, channels: 3, background: "#123456" },
|
||||
})
|
||||
.jpeg({ quality: 80 })
|
||||
.toBuffer();
|
||||
const savedJpeg = await store.saveMediaBuffer(jpeg, "image/jpeg");
|
||||
expect(savedJpeg.contentType).toBe("image/jpeg");
|
||||
expect(savedJpeg.path.endsWith(".jpg")).toBe(true);
|
||||
const buf = Buffer.from("hello");
|
||||
const saved = await store.saveMediaBuffer(buf, "text/plain");
|
||||
const savedStat = await fs.stat(saved.path);
|
||||
expect(savedStat.size).toBe(buf.length);
|
||||
expect(saved.contentType).toBe("text/plain");
|
||||
expect(saved.path.endsWith(".txt")).toBe(true);
|
||||
|
||||
const huge = Buffer.alloc(5 * 1024 * 1024 + 1);
|
||||
await expect(store.saveMediaBuffer(huge)).rejects.toThrow(
|
||||
"Media exceeds 5MB limit",
|
||||
);
|
||||
const jpeg = await sharp({
|
||||
create: { width: 2, height: 2, channels: 3, background: "#123456" },
|
||||
})
|
||||
.jpeg({ quality: 80 })
|
||||
.toBuffer();
|
||||
const savedJpeg = await store.saveMediaBuffer(jpeg, "image/jpeg");
|
||||
expect(savedJpeg.contentType).toBe("image/jpeg");
|
||||
expect(savedJpeg.path.endsWith(".jpg")).toBe(true);
|
||||
|
||||
const huge = Buffer.alloc(5 * 1024 * 1024 + 1);
|
||||
await expect(store.saveMediaBuffer(huge)).rejects.toThrow(
|
||||
"Media exceeds 5MB limit",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("copies local files and cleans old media", async () => {
|
||||
const srcFile = path.join(HOME, "tmp-src.txt");
|
||||
await fs.mkdir(HOME, { recursive: true });
|
||||
await fs.writeFile(srcFile, "local file");
|
||||
const saved = await store.saveMediaSource(srcFile);
|
||||
expect(saved.size).toBe(10);
|
||||
const savedStat = await fs.stat(saved.path);
|
||||
expect(savedStat.isFile()).toBe(true);
|
||||
expect(path.extname(saved.path)).toBe(".txt");
|
||||
await withTempHome(async (home) => {
|
||||
vi.resetModules();
|
||||
const store = await import("./store.js");
|
||||
|
||||
// make the file look old and ensure cleanOldMedia removes it
|
||||
const past = Date.now() - 10_000;
|
||||
await fs.utimes(saved.path, past / 1000, past / 1000);
|
||||
await store.cleanOldMedia(1);
|
||||
await expect(fs.stat(saved.path)).rejects.toThrow();
|
||||
const srcFile = path.join(home, "tmp-src.txt");
|
||||
await fs.mkdir(home, { recursive: true });
|
||||
await fs.writeFile(srcFile, "local file");
|
||||
const saved = await store.saveMediaSource(srcFile);
|
||||
expect(saved.size).toBe(10);
|
||||
const savedStat = await fs.stat(saved.path);
|
||||
expect(savedStat.isFile()).toBe(true);
|
||||
expect(path.extname(saved.path)).toBe(".txt");
|
||||
|
||||
// make the file look old and ensure cleanOldMedia removes it
|
||||
const past = Date.now() - 10_000;
|
||||
await fs.utimes(saved.path, past / 1000, past / 1000);
|
||||
await store.cleanOldMedia(1);
|
||||
await expect(fs.stat(saved.path)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
it("sets correct mime for xlsx by extension", async () => {
|
||||
const xlsxPath = path.join(HOME, "sheet.xlsx");
|
||||
await fs.mkdir(HOME, { recursive: true });
|
||||
await fs.writeFile(xlsxPath, "not really an xlsx");
|
||||
await withTempHome(async (home) => {
|
||||
vi.resetModules();
|
||||
const store = await import("./store.js");
|
||||
|
||||
const saved = await store.saveMediaSource(xlsxPath);
|
||||
expect(saved.contentType).toBe(
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
);
|
||||
expect(path.extname(saved.path)).toBe(".xlsx");
|
||||
const xlsxPath = path.join(home, "sheet.xlsx");
|
||||
await fs.mkdir(home, { recursive: true });
|
||||
await fs.writeFile(xlsxPath, "not really an xlsx");
|
||||
|
||||
const saved = await store.saveMediaSource(xlsxPath);
|
||||
expect(saved.contentType).toBe(
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
);
|
||||
expect(path.extname(saved.path)).toBe(".xlsx");
|
||||
});
|
||||
});
|
||||
|
||||
it("renames media based on detected mime even when extension is wrong", async () => {
|
||||
const pngBytes = await sharp({
|
||||
create: { width: 2, height: 2, channels: 3, background: "#00ff00" },
|
||||
})
|
||||
.png()
|
||||
.toBuffer();
|
||||
const bogusExt = path.join(HOME, "image-wrong.bin");
|
||||
await fs.writeFile(bogusExt, pngBytes);
|
||||
await withTempHome(async (home) => {
|
||||
vi.resetModules();
|
||||
const store = await import("./store.js");
|
||||
|
||||
const saved = await store.saveMediaSource(bogusExt);
|
||||
expect(saved.contentType).toBe("image/png");
|
||||
expect(path.extname(saved.path)).toBe(".png");
|
||||
const pngBytes = await sharp({
|
||||
create: { width: 2, height: 2, channels: 3, background: "#00ff00" },
|
||||
})
|
||||
.png()
|
||||
.toBuffer();
|
||||
const bogusExt = path.join(home, "image-wrong.bin");
|
||||
await fs.writeFile(bogusExt, pngBytes);
|
||||
|
||||
const buf = await fs.readFile(saved.path);
|
||||
expect(buf.equals(pngBytes)).toBe(true);
|
||||
const saved = await store.saveMediaSource(bogusExt);
|
||||
expect(saved.contentType).toBe("image/png");
|
||||
expect(path.extname(saved.path)).toBe(".png");
|
||||
|
||||
const buf = await fs.readFile(saved.path);
|
||||
expect(buf.equals(pngBytes)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("sniffs xlsx mime for zip buffers and renames extension", async () => {
|
||||
const zip = new JSZip();
|
||||
zip.file(
|
||||
"[Content_Types].xml",
|
||||
'<Types><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/></Types>',
|
||||
);
|
||||
zip.file("xl/workbook.xml", "<workbook/>");
|
||||
const fakeXlsx = await zip.generateAsync({ type: "nodebuffer" });
|
||||
const bogusExt = path.join(HOME, "sheet.bin");
|
||||
await fs.writeFile(bogusExt, fakeXlsx);
|
||||
await withTempHome(async (home) => {
|
||||
vi.resetModules();
|
||||
const store = await import("./store.js");
|
||||
|
||||
const saved = await store.saveMediaSource(bogusExt);
|
||||
expect(saved.contentType).toBe(
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
);
|
||||
expect(path.extname(saved.path)).toBe(".xlsx");
|
||||
const zip = new JSZip();
|
||||
zip.file(
|
||||
"[Content_Types].xml",
|
||||
'<Types><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/></Types>',
|
||||
);
|
||||
zip.file("xl/workbook.xml", "<workbook/>");
|
||||
const fakeXlsx = await zip.generateAsync({ type: "nodebuffer" });
|
||||
const bogusExt = path.join(home, "sheet.bin");
|
||||
await fs.writeFile(bogusExt, fakeXlsx);
|
||||
|
||||
const saved = await store.saveMediaSource(bogusExt);
|
||||
expect(saved.contentType).toBe(
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
);
|
||||
expect(path.extname(saved.path)).toBe(".xlsx");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import fs from "node:fs";
|
||||
import fsPromises from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { withTempHome } from "../../test/helpers/temp-home.js";
|
||||
|
||||
const runtime = {
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
@@ -12,74 +12,74 @@ const runtime = {
|
||||
};
|
||||
|
||||
describe("web logout", () => {
|
||||
const origHomedir = os.homedir;
|
||||
let tmpDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "clawdbot-logout-"));
|
||||
vi.spyOn(os, "homedir").mockReturnValue(tmpDir);
|
||||
vi.resetModules();
|
||||
vi.doMock("../utils.js", async () => {
|
||||
const actual =
|
||||
await vi.importActual<typeof import("../utils.js")>("../utils.js");
|
||||
return {
|
||||
...actual,
|
||||
CONFIG_DIR: path.join(tmpDir, ".clawdbot"),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.doUnmock("../utils.js");
|
||||
await fsPromises
|
||||
.rm(tmpDir, { recursive: true, force: true })
|
||||
.catch(() => {});
|
||||
// restore for safety
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
(os.homedir as unknown as typeof origHomedir) = origHomedir;
|
||||
});
|
||||
|
||||
it(
|
||||
"deletes cached credentials when present",
|
||||
{ timeout: 15_000 },
|
||||
async () => {
|
||||
const { logoutWeb, WA_WEB_AUTH_DIR } = await import("./session.js");
|
||||
await withTempHome(async (home) => {
|
||||
vi.resetModules();
|
||||
const { logoutWeb, WA_WEB_AUTH_DIR } = await import("./session.js");
|
||||
|
||||
expect(WA_WEB_AUTH_DIR.startsWith(tmpDir)).toBe(true);
|
||||
fs.mkdirSync(WA_WEB_AUTH_DIR, { recursive: true });
|
||||
fs.writeFileSync(path.join(WA_WEB_AUTH_DIR, "creds.json"), "{}");
|
||||
const result = await logoutWeb({ runtime: runtime as never });
|
||||
const rel = path.relative(
|
||||
path.resolve(home),
|
||||
path.resolve(WA_WEB_AUTH_DIR),
|
||||
);
|
||||
expect(rel && !rel.startsWith("..") && !path.isAbsolute(rel)).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(fs.existsSync(WA_WEB_AUTH_DIR)).toBe(false);
|
||||
fs.mkdirSync(WA_WEB_AUTH_DIR, { recursive: true });
|
||||
fs.writeFileSync(path.join(WA_WEB_AUTH_DIR, "creds.json"), "{}");
|
||||
const result = await logoutWeb({ runtime: runtime as never });
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(fs.existsSync(WA_WEB_AUTH_DIR)).toBe(false);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("no-ops when nothing to delete", { timeout: 15_000 }, async () => {
|
||||
const { logoutWeb } = await import("./session.js");
|
||||
const result = await logoutWeb({ runtime: runtime as never });
|
||||
expect(result).toBe(false);
|
||||
expect(runtime.log).toHaveBeenCalled();
|
||||
await withTempHome(async () => {
|
||||
vi.resetModules();
|
||||
const { logoutWeb } = await import("./session.js");
|
||||
const result = await logoutWeb({ runtime: runtime as never });
|
||||
expect(result).toBe(false);
|
||||
expect(runtime.log).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps shared oauth.json when using legacy auth dir", async () => {
|
||||
const { logoutWeb } = await import("./session.js");
|
||||
const credsDir = path.join(tmpDir, ".clawdbot", "credentials");
|
||||
fs.mkdirSync(credsDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(credsDir, "creds.json"), "{}");
|
||||
fs.writeFileSync(path.join(credsDir, "oauth.json"), '{"token":true}');
|
||||
fs.writeFileSync(path.join(credsDir, "session-abc.json"), "{}");
|
||||
await withTempHome(async () => {
|
||||
vi.resetModules();
|
||||
const { logoutWeb } = await import("./session.js");
|
||||
|
||||
const result = await logoutWeb({
|
||||
authDir: credsDir,
|
||||
isLegacyAuthDir: true,
|
||||
runtime: runtime as never,
|
||||
const { resolveOAuthDir } = await import("../config/paths.js");
|
||||
const credsDir = resolveOAuthDir();
|
||||
|
||||
fs.mkdirSync(credsDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(credsDir, "creds.json"), "{}");
|
||||
fs.writeFileSync(path.join(credsDir, "oauth.json"), '{"token":true}');
|
||||
fs.writeFileSync(path.join(credsDir, "session-abc.json"), "{}");
|
||||
|
||||
const result = await logoutWeb({
|
||||
authDir: credsDir,
|
||||
isLegacyAuthDir: true,
|
||||
runtime: runtime as never,
|
||||
});
|
||||
expect(result).toBe(true);
|
||||
expect(fs.existsSync(path.join(credsDir, "oauth.json"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(credsDir, "creds.json"))).toBe(false);
|
||||
expect(fs.existsSync(path.join(credsDir, "session-abc.json"))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
expect(result).toBe(true);
|
||||
expect(fs.existsSync(path.join(credsDir, "oauth.json"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(credsDir, "creds.json"))).toBe(false);
|
||||
expect(fs.existsSync(path.join(credsDir, "session-abc.json"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user