mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-27 20:00:51 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e1bdd85d8 | ||
|
|
450d1df2e7 | ||
|
|
3ed22954db |
No files matched your search
@@ -541,3 +541,98 @@ test("late pause acknowledgement cannot restart a cancelling stream before settl
|
||||
await pause;
|
||||
assert.equal(resumes, 0);
|
||||
});
|
||||
|
||||
for (const rejected of [false, true]) {
|
||||
test(`folder pause retains successful children without claiming failed children paused: rejected=${rejected}`, async (t) => {
|
||||
t.after(resetTransferPauseLatchesForTests);
|
||||
let fail = true;
|
||||
let resumes = 0;
|
||||
const id = `partial-folder-${rejected}`;
|
||||
const { host, getTasks } = createHost([
|
||||
{ ...makeTask(id), isDirectory: true },
|
||||
{ ...makeTask(`${id}-ok`), parentTaskId: id },
|
||||
{ ...makeTask(`${id}-bad`), parentTaskId: id },
|
||||
], () => ({
|
||||
pauseTransfer: async (childId) => {
|
||||
if (fail && childId.endsWith('-bad')) {
|
||||
if (rejected) throw new Error('pause IPC unavailable');
|
||||
return { success: false, reason: 'This transfer cannot be paused safely' };
|
||||
}
|
||||
return { success: true, checkpointBytes: 10 };
|
||||
},
|
||||
resumeTransfer: async () => { resumes++; return { success: true }; },
|
||||
}));
|
||||
await softPauseTransfer(host, id);
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
assert.equal(getTasks()[0].status, 'pausing');
|
||||
assert.match(getTasks()[0].pauseUnavailableReason || '', /pause/i);
|
||||
assert.equal(getTasks()[1].status, 'paused');
|
||||
assert.equal(getTasks()[2].status, 'transferring');
|
||||
assert.equal(isTransferPauseLatched(id), true);
|
||||
assert.equal(resumes, 0, 'failed pause must not resume successful siblings');
|
||||
fail = false;
|
||||
await softPauseTransfer(host, id);
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
assert.ok(getTasks().every(row => row.status === 'paused'));
|
||||
assert.equal(getTasks()[0].pauseUnavailableReason, undefined);
|
||||
});
|
||||
}
|
||||
|
||||
test('folder pause does not claim success while acknowledgements are pending or retry budget expires', async (t) => {
|
||||
t.after(resetTransferPauseLatchesForTests);
|
||||
const id = 'slow-start-folder';
|
||||
let calls = 0;
|
||||
const { host, getTasks } = createHost([
|
||||
{ ...makeTask(id), isDirectory: true },
|
||||
{ ...makeTask(`${id}-child`), parentTaskId: id },
|
||||
], () => ({ pauseTransfer: async () => {
|
||||
calls++;
|
||||
return { success: false, reason: 'This transfer cannot be paused yet' };
|
||||
} }));
|
||||
assert.equal(await softPauseTransfer(host, id), 'pausing');
|
||||
assert.equal(getTasks()[0].status, 'pausing');
|
||||
// Wait for the bounded startup retry budget (four 40ms delays).
|
||||
await new Promise(resolve => setTimeout(resolve, 220));
|
||||
assert.equal(calls, 5);
|
||||
assert.equal(getTasks()[0].status, 'pausing');
|
||||
assert.match(getTasks()[0].pauseUnavailableReason || '', /cannot be paused yet/);
|
||||
assert.equal(getTasks()[1].status, 'transferring');
|
||||
});
|
||||
|
||||
test('explicit resume after partial folder pause releases successful siblings and walk latch', async (t) => {
|
||||
t.after(resetTransferPauseLatchesForTests);
|
||||
const id = 'resume-partial-folder';
|
||||
const resumed: string[] = [];
|
||||
const { host, getTasks } = createHost([
|
||||
{ ...makeTask(id), isDirectory: true },
|
||||
{ ...makeTask(`${id}-ok`), parentTaskId: id },
|
||||
{ ...makeTask(`${id}-bad`), parentTaskId: id },
|
||||
], () => ({
|
||||
pauseTransfer: async childId => childId.endsWith('-ok')
|
||||
? { success: true } : { success: false, reason: 'Pause rejected' },
|
||||
resumeTransfer: async childId => { resumed.push(childId); return { success: true }; },
|
||||
}));
|
||||
await softPauseTransfer(host, id);
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
assert.equal((await softResumeTransfer(host, id)).handled, true);
|
||||
assert.equal(isTransferPauseLatched(id), false);
|
||||
assert.ok(getTasks().every(row => row.status === 'transferring'));
|
||||
assert.deepEqual(resumed.sort(), [`${id}-bad`, `${id}-ok`]);
|
||||
});
|
||||
|
||||
test('child completion during a rejected folder pause does not leave a false failure', async (t) => {
|
||||
t.after(resetTransferPauseLatchesForTests);
|
||||
const id = 'completed-during-folder-pause';
|
||||
let finish!: (result: { success: boolean; reason: string }) => void;
|
||||
const { host, getTasks } = createHost([
|
||||
{ ...makeTask(id), isDirectory: true },
|
||||
{ ...makeTask(`${id}-child`), parentTaskId: id },
|
||||
], () => ({ pauseTransfer: () => new Promise(resolve => { finish = resolve; }) }));
|
||||
await softPauseTransfer(host, id);
|
||||
host.setTasks(getTasks().map(row => row.parentTaskId ? { ...row, status: 'completed' } : row));
|
||||
finish({ success: false, reason: 'Pause rejected' });
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
assert.equal(getTasks()[0].status, 'paused');
|
||||
assert.equal(getTasks()[0].pauseUnavailableReason, undefined);
|
||||
assert.equal(getTasks()[1].status, 'completed');
|
||||
});
|
||||
@@ -184,7 +184,7 @@ export async function softPauseTransfer(
|
||||
try { globalSftpTransferScheduler.pause(id); } catch { /* best-effort */ }
|
||||
}
|
||||
|
||||
const immediateStatus = task.isDirectory ? "paused" as const : "pausing" as const;
|
||||
const immediateStatus = "pausing" as const;
|
||||
// Freeze via latch/status; leave lifecycleEpoch alone until bridge responds.
|
||||
host.setTasks(paintTreeStatus(
|
||||
host.getTasks(),
|
||||
@@ -271,7 +271,11 @@ export async function softPauseTransfer(
|
||||
if (!pauseStillCurrent()) {
|
||||
return { id, result: { success: false, reason: "Pause superseded by resume" } };
|
||||
}
|
||||
const result = await pauseOne(id);
|
||||
// A rejected IPC is a failed acknowledgement, not proof of pause.
|
||||
const result: Awaited<ReturnType<NonNullable<TransferControlBridge["pauseTransfer"]>>> = await pauseOne(id).catch((error: unknown) => ({
|
||||
success: false,
|
||||
reason: error instanceof Error ? error.message : "Could not pause transfer",
|
||||
}));
|
||||
if (wasSuperseded(result)) return { id, result };
|
||||
const live = host.getTasks().find((candidate) => candidate.id === taskId);
|
||||
const userResumed = !pauseStillCurrent()
|
||||
@@ -293,16 +297,26 @@ export async function softPauseTransfer(
|
||||
if (after.status !== "paused" && after.status !== "pausing") return;
|
||||
const byId = new Map(pauseResults.map((row) => [row.id, row.result]));
|
||||
const bridgeEpoch = maxBridgeLifecycleEpoch(pauseResults.map((row) => row.result));
|
||||
// Final directory paint: parent + unfinished children all go paused (do not
|
||||
// leave children stuck on transferring under a paused parent).
|
||||
const liveTasks = host.getTasks();
|
||||
const failed = pauseResults.filter(({ id, result }) => {
|
||||
const live = liveTasks.find((candidate) => candidate.id === id);
|
||||
return live && !["completed", "cancelled", "failed"].includes(live.status)
|
||||
&& !result.success && !isBenignPauseMiss(result.reason);
|
||||
});
|
||||
// Keep acknowledged children paused and retain the walk latch. Never
|
||||
// auto-resume siblings to roll back a partial pause. Failed children may
|
||||
// still be streaming; expose that truth and allow an explicit retry.
|
||||
const pauseFailure = failed.length > 0
|
||||
? (failed[0].result.reason || "Could not pause all folder transfers")
|
||||
: undefined;
|
||||
host.setTasks(host.getTasks().map((candidate) => {
|
||||
if (candidate.id === taskId) {
|
||||
return {
|
||||
...candidate,
|
||||
status: "paused" as const,
|
||||
status: pauseFailure ? "pausing" as const : "paused" as const,
|
||||
speed: 0,
|
||||
checkpointBytes: candidate.transferredBytes,
|
||||
pauseUnavailableReason: undefined,
|
||||
pauseUnavailableReason: pauseFailure,
|
||||
phase: undefined,
|
||||
// Bridge epoch only — control-plane pauseEpoch must not poison ingest.
|
||||
...(bridgeEpoch !== undefined ? { lifecycleEpoch: bridgeEpoch } : null),
|
||||
@@ -311,24 +325,25 @@ export async function softPauseTransfer(
|
||||
if (candidate.parentTaskId !== taskId && !backendIds.includes(candidate.id)) return candidate;
|
||||
if (["completed", "cancelled", "failed"].includes(candidate.status)) return candidate;
|
||||
const result = byId.get(candidate.id);
|
||||
const childFailed = result && !result.success && !isBenignPauseMiss(result.reason);
|
||||
const childEpoch = Number.isFinite(result?.lifecycleEpoch)
|
||||
? (result!.lifecycleEpoch as number)
|
||||
: bridgeEpoch;
|
||||
: childFailed ? undefined : bridgeEpoch;
|
||||
return {
|
||||
...candidate,
|
||||
status: "paused" as const,
|
||||
status: childFailed ? "transferring" as const : "paused" as const,
|
||||
speed: 0,
|
||||
checkpointBytes: result?.checkpointBytes ?? candidate.checkpointBytes ?? candidate.transferredBytes,
|
||||
resumeStage: result?.resumeStage ?? candidate.resumeStage,
|
||||
downloadCheckpointBytes: result?.downloadCheckpointBytes ?? candidate.downloadCheckpointBytes,
|
||||
uploadCheckpointBytes: result?.uploadCheckpointBytes ?? candidate.uploadCheckpointBytes,
|
||||
sourceFingerprint: result?.sourceFingerprint ?? candidate.sourceFingerprint,
|
||||
pauseUnavailableReason: undefined,
|
||||
pauseUnavailableReason: childFailed ? (result.reason || "Could not pause transfer") : undefined,
|
||||
...(childEpoch !== undefined ? { lifecycleEpoch: childEpoch } : null),
|
||||
};
|
||||
}));
|
||||
})().catch(() => { /* best-effort */ });
|
||||
return "paused";
|
||||
return "pausing";
|
||||
}
|
||||
|
||||
// Single-file: await soft-drain with supersede guards.
|
||||
|
||||
@@ -122,8 +122,11 @@ test("runtime soft-resumes live walk after owner teardown simulation (no dedicat
|
||||
resetGlobals();
|
||||
const resumeCalls: string[] = [];
|
||||
let dedicatedHandlerCalls = 0;
|
||||
let acknowledgePause!: () => void;
|
||||
installBridge(t, {
|
||||
pauseTransfer: async () => ({ success: true, checkpointBytes: 5 }),
|
||||
pauseTransfer: () => new Promise((resolve) => {
|
||||
acknowledgePause = () => resolve({ success: true, checkpointBytes: 5 });
|
||||
}),
|
||||
resumeTransfer: async (id) => {
|
||||
resumeCalls.push(id);
|
||||
return { success: true };
|
||||
@@ -151,6 +154,9 @@ test("runtime soft-resumes live walk after owner teardown simulation (no dedicat
|
||||
]);
|
||||
|
||||
await runtime.pause("folder");
|
||||
assert.equal(runtime.getTask("folder")?.status, "pausing");
|
||||
acknowledgePause();
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
assert.equal(runtime.getTask("folder")?.status, "paused");
|
||||
assert.equal(isTransferPauseLatched("folder"), true);
|
||||
assert.equal(isTransferWalkInFlight("folder"), true);
|
||||
|
||||
@@ -1505,6 +1505,7 @@ test("pause after terminal close works without any React owner", async () => {
|
||||
|
||||
await store.pause("stale-dir");
|
||||
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "stale-dir")?.status, "paused");
|
||||
assert.equal(isTransferPauseLatched("stale-dir"), true);
|
||||
assert.ok(pauseCalls.includes("stale-child"));
|
||||
@@ -2413,6 +2414,7 @@ test("dedicated directory resume after soft-pause winds down then startFresh (no
|
||||
|
||||
// Soft-pause paints paused under dedicated-resume.
|
||||
await store.pause("dir");
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "dir")?.status, "paused");
|
||||
|
||||
// Resume must cancel soft-paused children, clear sticky latches, await wind-down, then startFresh.
|
||||
@@ -2621,7 +2623,7 @@ test("async folder soft-drain does not re-pause after immediate resume", async (
|
||||
|
||||
// Pause returns immediately (async soft-drain).
|
||||
await store.pause("dir-race");
|
||||
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "dir-race")?.status, "paused");
|
||||
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "dir-race")?.status, "pausing");
|
||||
|
||||
// User hits resume before soft-drain finishes — full store resume (bumps epoch
|
||||
// + releases latch tree), which is what the UI does.
|
||||
@@ -2690,21 +2692,33 @@ test("orphan directory pause stays latched even when some children hard-miss pau
|
||||
|
||||
await store.pause("dir");
|
||||
|
||||
// Folder pause is async: UI is paused immediately; soft-drain may still be running.
|
||||
// Folder pause stays pending until the child acknowledgements settle.
|
||||
const dir = store.getSnapshot().tasks.find((task) => task.id === "dir");
|
||||
assert.equal(dir?.status, "paused", "folder parent must paint paused without waiting on children");
|
||||
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "c-ok")?.status, "paused");
|
||||
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "c-fail")?.status, "paused");
|
||||
// Soft-drain is fire-and-forget — give it a tick to hit the bridge.
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
assert.equal(dir?.status, "pausing");
|
||||
const ownerSnapshotDuringDrain = store.getSnapshot().tasks.map((row) => ({ ...row }));
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
assert.equal(store.getTask("c-ok")?.status, "paused");
|
||||
assert.equal(store.getTask("c-fail")?.status, "transferring");
|
||||
assert.deepEqual(pauseCalls.sort(), ["c-fail", "c-ok"]);
|
||||
// Latch-first: do not bridge-resume partial successes (that re-opened the queue).
|
||||
assert.deepEqual(resumeCalls, []);
|
||||
assert.equal(
|
||||
store.getSnapshot().tasks.find((task) => task.id === "dir")?.status,
|
||||
"paused",
|
||||
"hard-miss soft-drain must not demote folder out of paused",
|
||||
"pausing",
|
||||
"hard miss keeps the folder latched without claiming a successful pause",
|
||||
);
|
||||
assert.equal(store.getTask("dir")?.pauseUnavailableReason, "This transfer cannot be paused safely");
|
||||
store.publishOwner("dedicated-resume", ownerSnapshotDuringDrain);
|
||||
assert.equal(store.getTask("dir")?.status, "pausing");
|
||||
assert.equal(store.getTask("dir")?.pauseUnavailableReason, "This transfer cannot be paused safely");
|
||||
assert.equal(store.getTask("c-ok")?.status, "paused");
|
||||
assert.equal(store.getTask("c-fail")?.status, "transferring");
|
||||
store.ingestBackgroundEvent({ type: "progress", transferId: "c-fail", transferred: 25, speed: 10 });
|
||||
assert.equal(store.getTask("c-fail")?.status, "transferring");
|
||||
assert.equal(store.getTask("c-fail")?.transferredBytes, 25);
|
||||
store.patchTask("c-fail", { transferredBytes: 50, speed: 10 });
|
||||
assert.equal(store.getTask("c-fail")?.status, "transferring");
|
||||
assert.equal(store.getTask("c-fail")?.transferredBytes, 50);
|
||||
});
|
||||
|
||||
test("dedicated resume source-changed marks attention and can reset checkpoint", async () => {
|
||||
|
||||
@@ -353,7 +353,22 @@ export function mergeOwnerPublishedTask(
|
||||
// Only a strictly newer lifecycle epoch may re-open transferring (resume).
|
||||
const incomingPaused = incoming.status === "paused" || incoming.status === "pausing";
|
||||
const existingPaused = existing.status === "paused" || existing.status === "pausing";
|
||||
if (incomingPaused && incomingLifecycleEpoch >= existingLifecycleEpoch) {
|
||||
// The panel can publish a snapshot from before the child acknowledgements
|
||||
// arrived. Only a newer control decision may clear the folder's failure.
|
||||
const rejectedFolderPause = existing.isDirectory && !existing.parentTaskId
|
||||
&& existing.status === "pausing" && !!existing.pauseUnavailableReason
|
||||
&& incomingLifecycleEpoch <= existingLifecycleEpoch
|
||||
&& isTransferPauseLatched(existing.id);
|
||||
const rejectedChildPause = parentStatus === "pausing"
|
||||
&& !!existing.parentTaskId && existing.status === "transferring" && !!existing.pauseUnavailableReason;
|
||||
if (rejectedFolderPause) {
|
||||
merged.status = "pausing";
|
||||
merged.speed = 0;
|
||||
merged.pauseUnavailableReason = existing.pauseUnavailableReason;
|
||||
} else if (rejectedChildPause && incomingLifecycleEpoch <= existingLifecycleEpoch) {
|
||||
merged.status = "transferring";
|
||||
merged.pauseUnavailableReason = existing.pauseUnavailableReason;
|
||||
} else if (incomingPaused && incomingLifecycleEpoch >= existingLifecycleEpoch) {
|
||||
merged.status = incoming.status;
|
||||
merged.speed = 0;
|
||||
// Pin the visible bar while paused/latched. Soft-drain must not keep
|
||||
@@ -392,6 +407,7 @@ export function mergeOwnerPublishedTask(
|
||||
const parentHoldsPause = parentStatus === "paused" || parentStatus === "pausing";
|
||||
if (
|
||||
parentHoldsPause
|
||||
&& !rejectedChildPause
|
||||
&& !["completed", "cancelled", "failed"].includes(merged.status)
|
||||
&& (merged.status === "transferring" || merged.status === "pending" || merged.status === "queued")
|
||||
) {
|
||||
@@ -1722,17 +1738,15 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
// Soft-drain / walk progress must not move the visible bar after Pause.
|
||||
// Latch or paused/pausing freezes transferredBytes/speed unless this patch
|
||||
// is an explicit resume (transferring + epoch, or dedicated-resume).
|
||||
const pauseHeld = isTransferOrRootPauseLatched(task.parentTaskId ?? task.id, task.id)
|
||||
const parent = task.parentTaskId ? tasks.find((candidate) => candidate.id === task.parentTaskId) : undefined;
|
||||
const rejectedChildPause = parent?.status === "pausing" && !!parent.pauseUnavailableReason
|
||||
&& task.status === "transferring" && !!task.pauseUnavailableReason;
|
||||
const pauseHeld = !rejectedChildPause && (isTransferOrRootPauseLatched(task.parentTaskId ?? task.id, task.id)
|
||||
|| isTransferPauseLatched(task.id)
|
||||
|| task.status === "paused"
|
||||
|| task.status === "pausing"
|
||||
|| (!!task.parentTaskId && (
|
||||
isTransferPauseLatched(task.parentTaskId)
|
||||
|| (() => {
|
||||
const parent = tasks.find((candidate) => candidate.id === task.parentTaskId);
|
||||
return parent?.status === "paused" || parent?.status === "pausing";
|
||||
})()
|
||||
));
|
||||
|| parent?.status === "paused"
|
||||
|| parent?.status === "pausing");
|
||||
if (pauseHeld && !explicitResume) {
|
||||
// Keep lifecycle at paused/pausing; allow checkpoint metadata only.
|
||||
if (task.status === "pausing" || task.status === "paused") {
|
||||
@@ -2451,10 +2465,12 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
task.parentTaskId ?? task.id,
|
||||
task.id,
|
||||
) || isTransferPauseLatched(task.id);
|
||||
const uiPauseLatched = task.status === "paused"
|
||||
const rejectedChildPause = parentRow?.status === "pausing" && !!parentRow.pauseUnavailableReason
|
||||
&& task.status === "transferring" && !!task.pauseUnavailableReason;
|
||||
const uiPauseLatched = !rejectedChildPause && (task.status === "paused"
|
||||
|| task.status === "pausing"
|
||||
|| parentHoldsPause
|
||||
|| selfLatched;
|
||||
|| selfLatched);
|
||||
const explicitResume = lifecycleStatus === "transferring"
|
||||
&& event.lifecycleEpoch !== undefined
|
||||
&& incomingEpoch > currentEpoch;
|
||||
|
||||
@@ -436,7 +436,7 @@ function TransferRow({
|
||||
task: TransferTask;
|
||||
children: TransferTask[];
|
||||
} | null>(null);
|
||||
if (task.status === "pausing") {
|
||||
if (task.status === "pausing" && !task.pauseUnavailableReason) {
|
||||
if (!pausingSnapshotRef.current) {
|
||||
pausingSnapshotRef.current = {
|
||||
task: { ...task },
|
||||
@@ -464,20 +464,23 @@ function TransferRow({
|
||||
&& !task.error;
|
||||
const sharedResuming = useSftpTransferResuming(task.id);
|
||||
const isResuming = sharedResuming || storeResuming;
|
||||
const canPause = task.resumable !== false && task.status === "transferring" && canControl && !isResuming;
|
||||
const pauseFailed = task.status === "pausing" && !!task.pauseUnavailableReason;
|
||||
const canPause = task.resumable !== false && (task.status === "transferring" || pauseFailed) && canControl && !isResuming;
|
||||
// Orphaned tasks after app restart (interrupted / attention / paused without a
|
||||
// live panel owner) must still expose resume/cancel from the global center.
|
||||
// Conflict rows must use resolveConflict — Resume would overwrite blindly.
|
||||
// Non-resumable attention rows (e.g. duplicate-destination refusals) are
|
||||
// terminal: resuming them would start a second writer on the same path.
|
||||
// Do not show Resume during soft-drain "pausing" — play + spinner together
|
||||
// makes the row twitch as buttons appear/disappear mid-drain.
|
||||
// makes the row twitch as buttons appear/disappear mid-drain. A settled
|
||||
// partial failure is different: offer Retry Pause and explicit Resume.
|
||||
const canResume = !isResuming && !task.conflict && (
|
||||
["paused", "interrupted"].includes(task.status)
|
||||
|| (pauseFailed && task.resumable !== false)
|
||||
|| (task.status === "attention" && task.resumable !== false)
|
||||
|| (task.status === "failed" && task.resumable !== false && (task.checkpointBytes ?? 0) > 0)
|
||||
) && canControl;
|
||||
const isPausing = task.status === "pausing";
|
||||
const isPausing = task.status === "pausing" && !pauseFailed;
|
||||
const canCancel = ["pending", "queued", "transferring", "pausing", "paused", "interrupted", "attention"].includes(task.status) && canControl;
|
||||
const canRetry = task.status === "failed" && task.retryable !== false && canControl;
|
||||
const isTerminal = ["completed", "failed", "cancelled"].includes(task.status);
|
||||
@@ -577,7 +580,7 @@ function TransferRow({
|
||||
<Pause size={13} />
|
||||
</TransferAction>
|
||||
)}
|
||||
{task.status === "pausing" && (
|
||||
{task.status === "pausing" && !pauseFailed && (
|
||||
<div className="flex h-8 w-8 items-center justify-center" role="status" aria-label={t("sftp.transferCenter.status.pausing")}>
|
||||
<Loader2 size={13} className="animate-spin text-amber-500" />
|
||||
</div>
|
||||
|
||||
@@ -206,6 +206,23 @@ test("surfaces pause unavailable reason on a transferring row", () => {
|
||||
assert.match(markup, /This transfer cannot be paused yet/);
|
||||
});
|
||||
|
||||
test("shows a settled folder pause failure with retry and resume instead of a spinner", () => {
|
||||
const markup = renderTransferItem({
|
||||
...baseTask,
|
||||
isDirectory: true,
|
||||
status: "pausing",
|
||||
error: undefined,
|
||||
speed: 0,
|
||||
resumable: true,
|
||||
pauseUnavailableReason: "This transfer cannot be paused yet",
|
||||
}, { onPause: () => {}, onResume: () => {} });
|
||||
|
||||
assert.match(markup, /This transfer cannot be paused yet/);
|
||||
assert.match(markup, /aria-label="Pause: archive\.tar\.gz"/);
|
||||
assert.match(markup, /aria-label="Resume: archive\.tar\.gz"/);
|
||||
assert.doesNotMatch(markup, /aria-busy="true"|aria-label="Pausing:/);
|
||||
});
|
||||
|
||||
test("renders child resize handle as a keyboard-reachable separator", () => {
|
||||
const markup = renderTransferItem(
|
||||
{
|
||||
|
||||
@@ -154,7 +154,7 @@ export const ModelSelector: React.FC<{
|
||||
await bridge.aiAllowlistAddHost(baseURL);
|
||||
}
|
||||
const url = buildProviderProbeUrl(baseURL, effectiveModelsEndpoint);
|
||||
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders, baseURL);
|
||||
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders);
|
||||
const result = await bridge.aiFetch(url, "GET", headers, undefined, undefined, undefined, undefined, skipTLSVerify);
|
||||
if (!result.ok) {
|
||||
if (discoveryKeyRef.current !== requestKey) return;
|
||||
|
||||
@@ -139,6 +139,8 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
// panel setTransfersState for every tick — that re-rendered the whole SFTP
|
||||
// tree and pegged the renderer during large copies.
|
||||
const task = useSftpTransferTask(propsTask.id, propsTask);
|
||||
const pauseFailed = task.status === 'pausing' && !!task.pauseUnavailableReason;
|
||||
const isPausing = task.status === 'pausing' && !pauseFailed;
|
||||
|
||||
// Same progress model as the global transfer center (done · found for folders).
|
||||
const isDirParent = isDirectoryParentTask(task);
|
||||
@@ -196,7 +198,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
? (fileCountDisplay
|
||||
? `${t('sftp.transferCenter.phase.scanning')} · ${fileCountDisplay}`
|
||||
: t('sftp.transferCenter.phase.scanning'))
|
||||
: task.status === 'pausing'
|
||||
: isPausing
|
||||
? pausingLabel
|
||||
: isDirParent
|
||||
? (fileCountDisplay
|
||||
@@ -227,7 +229,9 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
|
||||
const statusIcon = isResuming
|
||||
? <Loader2 size={12} className="animate-spin text-primary" />
|
||||
: task.status === 'pausing'
|
||||
: pauseFailed
|
||||
? <Pause size={12} className="text-amber-500" />
|
||||
: isPausing
|
||||
? <Loader2 size={12} className="animate-spin text-amber-500" />
|
||||
: task.status === 'transferring'
|
||||
? <Loader2 size={12} className="animate-spin text-primary" />
|
||||
@@ -290,7 +294,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
// Surface hard pause misses (e.g. "cannot be paused yet") so the panel
|
||||
// pause button never looks dead when the backend refuses.
|
||||
const showPauseUnavailable = !!task.pauseUnavailableReason
|
||||
&& (task.status === 'transferring' || task.status === 'queued' || task.status === 'pending');
|
||||
&& (pauseFailed || task.status === 'transferring' || task.status === 'queued' || task.status === 'pending');
|
||||
const showWarning = task.status === 'completed' && !!task.warning;
|
||||
const hasFooterContent = showTransferSizeCalculation || showFailedError || showPauseUnavailable || showWarning || childWarningCount > 0;
|
||||
const retryActionLabel = t('sftp.transfers.retryAction');
|
||||
@@ -352,7 +356,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
</Button>
|
||||
</IconButtonWithTooltip>
|
||||
)}
|
||||
{task.status === 'transferring' && task.resumable !== false && onPause && !isResuming && (
|
||||
{(task.status === 'transferring' || pauseFailed) && task.resumable !== false && onPause && !isResuming && (
|
||||
<IconButtonWithTooltip label={pauseActionLabel}>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -367,7 +371,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
</Button>
|
||||
</IconButtonWithTooltip>
|
||||
)}
|
||||
{task.status === 'pausing' && (
|
||||
{isPausing && (
|
||||
<IconButtonWithTooltip label={pausingLabel}>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -397,7 +401,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
</Button>
|
||||
</IconButtonWithTooltip>
|
||||
)}
|
||||
{(task.status === 'paused' || task.status === 'interrupted') && onResume && !isResuming && (
|
||||
{(task.status === 'paused' || task.status === 'interrupted' || (pauseFailed && task.resumable !== false)) && onResume && !isResuming && (
|
||||
<IconButtonWithTooltip label={resumeActionLabel}>
|
||||
<Button
|
||||
type="button"
|
||||
|
||||
@@ -2601,18 +2601,6 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
}
|
||||
}
|
||||
|
||||
// Claim Shift+Insert as clipboard paste before Kitty/Win32 or xterm can
|
||||
// encode it as an Insert key, while preserving user shortcut precedence.
|
||||
if (
|
||||
e.key === "Insert" && e.shiftKey
|
||||
&& !e.ctrlKey && !e.altKey && !e.metaKey
|
||||
) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void ctx.terminalContextActionsRef?.current?.onPaste?.();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Sogou/macOS CJK punctuation: keydown still reports ASCII "," while the
|
||||
// full-width "," arrives on insertText. Returning false (without
|
||||
// preventDefault) stops xterm/Kitty from sending the half-width key so the
|
||||
@@ -2788,6 +2776,15 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
};
|
||||
return true;
|
||||
}
|
||||
// xterm leaves Shift+Insert to the browser's native paste handler. Fan out
|
||||
// the clipboard data from onData instead of encoding an Insert key for
|
||||
// peers or treating the paste as that key's pending legacy data (#4142).
|
||||
if (
|
||||
e.key === "Insert" && e.shiftKey
|
||||
&& !e.ctrlKey && !e.altKey && !e.metaKey
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (!shouldDeferKittyKeyEvent(normalizedKittyEvent)) {
|
||||
const identity = kittyKeyIdentity(e);
|
||||
if (
|
||||
|
||||
@@ -7,7 +7,7 @@ import { buildSync } from "esbuild";
|
||||
import { JSDOM } from "jsdom";
|
||||
import ts from "typescript";
|
||||
|
||||
test("Shift+Insert uses onPaste and broadcasts clipboard bytes once across keyboard modes", async () => {
|
||||
test("native Shift+Insert broadcasts clipboard bytes once without an Insert key", async () => {
|
||||
const root = fileURLToPath(new URL("../../..", import.meta.url));
|
||||
const layer = readFileSync(new URL("../../TerminalLayer.tsx", import.meta.url), "utf8");
|
||||
const start = layer.indexOf(" const handleBroadcastInput = useCallback(");
|
||||
@@ -21,8 +21,6 @@ test("Shift+Insert uses onPaste and broadcasts clipboard bytes once across keybo
|
||||
contents: `
|
||||
export { createXTermRuntime } from "./components/terminal/runtime/createXTermRuntime";
|
||||
export { DEFAULT_TERMINAL_SETTINGS } from "./domain/models/terminal";
|
||||
export { DEFAULT_KEY_BINDINGS } from "./domain/models/keyBindings";
|
||||
export { pasteTextIntoTerminal } from "./components/terminal/runtime/terminalUserPaste";
|
||||
export { resolveTerminalBroadcastTargetIds } from "./domain/terminalBroadcast";
|
||||
export { dispatchKittyKeyboardBroadcastInput } from "./components/terminal/runtime/kittyKeyboardBroadcast";
|
||||
export * from "./components/terminal/runtime/terminalPacedBroadcast";
|
||||
@@ -52,8 +50,7 @@ test("Shift+Insert uses onPaste and broadcasts clipboard bytes once across keybo
|
||||
`);
|
||||
dom.window.eval(bundle);
|
||||
const results = await dom.window.eval(`(async () => {
|
||||
const {createXTermRuntime, DEFAULT_TERMINAL_SETTINGS, DEFAULT_KEY_BINDINGS,
|
||||
pasteTextIntoTerminal, resolveTerminalBroadcastTargetIds,
|
||||
const {createXTermRuntime, DEFAULT_TERMINAL_SETTINGS, resolveTerminalBroadcastTargetIds,
|
||||
dispatchKittyKeyboardBroadcastInput, markTerminalBroadcastUserInput,
|
||||
captureTerminalBroadcastInput, isTerminalBroadcastInputCurrent} = runtimeTest;
|
||||
const ref = current => ({current});
|
||||
@@ -63,123 +60,71 @@ test("Shift+Insert uses onPaste and broadcasts clipboard bytes once across keybo
|
||||
const canUseDirectSessionWriteFallback = () => true;
|
||||
const isTerminalSensitiveInputActive = () => false;
|
||||
const wires = new Map();
|
||||
const pasteCalls = new Map();
|
||||
const terminalBackend = {
|
||||
writeToSession:(id,data)=>wires.get(id).push(data), resizeSession(){}, openExternalAvailable:false,
|
||||
};
|
||||
${dispatcher}
|
||||
const make = (id, kittyKeyboardProtocolEnabled, options = {}) => {
|
||||
const make = (id, kittyKeyboardProtocolEnabled) => {
|
||||
const container = document.createElement('div'); document.body.appendChild(container);
|
||||
wires.set(id, []);
|
||||
pasteCalls.set(id, 0);
|
||||
const terminalContextActionsRef = ref({});
|
||||
const host = {id,label:id,hostname:'localhost',protocol:'ssh',sshInputCompatibility:false};
|
||||
const runtime = createXTermRuntime({
|
||||
return createXTermRuntime({
|
||||
container, host, getHost:()=>host, sessionId:id, sessionRef:ref(id), statusRef:ref('connected'),
|
||||
fontFamilyId:'jetbrains-mono',resolvedFontFamily:'monospace',fontSize:14,
|
||||
terminalTheme:{colors:{background:'#111111',foreground:'#eeeeee',cursor:'#ffffff',selection:'#444444'}},
|
||||
terminalSettingsRef:ref({...DEFAULT_TERMINAL_SETTINGS,rendererType:'dom',fontLigatures:false,cursorBlink:false}),
|
||||
terminalBackend,hotkeySchemeRef:ref('pc'),
|
||||
keyBindingsRef:ref(options.bindings ?? DEFAULT_KEY_BINDINGS),onHotkeyActionRef:ref(undefined),
|
||||
terminalContextActionsRef, snippetsRef:ref(options.snippets ?? []),
|
||||
onSnippetShortkeyRef:ref(options.onSnippet),
|
||||
terminalBackend,hotkeySchemeRef:ref('disabled'),keyBindingsRef:ref([]),onHotkeyActionRef:ref(undefined),
|
||||
isBroadcastEnabledRef:ref(true),onBroadcastInputRef:ref(handleBroadcastInput),
|
||||
commandBufferRef:ref(''),requestSearchFocus:options.onSearch ?? (()=>{}),kittyKeyboardProtocolEnabled,
|
||||
commandBufferRef:ref(''),requestSearchFocus(){},kittyKeyboardProtocolEnabled,
|
||||
});
|
||||
terminalContextActionsRef.current.onPaste = async () => {
|
||||
pasteCalls.set(id, pasteCalls.get(id) + 1);
|
||||
if (options.delayed) await new Promise(resolve=>setTimeout(resolve,10));
|
||||
pasteTextIntoTerminal(runtime.term, 'clipboard', {scrollOnPaste:false});
|
||||
};
|
||||
return runtime;
|
||||
};
|
||||
const results = [];
|
||||
const modes = [
|
||||
{name:'legacy',kitty:false,setup:''},
|
||||
{name:'native-kitty',kitty:false,setup:'\\x1b[>1u'},
|
||||
{name:'native-kitty-all-keys',kitty:false,setup:'\\x1b[>8u'},
|
||||
{name:'netcatty-kitty',kitty:true,setup:'\\x1b[>1u'},
|
||||
{name:'win32',kitty:false,setup:'\\x1b[?9001h'},
|
||||
];
|
||||
for (const mode of modes) {
|
||||
for (const bracketed of [false,true]) {
|
||||
for (const delayed of [true,false]) {
|
||||
for (const peerKitty of [false,true]) {
|
||||
const source = make('source', mode.kitty, {delayed}), peer = make('peer', peerKitty);
|
||||
try {
|
||||
sessionsRef.current = ['source','peer'].map(id=>({id,protocol:'ssh',workspaceId:'workspace'}));
|
||||
if (mode.setup) await new Promise(resolve=>source.term.write(mode.setup,resolve));
|
||||
if (peerKitty) await new Promise(resolve=>peer.term.write('\\x1b[>8u',resolve));
|
||||
if (bracketed) await new Promise(resolve=>source.term.write('\\x1b[?2004h',resolve));
|
||||
const key = new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
});
|
||||
source.term.textarea.dispatchEvent(key);
|
||||
if (delayed) await new Promise(resolve=>setTimeout(resolve,20));
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
}));
|
||||
results.push({mode:mode.name,bracketed,delayed,peerKitty,pasteCalls:pasteCalls.get('source'),
|
||||
prevented:key.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
// Ordinary Insert still uses the physical-key broadcast path.
|
||||
if (!peerKitty && mode.name !== 'win32') {
|
||||
wires.get('source').length=0; wires.get('peer').length=0;
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,
|
||||
}));
|
||||
results.push({plainInsert:true,mode:mode.name,pasteCalls:pasteCalls.get('source'),
|
||||
source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
}
|
||||
for (const bracketed of [false,true]) {
|
||||
for (const delayed of [true,false]) {
|
||||
for (const peerKitty of [false,true]) {
|
||||
const source = make('source', false), peer = make('peer', peerKitty);
|
||||
try {
|
||||
sessionsRef.current = ['source','peer'].map(id=>({id,protocol:'ssh',workspaceId:'workspace'}));
|
||||
if (peerKitty) await new Promise(resolve=>peer.term.write('\\x1b[>8u',resolve));
|
||||
if (bracketed) await new Promise(resolve=>source.term.write('\\x1b[?2004h',resolve));
|
||||
const key = new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
});
|
||||
source.term.textarea.dispatchEvent(key);
|
||||
const beforePaste = [...wires.get('peer')];
|
||||
if (delayed) await new Promise(resolve=>setTimeout(resolve,10));
|
||||
// Supply the native clipboard event which Chromium emits for this chord.
|
||||
const paste = new Event('paste', {bubbles:true,cancelable:true});
|
||||
Object.defineProperty(paste,'clipboardData',{value:{getData:()=> 'clipboard'}});
|
||||
source.term.textarea.dispatchEvent(paste);
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
}));
|
||||
results.push({bracketed,delayed,peerKitty,beforePaste,
|
||||
prevented:key.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
// Ordinary Insert still uses the physical-key broadcast path.
|
||||
if (!peerKitty) {
|
||||
wires.get('source').length=0; wires.get('peer').length=0;
|
||||
const pasteShortcut = new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'V',code:'KeyV',keyCode:86,ctrlKey:true,shiftKey:true,
|
||||
});
|
||||
source.term.textarea.dispatchEvent(pasteShortcut);
|
||||
if (delayed) await new Promise(resolve=>setTimeout(resolve,20));
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles:true,key:'V',code:'KeyV',keyCode:86,ctrlKey:true,shiftKey:true,
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,
|
||||
}));
|
||||
results.push({configuredPaste:true,mode:mode.name,bracketed,pasteCalls:pasteCalls.get('source'),
|
||||
prevented:pasteShortcut.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
} finally { source.dispose(); peer.dispose(); }
|
||||
}
|
||||
results.push({plainInsert:true,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
}
|
||||
} finally { source.dispose(); peer.dispose(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const shortcut of ['binding','snippet']) {
|
||||
let searchCalls = 0, snippetCalls = 0;
|
||||
const source = make('source', true, shortcut === 'binding'
|
||||
? {onSearch:()=>searchCalls++,bindings:DEFAULT_KEY_BINDINGS.map(binding=>binding.action === 'searchTerminal'
|
||||
? {...binding,pc:'Shift + Insert'} : binding)}
|
||||
: {snippets:[{id:'snippet',shortkey:'Shift + Insert'}],onSnippet:()=>snippetCalls++});
|
||||
try {
|
||||
await new Promise(resolve=>source.term.write('\\x1b[>1u',resolve));
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
}));
|
||||
results.push({shortcut,pasteCalls:pasteCalls.get('source'),snippetCalls,searchCalls,
|
||||
source:[...wires.get('source')]});
|
||||
} finally { source.dispose(); }
|
||||
}
|
||||
return JSON.stringify(results);
|
||||
})()`);
|
||||
for (const result of JSON.parse(results)) {
|
||||
if (result.plainInsert) {
|
||||
assert.equal(result.pasteCalls, 1);
|
||||
assert.deepEqual(result.source, ["\x1b[2~"]);
|
||||
assert.deepEqual(result.peer, ["\x1b[2~"]);
|
||||
continue;
|
||||
}
|
||||
if (result.shortcut) {
|
||||
assert.equal(result.pasteCalls, 0, result.shortcut);
|
||||
assert.equal(result.snippetCalls, result.shortcut === 'snippet' ? 1 : 0);
|
||||
assert.equal(result.searchCalls, result.shortcut === 'binding' ? 1 : 0);
|
||||
assert.deepEqual(result.source, []);
|
||||
continue;
|
||||
}
|
||||
const label = JSON.stringify(result);
|
||||
assert.equal(result.pasteCalls, result.configuredPaste ? 2 : 1, label);
|
||||
assert.equal(result.prevented, true, label);
|
||||
assert.deepEqual(result.beforePaste, [], label);
|
||||
assert.equal(result.prevented, false, "native paste must remain enabled: " + label);
|
||||
const expected = result.bracketed ? "\x1b[200~clipboard\x1b[201~" : "clipboard";
|
||||
assert.deepEqual(result.source, [expected], label);
|
||||
assert.deepEqual(result.peer, [expected], label);
|
||||
|
||||
@@ -374,14 +374,3 @@ test('side panel close button stays visible at every panel width', () => {
|
||||
assert.match(closeSlice, /className="h-7 w-7 shrink-0 rounded-md p-0 hover:bg-transparent"/);
|
||||
assert.doesNotMatch(closeSlice, /\bhidden\b|max-(sm|md|lg|xl):/);
|
||||
});
|
||||
|
||||
test('magnified side-panel chrome thickens the accent stroke on low-DPR displays', () => {
|
||||
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
|
||||
const overlay = source.slice(
|
||||
source.indexOf('data-section="pane-magnification-overlay"'),
|
||||
source.indexOf('data-section="pane-magnification-content"'),
|
||||
);
|
||||
assert.match(overlay, /overflow-hidden rounded-md border bg-background shadow-2xl/);
|
||||
assert.match(overlay, /borderColor: sidePanelTheme\.accent,/);
|
||||
assert.match(overlay, /resolveMagnifiedChromeBorderWidth\(/);
|
||||
});
|
||||
@@ -64,7 +64,7 @@ import { PersistentSidePanelPortal, SidePanelMountedContent } from './terminalLa
|
||||
import { usePluginTerminalSidebar } from '../../application/state/usePluginTerminalSidebar';
|
||||
import { PluginTerminalSidebarPageHost } from '../plugins/PluginTerminalSidebar';
|
||||
import { PluginContributionIcon } from '../plugins/PluginContributionIcon';
|
||||
import { getPaneMagnificationShortcutLabel, resolveMagnifiedChromeBorderWidth } from '../../domain/paneMagnification';
|
||||
import { getPaneMagnificationShortcutLabel } from '../../domain/paneMagnification';
|
||||
|
||||
const MemoizedSidePanelMountedContent = memo(
|
||||
SidePanelMountedContent,
|
||||
@@ -1545,9 +1545,6 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
|
||||
className="absolute inset-3 flex flex-col overflow-hidden rounded-md border bg-background shadow-2xl animate-in fade-in zoom-in-95 duration-150"
|
||||
style={{
|
||||
borderColor: sidePanelTheme.accent,
|
||||
borderWidth: resolveMagnifiedChromeBorderWidth(
|
||||
typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1),
|
||||
),
|
||||
backgroundColor: sidePanelTheme.termBg,
|
||||
color: sidePanelTheme.termFg,
|
||||
}}
|
||||
|
||||
@@ -52,7 +52,6 @@ import type { ResolvedAppearance, TerminalAppearanceHostScope } from '../../doma
|
||||
import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePanelAutoOpen';
|
||||
import type { SidePanelTool } from '../../domain/sidePanelLayout';
|
||||
import {
|
||||
resolveMagnifiedChromeBorderWidth,
|
||||
resolvePaneMagnificationStyle,
|
||||
type PaneMagnificationController,
|
||||
type PaneMagnificationTarget,
|
||||
@@ -1440,12 +1439,10 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
observer.observe(surface);
|
||||
return () => observer.disconnect();
|
||||
}, [isMagnified]);
|
||||
const magnifiedDevicePixelRatio = typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1);
|
||||
const style: React.CSSProperties = resolvePaneMagnificationStyle(
|
||||
layoutStyle,
|
||||
isMagnified && !!magnifiedSurfaceBounds,
|
||||
magnifiedSurfaceBounds,
|
||||
magnifiedDevicePixelRatio,
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
@@ -1608,9 +1605,6 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
style={{
|
||||
...style,
|
||||
borderColor: isMagnified && magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined,
|
||||
borderWidth: isMagnified && magnifiedSurfaceBounds
|
||||
? resolveMagnifiedChromeBorderWidth(magnifiedDevicePixelRatio)
|
||||
: undefined,
|
||||
}}
|
||||
tabIndex={-1}
|
||||
onClick={handlePaneClick}
|
||||
|
||||
@@ -15,14 +15,6 @@ test("magnified terminal panes use the resolved terminal accent for border chrom
|
||||
|
||||
assert.match(paneSource, /isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl /);
|
||||
assert.match(paneSource, /borderColor: isMagnified && magnifiedSurfaceBounds \? sessionAppearanceTheme\.colors\.cursor : undefined/);
|
||||
assert.match(paneSource, /borderWidth: isMagnified && magnifiedSurfaceBounds/);
|
||||
assert.match(paneSource, /resolveMagnifiedChromeBorderWidth\(magnifiedDevicePixelRatio\)/);
|
||||
});
|
||||
|
||||
test("magnified terminal panes snap overlay bounds to the device-pixel grid", () => {
|
||||
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
|
||||
assert.match(source, /resolvePaneMagnificationStyle\(\s*layoutStyle,\s*isMagnified && !!magnifiedSurfaceBounds,\s*magnifiedSurfaceBounds,\s*magnifiedDevicePixelRatio,\s*\)/);
|
||||
assert.match(source, /const magnifiedDevicePixelRatio = typeof window === 'undefined' \? 1 : \(window\.devicePixelRatio \|\| 1\)/);
|
||||
});
|
||||
|
||||
test("terminal keyboard focus updates the pane selected for magnification", () => {
|
||||
|
||||
@@ -7,9 +7,7 @@ import {
|
||||
isPaneMagnificationSelectionValid,
|
||||
resolvePaneMagnificationCandidate,
|
||||
resolvePaneMagnificationStyle,
|
||||
resolveMagnifiedChromeBorderWidth,
|
||||
resolveTwoPaneMagnificationStyle,
|
||||
snapCssRectToDevicePixels,
|
||||
type PaneMagnificationController,
|
||||
} from './paneMagnification.ts';
|
||||
|
||||
@@ -92,53 +90,6 @@ test('magnification overlays the original layout without changing its rect', ()
|
||||
});
|
||||
});
|
||||
|
||||
test('magnified chrome uses a 2px accent stroke only below 1.5 device pixels', () => {
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1), 2);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1.2), 2);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1.49), 2);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1.5), 1);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(2), 1);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(0), 1);
|
||||
});
|
||||
|
||||
test('magnified surface bounds snap to the device-pixel grid after the 12px inset', () => {
|
||||
const original = { left: '0px', top: '0px', width: '100px', height: '100px' };
|
||||
// Integer CSS pixels at 1x stay unchanged (existing contract).
|
||||
assert.deepEqual(resolvePaneMagnificationStyle(original, true, {
|
||||
left: 120,
|
||||
top: 80,
|
||||
width: 1400,
|
||||
height: 900,
|
||||
}, 1), {
|
||||
position: 'fixed',
|
||||
left: '132px',
|
||||
top: '92px',
|
||||
width: '1376px',
|
||||
height: '876px',
|
||||
zIndex: 50,
|
||||
});
|
||||
|
||||
// 120.4+12=132.4 at 2x -> 264.8 rounds to 265 -> 132.5
|
||||
// right: 120.4+1400-12=1508.4 at 2x -> 3016.8 rounds to 3017 -> 1508.5
|
||||
const snapped = resolvePaneMagnificationStyle(original, true, {
|
||||
left: 120.4,
|
||||
top: 80.4,
|
||||
width: 1400,
|
||||
height: 900,
|
||||
}, 2);
|
||||
assert.deepEqual(snapped, {
|
||||
position: 'fixed',
|
||||
left: '132.5px',
|
||||
top: '92.5px',
|
||||
width: '1376px',
|
||||
height: '876px',
|
||||
zIndex: 50,
|
||||
});
|
||||
|
||||
const rect = snapCssRectToDevicePixels(10.2, 20.2, 110.2, 80.2, 2);
|
||||
assert.deepEqual(rect, { left: 10, top: 20, width: 100, height: 60 });
|
||||
});
|
||||
|
||||
test('two-pane magnification keeps the dormant pane geometry unchanged', () => {
|
||||
assert.deepEqual(resolveTwoPaneMagnificationStyle('left', true, true), {
|
||||
left: '12px', top: '12px', width: 'calc(100% - 24px)', height: 'calc(100% - 24px)', zIndex: 50,
|
||||
|
||||
@@ -92,52 +92,19 @@ export function getPaneMagnificationShortcutLabel(
|
||||
return (hotkeyScheme === 'mac' ? binding?.mac : binding?.pc)?.replace(/ \+ /g, '+') ?? '';
|
||||
}
|
||||
|
||||
export function resolveMagnifiedChromeBorderWidth(devicePixelRatio = 1): number {
|
||||
return devicePixelRatio > 0 && devicePixelRatio < 1.5 ? 2 : 1;
|
||||
}
|
||||
|
||||
export function snapCssRectToDevicePixels(
|
||||
left: number,
|
||||
top: number,
|
||||
right: number,
|
||||
bottom: number,
|
||||
devicePixelRatio = 1,
|
||||
): { left: number; top: number; width: number; height: number } {
|
||||
const dpr = devicePixelRatio > 0 ? devicePixelRatio : 1;
|
||||
const snap = (value: number) => Math.round(value * dpr) / dpr;
|
||||
const snappedLeft = snap(left);
|
||||
const snappedTop = snap(top);
|
||||
const snappedRight = snap(right);
|
||||
const snappedBottom = snap(bottom);
|
||||
return {
|
||||
left: snappedLeft,
|
||||
top: snappedTop,
|
||||
width: Math.max(0, snappedRight - snappedLeft),
|
||||
height: Math.max(0, snappedBottom - snappedTop),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolvePaneMagnificationStyle(
|
||||
original: React.CSSProperties,
|
||||
magnified: boolean,
|
||||
surfaceBounds?: { left: number; top: number; width: number; height: number } | null,
|
||||
devicePixelRatio = 1,
|
||||
): React.CSSProperties {
|
||||
if (!magnified) return original;
|
||||
if (surfaceBounds) {
|
||||
const snapped = snapCssRectToDevicePixels(
|
||||
surfaceBounds.left + 12,
|
||||
surfaceBounds.top + 12,
|
||||
surfaceBounds.left + surfaceBounds.width - 12,
|
||||
surfaceBounds.top + surfaceBounds.height - 12,
|
||||
devicePixelRatio,
|
||||
);
|
||||
return {
|
||||
position: 'fixed',
|
||||
left: `${snapped.left}px`,
|
||||
top: `${snapped.top}px`,
|
||||
width: `${snapped.width}px`,
|
||||
height: `${snapped.height}px`,
|
||||
left: `${surfaceBounds.left + 12}px`,
|
||||
top: `${surfaceBounds.top + 12}px`,
|
||||
width: `${Math.max(0, surfaceBounds.width - 24)}px`,
|
||||
height: `${Math.max(0, surfaceBounds.height - 24)}px`,
|
||||
zIndex: 50,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import type { TransferTask } from './models';
|
||||
import { getGlobalTransferBatchEligibility, listGloballyPausableTransferIds } from './sftpTransferActions';
|
||||
|
||||
test('a partially failed folder pause can be retried or explicitly resumed', () => {
|
||||
const task = { id: 'folder', status: 'pausing', isDirectory: true, resumable: true,
|
||||
pauseUnavailableReason: 'This transfer cannot be paused yet' } as TransferTask;
|
||||
assert.equal(getGlobalTransferBatchEligibility([task]).pausableCount, 1);
|
||||
assert.equal(getGlobalTransferBatchEligibility([task]).resumableCount, 1);
|
||||
assert.deepEqual(listGloballyPausableTransferIds([task]), ['folder']);
|
||||
assert.equal(getGlobalTransferBatchEligibility([{ ...task, pauseUnavailableReason: undefined }]).pausableCount, 0);
|
||||
});
|
||||
@@ -5,7 +5,8 @@ export function getGlobalTransferBatchEligibility(tasks: readonly TransferTask[]
|
||||
return {
|
||||
cancellableCount: listGloballyCancellableTransferIds(tasks).length,
|
||||
pausableCount: topLevel.filter((task) => (
|
||||
["pending", "queued", "transferring"].includes(task.status)
|
||||
(["pending", "queued", "transferring"].includes(task.status)
|
||||
|| (task.status === "pausing" && !!task.pauseUnavailableReason))
|
||||
&& task.resumable !== false
|
||||
&& !(task.ownerId === "dedicated-resume" && task.reconnectRequired)
|
||||
)).length,
|
||||
|
||||
@@ -70,10 +70,6 @@ const CMD_PROMPT_PATTERN = /^[A-Za-z]:(?:\\[^<>"|]*)?>$/;
|
||||
// the final `]` before `$`/`#` is the delimiter.
|
||||
const POSIX_PROMPT_PATTERN = /^(?:[^\s@]+@[^\s:]+(?::[^\n\r]*)?|\[[^\s@\]]+@[^\s\]:]+(?:\s+[^\n\r]+)?\])[#$]$/;
|
||||
|
||||
// Bracket PS1 without @host, with bash `\t` time: `[\u \t \w]$` -> `[root 12:04:23 ~]$` (#4276).
|
||||
// Require HH:MM:SS so loose `[word]$` output cannot count as idle.
|
||||
const BRACKET_TIME_POSIX_PROMPT_PATTERN = /^\[[^\s@\]]+\s+\d{2}:\d{2}:\d{2}(?:\s+[^\n\r\]]+)?\][#$]$/;
|
||||
|
||||
// Space-separated bash PS1 `\u@\h \w $ ` renders as `user@host ~ $`.
|
||||
// macOS ships zsh with `%n@%m %1~ %#`, which renders as
|
||||
// `user@host ~ %` / `user@host My Project %`; privileged shells end in `#`.
|
||||
@@ -141,7 +137,6 @@ function isDefaultPosixPromptLine(line) {
|
||||
const withoutEnvPrefix = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
|
||||
return (
|
||||
POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
BRACKET_TIME_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
PAREN_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
ALPINE_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
ZSH_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
|
||||
@@ -192,30 +192,6 @@ test("isDefaultPosixPromptLine matches classic user@host prompts", () => {
|
||||
assert.equal(isDefaultPosixPromptLine(""), false);
|
||||
});
|
||||
|
||||
test("recognizes bracketed time prompts without a hostname and preserves trailing space", () => {
|
||||
for (const prompt of [
|
||||
"[root 12:04:23 ~]$",
|
||||
"[root 12:04:23 ~]$ ",
|
||||
"[alice 00:00:00 /var/log]# ",
|
||||
"[alice-admin 23:59:59 ~/src]$ ",
|
||||
]) {
|
||||
assert.equal(isDefaultPosixPromptLine(prompt), true, prompt);
|
||||
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt);
|
||||
}
|
||||
});
|
||||
|
||||
test("bracketed time prompt recognition rejects pending input and prompts without time", () => {
|
||||
for (const line of [
|
||||
"[root 12:04:23 ~]$ hostname",
|
||||
"[root 12:04:23 ~]$ echo $",
|
||||
"[root ~]$",
|
||||
"[word]$",
|
||||
]) {
|
||||
assert.equal(isDefaultPosixPromptLine(line), false, line);
|
||||
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${line}`), "", line);
|
||||
}
|
||||
});
|
||||
|
||||
test("recognizes space-separated Bash idle prompts and preserves trailing whitespace", () => {
|
||||
for (const prompt of [
|
||||
"root@VM-Q7L4M8P2 ~ $",
|
||||
@@ -512,13 +488,6 @@ test("extracts a trailing RHEL-family bracketed idle prompt", () => {
|
||||
assert.equal(extractTrailingIdlePrompt("welcome\r\nroot@host ~#"), "");
|
||||
});
|
||||
|
||||
test("extractTrailingIdlePrompt recognizes an ANSI-colored bracketed time prompt", () => {
|
||||
assert.equal(
|
||||
extractTrailingIdlePrompt("welcome\r\n[\x1b[1;34mroot \x1b[1;36m12:04:23 \x1b[1;32m~\x1b[0m]$ "),
|
||||
"[root 12:04:23 ~]$ ",
|
||||
);
|
||||
});
|
||||
|
||||
test("extractTrailingIdlePrompt recognizes a two-line user@host then bare $/# PS1", () => {
|
||||
// export PS1="\u@\h: \w\n$ " paints the host line, then a lone "$ ".
|
||||
// The cached prompt must keep both lines so a lone "$" cannot satisfy endsWith.
|
||||
@@ -1264,14 +1233,6 @@ test("trackSessionIdlePrompt and getFreshIdlePrompt accept an Oracle/RHEL bracke
|
||||
assert.equal(getFreshIdlePrompt(bracketedPath), "[user@host My [Project]]$ ");
|
||||
});
|
||||
|
||||
test("trackSessionIdlePrompt and getFreshIdlePrompt accept a bracketed time prompt", () => {
|
||||
const session = {};
|
||||
const prompt = "[root 12:04:23 ~]$ ";
|
||||
assert.equal(trackSessionIdlePrompt(session, `Last login...\r\n${prompt}`), prompt);
|
||||
assert.equal(session.lastIdlePrompt, prompt);
|
||||
assert.equal(getFreshIdlePrompt(session), prompt);
|
||||
});
|
||||
|
||||
test("visible idle prompt survives a PSReadLine erase that leaves the raw tail dirty", () => {
|
||||
// PSReadLine echoes the pending-input clear prefix (`ggd2147483647d` / `i`),
|
||||
// then homes the cursor and erases those keys with CSI. stripAnsi drops the
|
||||
|
||||
@@ -71,19 +71,3 @@ test("normalizeAnthropicSdkBaseURL preserves custom non-/v1 path prefixes", () =
|
||||
"https://gateway.example/api/v1",
|
||||
);
|
||||
});
|
||||
|
||||
test("normalizes the official Ark Agent Plan Anthropic prefix only", () => {
|
||||
const base = "https://ark.cn-beijing.volces.com/api/plan";
|
||||
for (const input of [base, base + "/", " " + base + " ", base + "/v1", base + "/v1/"]) {
|
||||
assert.equal(normalizeAnthropicSdkBaseURL(input), base + "/v1");
|
||||
}
|
||||
for (const input of [
|
||||
base.replace("https:", "http:"),
|
||||
base.replace(".com", ".com.example"),
|
||||
base.replace(".com", ".com:8443"),
|
||||
base + "/custom",
|
||||
"https://gateway.example/api/plan",
|
||||
]) {
|
||||
assert.equal(normalizeAnthropicSdkBaseURL(input), input);
|
||||
}
|
||||
});
|
||||
@@ -39,7 +39,6 @@ export function isBareOriginBaseURL(baseURL: string): boolean {
|
||||
* Normalize a stored Anthropic-compat Base URL for @ai-sdk/anthropic.
|
||||
* - Bare hosts gain a /v1 suffix (Claude Code style → SDK style).
|
||||
* - Bases that already end in /v1 are left unchanged.
|
||||
* - The official Ark Agent Plan /api/plan prefix gains a /v1 suffix.
|
||||
* - Other path prefixes (custom proxies) are left unchanged so chat keeps
|
||||
* requesting `{prefix}/messages` rather than `{prefix}/v1/messages`.
|
||||
*/
|
||||
@@ -47,9 +46,6 @@ export function normalizeAnthropicSdkBaseURL(baseURL: string): string {
|
||||
const trimmed = stripTrailingSlashes(baseURL);
|
||||
if (!trimmed) return trimmed;
|
||||
if (anthropicBaseIncludesV1(trimmed)) return trimmed;
|
||||
// Claude Code appends /v1/messages to the documented Ark Agent Plan base.
|
||||
// The Anthropic SDK appends only /messages, so supply the missing /v1.
|
||||
if (trimmed === "https://ark.cn-beijing.volces.com/api/plan") return `${trimmed}/v1`;
|
||||
if (!isBareOriginBaseURL(trimmed)) return trimmed;
|
||||
return `${trimmed}/v1`;
|
||||
}
|
||||
@@ -142,12 +142,7 @@ export async function fetchProviderModelCatalog(
|
||||
await bridge.aiAllowlistAddHost(baseURL);
|
||||
}
|
||||
const url = buildProviderProbeUrl(baseURL, endpoint);
|
||||
const headers = buildModelDiscoveryHeaders(
|
||||
style,
|
||||
apiKey,
|
||||
await decryptProviderHeaders(provider.customHeaders),
|
||||
baseURL,
|
||||
);
|
||||
const headers = buildModelDiscoveryHeaders(style, apiKey, await decryptProviderHeaders(provider.customHeaders));
|
||||
const result = await bridge.aiFetch(
|
||||
url,
|
||||
'GET',
|
||||
|
||||
@@ -1,34 +1,13 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
buildModelDiscoveryHeaders,
|
||||
isCustomAnthropicBaseURL,
|
||||
resolveModelsDiscoveryEndpoint,
|
||||
} from "./modelDiscoveryHeaders";
|
||||
import { buildModelDiscoveryHeaders, resolveModelsDiscoveryEndpoint } from "./modelDiscoveryHeaders";
|
||||
|
||||
test("buildModelDiscoveryHeaders uses x-api-key+anthropic-version only on official anthropic host", () => {
|
||||
for (const baseURL of [undefined, "", "https://api.anthropic.com", "https://api.anthropic.com/v1"]) {
|
||||
assert.deepEqual(buildModelDiscoveryHeaders("anthropic", "sk-test", {}, baseURL), {
|
||||
"x-api-key": "sk-test",
|
||||
"anthropic-version": "2023-06-01",
|
||||
});
|
||||
assert.equal(isCustomAnthropicBaseURL(baseURL), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("buildModelDiscoveryHeaders sends both x-api-key and Bearer auth on custom anthropic bases", () => {
|
||||
for (const baseURL of [
|
||||
"https://ark.cn-beijing.volces.com/api/plan",
|
||||
"https://gateway.example/v1",
|
||||
]) {
|
||||
assert.equal(isCustomAnthropicBaseURL(baseURL), true);
|
||||
assert.deepEqual(buildModelDiscoveryHeaders("anthropic", "sk-test", {}, baseURL), {
|
||||
"x-api-key": "sk-test",
|
||||
Authorization: "Bearer sk-test",
|
||||
"anthropic-version": "2023-06-01",
|
||||
});
|
||||
}
|
||||
test("buildModelDiscoveryHeaders uses x-api-key+anthropic-version for the anthropic family", () => {
|
||||
assert.deepEqual(buildModelDiscoveryHeaders("anthropic", "sk-test"), {
|
||||
"x-api-key": "sk-test",
|
||||
"anthropic-version": "2023-06-01",
|
||||
});
|
||||
});
|
||||
|
||||
test("buildModelDiscoveryHeaders uses Bearer auth for the openai-compatible family", () => {
|
||||
@@ -86,16 +65,4 @@ test('custom discovery headers override default auth regardless of case', () =>
|
||||
assert.equal(Object.keys(headers).filter(key => key.toLowerCase() === name.toLowerCase()).length, 1);
|
||||
assert.equal(headers['X-Tenant'], 'tenant');
|
||||
}
|
||||
|
||||
const customAnthropicAuth = buildModelDiscoveryHeaders(
|
||||
'anthropic',
|
||||
'default-key',
|
||||
{ authorization: 'Bearer custom-token' },
|
||||
'https://ark.cn-beijing.volces.com/api/plan',
|
||||
);
|
||||
assert.deepEqual(customAnthropicAuth, {
|
||||
'x-api-key': 'default-key',
|
||||
'anthropic-version': '2023-06-01',
|
||||
authorization: 'Bearer custom-token',
|
||||
});
|
||||
});
|
||||
@@ -27,27 +27,11 @@ export function resolveModelsDiscoveryEndpoint(
|
||||
return STYLE_DEFAULT_MODELS_ENDPOINT[style] ?? presetEndpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `baseURL` is a valid URL whose host is not the official
|
||||
* `api.anthropic.com` endpoint. Omitted or blank values default to the
|
||||
* official host and return `false`.
|
||||
*/
|
||||
export function isCustomAnthropicBaseURL(baseURL?: string): boolean {
|
||||
const trimmed = baseURL?.trim();
|
||||
if (!trimmed) return false;
|
||||
try {
|
||||
return new URL(trimmed).hostname.toLowerCase() !== "api.anthropic.com";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick auth headers for a provider's `/models` discovery endpoint.
|
||||
*
|
||||
* Each wire-protocol family uses its own auth dialect:
|
||||
* - `anthropic`: `x-api-key` + `anthropic-version` on official `api.anthropic.com`;
|
||||
* custom Anthropic-compatible gateways also receive `Authorization: Bearer ...`
|
||||
* - `anthropic`: `x-api-key` + `anthropic-version`
|
||||
* - `google`: `x-goog-api-key` (Google Generative AI rejects Bearer)
|
||||
* - `openai`: `Authorization: Bearer …` (also the OpenAI-compat default)
|
||||
*
|
||||
@@ -57,16 +41,12 @@ export function isCustomAnthropicBaseURL(baseURL?: string): boolean {
|
||||
function buildDefaultModelDiscoveryHeaders(
|
||||
style: ProviderStyle,
|
||||
apiKey: string | undefined,
|
||||
baseURL?: string,
|
||||
): Record<string, string> {
|
||||
if (!apiKey) return {};
|
||||
switch (style) {
|
||||
case "anthropic":
|
||||
return {
|
||||
"x-api-key": apiKey,
|
||||
...(isCustomAnthropicBaseURL(baseURL)
|
||||
? { Authorization: `Bearer ${apiKey}` }
|
||||
: {}),
|
||||
"anthropic-version": "2023-06-01",
|
||||
};
|
||||
case "google":
|
||||
@@ -81,9 +61,8 @@ export function buildModelDiscoveryHeaders(
|
||||
style: ProviderStyle,
|
||||
apiKey: string | undefined,
|
||||
customHeaders: Record<string, string> = {},
|
||||
baseURL?: string,
|
||||
): Record<string, string> {
|
||||
const headers = buildDefaultModelDiscoveryHeaders(style, apiKey, baseURL);
|
||||
const headers = buildDefaultModelDiscoveryHeaders(style, apiKey);
|
||||
const overridden = new Set(Object.keys(customHeaders).map((name) => name.toLowerCase()));
|
||||
return Object.fromEntries([
|
||||
...Object.entries(headers).filter(([name]) => !overridden.has(name.toLowerCase())),
|
||||
|
||||
@@ -59,38 +59,17 @@ test("validateProviderProbeInputs requires base URL and API key except for ollam
|
||||
);
|
||||
});
|
||||
|
||||
test("classifyProviderProbeResponse marks auth, permission, server, and transport failures as error", () => {
|
||||
test("classifyProviderProbeResponse marks auth and transport failures as error", () => {
|
||||
assert.equal(
|
||||
classifyProviderProbeResponse({ ok: false, status: 401, latencyMs: 120, error: "Unauthorized" }).health,
|
||||
"error",
|
||||
);
|
||||
assert.equal(
|
||||
classifyProviderProbeResponse({ ok: false, status: 403, latencyMs: 90 }).health,
|
||||
"error",
|
||||
);
|
||||
assert.equal(
|
||||
classifyProviderProbeResponse({ ok: false, status: 502, latencyMs: 200 }).health,
|
||||
"error",
|
||||
);
|
||||
assert.equal(
|
||||
classifyProviderProbeResponse({ ok: false, status: 0, latencyMs: 30, error: "Request timeout" }).health,
|
||||
"error",
|
||||
);
|
||||
});
|
||||
|
||||
test("classifyProviderProbeResponse downgrades HTTP 404 models-list probe to warn", () => {
|
||||
const result = classifyProviderProbeResponse({
|
||||
ok: false,
|
||||
status: 404,
|
||||
latencyMs: 95,
|
||||
data: "404 page not found",
|
||||
});
|
||||
assert.equal(result.health, "warn");
|
||||
assert.equal(result.statusCode, 404);
|
||||
assert.equal(result.latencyMs, 95);
|
||||
assert.ok(result.error && result.error.includes("404"));
|
||||
});
|
||||
|
||||
test("classifyProviderProbeResponse marks 2xx with models payload as ok", () => {
|
||||
const result = classifyProviderProbeResponse({
|
||||
ok: true,
|
||||
@@ -209,11 +188,11 @@ test("probeProviderConnection returns typed failures before fetch", async () =>
|
||||
});
|
||||
|
||||
test("probeProviderConnection does not double /v1 for Anthropic AI SDK style bases", async () => {
|
||||
const calls: Array<{ url: string; headers?: Record<string, string> }> = [];
|
||||
const calls: string[] = [];
|
||||
const run = await probeProviderConnection({
|
||||
bridge: {
|
||||
aiFetch: async (url, _method, headers) => {
|
||||
calls.push({ url, headers });
|
||||
aiFetch: async (url) => {
|
||||
calls.push(url);
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
@@ -226,90 +205,6 @@ test("probeProviderConnection does not double /v1 for Anthropic AI SDK style bas
|
||||
providerId: "custom",
|
||||
style: "anthropic",
|
||||
});
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
url: "https://gateway.example/v1/models",
|
||||
headers: {
|
||||
"x-api-key": "sk-test",
|
||||
Authorization: "Bearer sk-test",
|
||||
"anthropic-version": "2023-06-01",
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(calls, ["https://gateway.example/v1/models"]);
|
||||
assert.equal(run.ok, true);
|
||||
});
|
||||
|
||||
test("probeProviderConnection keeps official Anthropic free of Bearer while custom gateways get Bearer and 404 warns", async () => {
|
||||
const calls: Array<{ url: string; headers?: Record<string, string> }> = [];
|
||||
|
||||
const official = await probeProviderConnection({
|
||||
bridge: {
|
||||
aiFetch: async (url, _method, headers) => {
|
||||
calls.push({ url, headers });
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
data: JSON.stringify({ data: [{ id: "claude-sonnet-4-5" }] }),
|
||||
};
|
||||
},
|
||||
},
|
||||
baseURL: "https://api.anthropic.com",
|
||||
apiKey: "sk-ant-test",
|
||||
providerId: "anthropic",
|
||||
style: "anthropic",
|
||||
});
|
||||
assert.equal(official.ok, true);
|
||||
assert.deepEqual(calls[0], {
|
||||
url: "https://api.anthropic.com/v1/models",
|
||||
headers: {
|
||||
"x-api-key": "sk-ant-test",
|
||||
"anthropic-version": "2023-06-01",
|
||||
},
|
||||
});
|
||||
|
||||
const agentPlanOpenAI = await probeProviderConnection({
|
||||
bridge: {
|
||||
aiFetch: async (url, _method, headers) => {
|
||||
calls.push({ url, headers });
|
||||
return { ok: false, status: 404, data: "404 page not found" };
|
||||
},
|
||||
},
|
||||
baseURL: "https://ark.cn-beijing.volces.com/api/plan/v3",
|
||||
apiKey: "ark-key",
|
||||
providerId: "custom",
|
||||
style: "openai",
|
||||
});
|
||||
assert.equal(agentPlanOpenAI.ok, true);
|
||||
if (!agentPlanOpenAI.ok) throw new Error("expected probe result");
|
||||
assert.equal(agentPlanOpenAI.classification.health, "warn");
|
||||
assert.equal(agentPlanOpenAI.classification.statusCode, 404);
|
||||
assert.deepEqual(calls[1], {
|
||||
url: "https://ark.cn-beijing.volces.com/api/plan/v3/models",
|
||||
headers: { Authorization: "Bearer ark-key" },
|
||||
});
|
||||
|
||||
const agentPlanAnthropic = await probeProviderConnection({
|
||||
bridge: {
|
||||
aiFetch: async (url, _method, headers) => {
|
||||
calls.push({ url, headers });
|
||||
return { ok: false, status: 404, data: "404 page not found" };
|
||||
},
|
||||
},
|
||||
baseURL: "https://ark.cn-beijing.volces.com/api/plan",
|
||||
apiKey: "ark-key",
|
||||
providerId: "custom",
|
||||
style: "anthropic",
|
||||
});
|
||||
assert.equal(agentPlanAnthropic.ok, true);
|
||||
if (!agentPlanAnthropic.ok) throw new Error("expected probe result");
|
||||
assert.equal(agentPlanAnthropic.classification.health, "warn");
|
||||
assert.equal(agentPlanAnthropic.classification.statusCode, 404);
|
||||
assert.deepEqual(calls[2], {
|
||||
url: "https://ark.cn-beijing.volces.com/api/plan/v1/models",
|
||||
headers: {
|
||||
"x-api-key": "ark-key",
|
||||
Authorization: "Bearer ark-key",
|
||||
"anthropic-version": "2023-06-01",
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -98,8 +98,7 @@ function countModelsInPayload(data: string | undefined): number | undefined {
|
||||
|
||||
/**
|
||||
* Map a lightweight `/models` (or equivalent) probe response to green / yellow / red.
|
||||
* Yellow covers slow-but-successful replies, empty model catalogs, and HTTP 404
|
||||
* (gateways that work for chat without exposing a models listing route).
|
||||
* Yellow covers slow-but-successful replies and empty model catalogs.
|
||||
*/
|
||||
export function classifyProviderProbeResponse(input: {
|
||||
ok: boolean;
|
||||
@@ -116,14 +115,6 @@ export function classifyProviderProbeResponse(input: {
|
||||
...(input.error ? { error: input.error } : {}),
|
||||
};
|
||||
|
||||
if (input.status === 404) {
|
||||
return {
|
||||
...base,
|
||||
health: "warn",
|
||||
error: input.error || "Model list not available (HTTP 404)",
|
||||
};
|
||||
}
|
||||
|
||||
if (!input.ok || input.status < 200 || input.status >= 300) {
|
||||
return {
|
||||
...base,
|
||||
@@ -191,12 +182,7 @@ export async function probeProviderConnection(input: {
|
||||
await bridge.aiAllowlistAddHost(baseURL);
|
||||
}
|
||||
const url = buildProviderProbeUrl(baseURL, endpoint);
|
||||
const headers = buildModelDiscoveryHeaders(
|
||||
input.style,
|
||||
input.apiKey,
|
||||
input.customHeaders,
|
||||
baseURL,
|
||||
);
|
||||
const headers = buildModelDiscoveryHeaders(input.style, input.apiKey, input.customHeaders);
|
||||
const result = await bridge.aiFetch(
|
||||
url,
|
||||
"GET",
|
||||
|
||||
@@ -5,7 +5,6 @@ import { wrapLanguageModel, type LanguageModelMiddleware } from 'ai';
|
||||
import type { ProviderConfig, ProviderStyle } from '../types';
|
||||
import { resolveOpenAIApi, resolveProviderStyle } from '../types';
|
||||
import { normalizeAnthropicSdkBaseURL } from '../anthropicCompatBaseUrl';
|
||||
import { isCustomAnthropicBaseURL } from '../modelDiscoveryHeaders';
|
||||
import { buildSdkRequestHeaders } from '../providerRequestHeaders';
|
||||
import { normalizeOllamaSdkBaseURL } from '../ollamaCompatBaseUrl';
|
||||
import { normalizeOpenAIChatCacheUsage } from '../openAIChatCacheUsage';
|
||||
@@ -775,25 +774,13 @@ function createProviderModel(
|
||||
: openai.chat(modelId);
|
||||
}
|
||||
|
||||
case 'anthropic': {
|
||||
// Official api.anthropic.com keeps x-api-key only. Custom Anthropic-compat
|
||||
// gateways (e.g. Volcengine Ark Agent Plan, Claude Code proxies) may require
|
||||
// Authorization: Bearer (ANTHROPIC_AUTH_TOKEN) or x-api-key, so send both.
|
||||
// @ai-sdk/anthropic rejects passing apiKey and authToken together, so pass
|
||||
// authToken for Bearer and retain x-api-key in headers unless overridden.
|
||||
const useCustomBearer = Boolean(apiKey && isCustomAnthropicBaseURL(baseURL));
|
||||
const hasCustomXApiKey = Object.keys(sdkHeaders).some(
|
||||
(key) => key.toLowerCase() === 'x-api-key',
|
||||
);
|
||||
case 'anthropic':
|
||||
return createAnthropic({
|
||||
...(useCustomBearer ? { authToken: apiKey } : { apiKey }),
|
||||
apiKey,
|
||||
baseURL,
|
||||
fetch: customFetch,
|
||||
headers: useCustomBearer && !hasCustomXApiKey
|
||||
? { 'x-api-key': apiKey!, ...sdkHeaders }
|
||||
: sdkHeaders,
|
||||
headers: sdkHeaders,
|
||||
})(modelId);
|
||||
}
|
||||
|
||||
case 'google':
|
||||
return createGoogle({
|
||||
|
||||
@@ -323,75 +323,3 @@ test("OpenAI Chat sends inline image attachments as data URLs through the bridge
|
||||
}
|
||||
assert.equal(requests.length, 4);
|
||||
});
|
||||
|
||||
test("Anthropic SDK sends x-api-key only on official host and adds Bearer on custom bases", async (t) => {
|
||||
const browserGlobal = globalThis as typeof globalThis & { window?: unknown };
|
||||
const originalWindow = browserGlobal.window;
|
||||
t.after(() => { browserGlobal.window = originalWindow; });
|
||||
const requests: Array<{ url: string; headers: Headers }> = [];
|
||||
Reflect.set(globalThis, "window", {
|
||||
netcatty: {
|
||||
aiFetch: async (url: string, _method: string, headers: Record<string, string>) => {
|
||||
requests.push({ url, headers: new Headers(headers) });
|
||||
return { ok: false, status: 400, data: '{"error":{"message":"captured anthropic request"}}' };
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const prompt = [{ role: "user" as const, content: [{ type: "text" as const, text: "hello" }] }];
|
||||
|
||||
for (const baseURL of [undefined, "https://api.anthropic.com", "https://api.anthropic.com/v1"]) {
|
||||
const model = createModelFromConfig(makeConfig({
|
||||
providerId: "anthropic",
|
||||
style: "anthropic",
|
||||
apiKey: "test-key",
|
||||
baseURL,
|
||||
}));
|
||||
await assert.rejects(async () => await model.doGenerate({ prompt }));
|
||||
const request = requests.at(-1)!;
|
||||
assert.equal(request.headers.get("x-api-key"), "__IPC_SECURED__");
|
||||
assert.equal(request.headers.get("authorization"), null);
|
||||
assert.equal(request.headers.get("anthropic-version"), "2023-06-01");
|
||||
}
|
||||
|
||||
for (const baseURL of [
|
||||
"https://ark.cn-beijing.volces.com/api/plan",
|
||||
"https://gateway.example/v1",
|
||||
]) {
|
||||
const model = createModelFromConfig(makeConfig({
|
||||
style: "anthropic",
|
||||
apiKey: "test-key",
|
||||
baseURL,
|
||||
}));
|
||||
await assert.rejects(async () => await model.doGenerate({ prompt }));
|
||||
const request = requests.at(-1)!;
|
||||
assert.equal(request.url, baseURL.endsWith("/api/plan")
|
||||
? baseURL + "/v1/messages"
|
||||
: baseURL + "/messages");
|
||||
assert.equal(request.headers.get("x-api-key"), "__IPC_SECURED__");
|
||||
assert.equal(request.headers.get("authorization"), "Bearer __IPC_SECURED__");
|
||||
assert.equal(request.headers.get("anthropic-version"), "2023-06-01");
|
||||
}
|
||||
|
||||
const overridden = createModelFromConfig(makeConfig({
|
||||
style: "anthropic",
|
||||
apiKey: "test-key",
|
||||
baseURL: "https://ark.cn-beijing.volces.com/api/plan",
|
||||
customHeaders: { Authorization: "Bearer custom-override" },
|
||||
}));
|
||||
await assert.rejects(async () => await overridden.doGenerate({ prompt }));
|
||||
const overriddenReq = requests.at(-1)!;
|
||||
assert.equal(overriddenReq.headers.get("x-api-key"), "__IPC_SECURED__");
|
||||
assert.equal(overriddenReq.headers.get("authorization"), "Bearer custom-override");
|
||||
|
||||
const overriddenApiKey = createModelFromConfig(makeConfig({
|
||||
style: "anthropic",
|
||||
apiKey: "test-key",
|
||||
baseURL: "https://ark.cn-beijing.volces.com/api/plan",
|
||||
customHeaders: { "X-API-Key": "custom-x-api-key" },
|
||||
}));
|
||||
await assert.rejects(async () => await overriddenApiKey.doGenerate({ prompt }));
|
||||
const overriddenApiKeyReq = requests.at(-1)!;
|
||||
assert.equal(overriddenApiKeyReq.headers.get("x-api-key"), "custom-x-api-key");
|
||||
assert.equal(overriddenApiKeyReq.headers.get("authorization"), "Bearer __IPC_SECURED__");
|
||||
});
|
||||
Reference in new issue
Block a user