mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-19 14:34:29 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4c9f1dbd3 |
No files matched your search
@@ -541,98 +541,3 @@ 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 = "pausing" as const;
|
||||
const immediateStatus = task.isDirectory ? "paused" as const : "pausing" as const;
|
||||
// Freeze via latch/status; leave lifecycleEpoch alone until bridge responds.
|
||||
host.setTasks(paintTreeStatus(
|
||||
host.getTasks(),
|
||||
@@ -271,11 +271,7 @@ export async function softPauseTransfer(
|
||||
if (!pauseStillCurrent()) {
|
||||
return { id, result: { success: false, reason: "Pause superseded by resume" } };
|
||||
}
|
||||
// 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",
|
||||
}));
|
||||
const result = await pauseOne(id);
|
||||
if (wasSuperseded(result)) return { id, result };
|
||||
const live = host.getTasks().find((candidate) => candidate.id === taskId);
|
||||
const userResumed = !pauseStillCurrent()
|
||||
@@ -297,26 +293,16 @@ 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));
|
||||
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;
|
||||
// Final directory paint: parent + unfinished children all go paused (do not
|
||||
// leave children stuck on transferring under a paused parent).
|
||||
host.setTasks(host.getTasks().map((candidate) => {
|
||||
if (candidate.id === taskId) {
|
||||
return {
|
||||
...candidate,
|
||||
status: pauseFailure ? "pausing" as const : "paused" as const,
|
||||
status: "paused" as const,
|
||||
speed: 0,
|
||||
checkpointBytes: candidate.transferredBytes,
|
||||
pauseUnavailableReason: pauseFailure,
|
||||
pauseUnavailableReason: undefined,
|
||||
phase: undefined,
|
||||
// Bridge epoch only — control-plane pauseEpoch must not poison ingest.
|
||||
...(bridgeEpoch !== undefined ? { lifecycleEpoch: bridgeEpoch } : null),
|
||||
@@ -325,25 +311,24 @@ 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)
|
||||
: childFailed ? undefined : bridgeEpoch;
|
||||
: bridgeEpoch;
|
||||
return {
|
||||
...candidate,
|
||||
status: childFailed ? "transferring" as const : "paused" as const,
|
||||
status: "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: childFailed ? (result.reason || "Could not pause transfer") : undefined,
|
||||
pauseUnavailableReason: undefined,
|
||||
...(childEpoch !== undefined ? { lifecycleEpoch: childEpoch } : null),
|
||||
};
|
||||
}));
|
||||
})().catch(() => { /* best-effort */ });
|
||||
return "pausing";
|
||||
return "paused";
|
||||
}
|
||||
|
||||
// Single-file: await soft-drain with supersede guards.
|
||||
|
||||
@@ -122,11 +122,8 @@ 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: () => new Promise((resolve) => {
|
||||
acknowledgePause = () => resolve({ success: true, checkpointBytes: 5 });
|
||||
}),
|
||||
pauseTransfer: async () => ({ success: true, checkpointBytes: 5 }),
|
||||
resumeTransfer: async (id) => {
|
||||
resumeCalls.push(id);
|
||||
return { success: true };
|
||||
@@ -154,9 +151,6 @@ 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,7 +1505,6 @@ 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"));
|
||||
@@ -2414,7 +2413,6 @@ 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.
|
||||
@@ -2623,7 +2621,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, "pausing");
|
||||
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "dir-race")?.status, "paused");
|
||||
|
||||
// User hits resume before soft-drain finishes — full store resume (bumps epoch
|
||||
// + releases latch tree), which is what the UI does.
|
||||
@@ -2692,33 +2690,21 @@ test("orphan directory pause stays latched even when some children hard-miss pau
|
||||
|
||||
await store.pause("dir");
|
||||
|
||||
// Folder pause stays pending until the child acknowledgements settle.
|
||||
// Folder pause is async: UI is paused immediately; soft-drain may still be running.
|
||||
const dir = store.getSnapshot().tasks.find((task) => task.id === "dir");
|
||||
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.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.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,
|
||||
"pausing",
|
||||
"hard miss keeps the folder latched without claiming a successful pause",
|
||||
"paused",
|
||||
"hard-miss soft-drain must not demote folder out of paused",
|
||||
);
|
||||
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,22 +353,7 @@ 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";
|
||||
// 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) {
|
||||
if (incomingPaused && incomingLifecycleEpoch >= existingLifecycleEpoch) {
|
||||
merged.status = incoming.status;
|
||||
merged.speed = 0;
|
||||
// Pin the visible bar while paused/latched. Soft-drain must not keep
|
||||
@@ -407,7 +392,6 @@ 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")
|
||||
) {
|
||||
@@ -1738,15 +1722,17 @@ 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 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)
|
||||
const pauseHeld = isTransferOrRootPauseLatched(task.parentTaskId ?? task.id, task.id)
|
||||
|| isTransferPauseLatched(task.id)
|
||||
|| task.status === "paused"
|
||||
|| task.status === "pausing"
|
||||
|| parent?.status === "paused"
|
||||
|| parent?.status === "pausing");
|
||||
|| (!!task.parentTaskId && (
|
||||
isTransferPauseLatched(task.parentTaskId)
|
||||
|| (() => {
|
||||
const parent = tasks.find((candidate) => candidate.id === task.parentTaskId);
|
||||
return 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") {
|
||||
@@ -2465,12 +2451,10 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
task.parentTaskId ?? task.id,
|
||||
task.id,
|
||||
) || isTransferPauseLatched(task.id);
|
||||
const rejectedChildPause = parentRow?.status === "pausing" && !!parentRow.pauseUnavailableReason
|
||||
&& task.status === "transferring" && !!task.pauseUnavailableReason;
|
||||
const uiPauseLatched = !rejectedChildPause && (task.status === "paused"
|
||||
const uiPauseLatched = 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" && !task.pauseUnavailableReason) {
|
||||
if (task.status === "pausing") {
|
||||
if (!pausingSnapshotRef.current) {
|
||||
pausingSnapshotRef.current = {
|
||||
task: { ...task },
|
||||
@@ -464,23 +464,20 @@ function TransferRow({
|
||||
&& !task.error;
|
||||
const sharedResuming = useSftpTransferResuming(task.id);
|
||||
const isResuming = sharedResuming || storeResuming;
|
||||
const pauseFailed = task.status === "pausing" && !!task.pauseUnavailableReason;
|
||||
const canPause = task.resumable !== false && (task.status === "transferring" || pauseFailed) && canControl && !isResuming;
|
||||
const canPause = task.resumable !== false && task.status === "transferring" && 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. A settled
|
||||
// partial failure is different: offer Retry Pause and explicit Resume.
|
||||
// makes the row twitch as buttons appear/disappear mid-drain.
|
||||
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" && !pauseFailed;
|
||||
const isPausing = task.status === "pausing";
|
||||
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);
|
||||
@@ -580,7 +577,7 @@ function TransferRow({
|
||||
<Pause size={13} />
|
||||
</TransferAction>
|
||||
)}
|
||||
{task.status === "pausing" && !pauseFailed && (
|
||||
{task.status === "pausing" && (
|
||||
<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,23 +206,6 @@ 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);
|
||||
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders, baseURL);
|
||||
const result = await bridge.aiFetch(url, "GET", headers, undefined, undefined, undefined, undefined, skipTLSVerify);
|
||||
if (!result.ok) {
|
||||
if (discoveryKeyRef.current !== requestKey) return;
|
||||
|
||||
@@ -139,8 +139,6 @@ 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);
|
||||
@@ -198,7 +196,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
? (fileCountDisplay
|
||||
? `${t('sftp.transferCenter.phase.scanning')} · ${fileCountDisplay}`
|
||||
: t('sftp.transferCenter.phase.scanning'))
|
||||
: isPausing
|
||||
: task.status === 'pausing'
|
||||
? pausingLabel
|
||||
: isDirParent
|
||||
? (fileCountDisplay
|
||||
@@ -229,9 +227,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
|
||||
const statusIcon = isResuming
|
||||
? <Loader2 size={12} className="animate-spin text-primary" />
|
||||
: pauseFailed
|
||||
? <Pause size={12} className="text-amber-500" />
|
||||
: isPausing
|
||||
: task.status === 'pausing'
|
||||
? <Loader2 size={12} className="animate-spin text-amber-500" />
|
||||
: task.status === 'transferring'
|
||||
? <Loader2 size={12} className="animate-spin text-primary" />
|
||||
@@ -294,7 +290,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
|
||||
&& (pauseFailed || task.status === 'transferring' || task.status === 'queued' || task.status === 'pending');
|
||||
&& (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');
|
||||
@@ -356,7 +352,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
</Button>
|
||||
</IconButtonWithTooltip>
|
||||
)}
|
||||
{(task.status === 'transferring' || pauseFailed) && task.resumable !== false && onPause && !isResuming && (
|
||||
{task.status === 'transferring' && task.resumable !== false && onPause && !isResuming && (
|
||||
<IconButtonWithTooltip label={pauseActionLabel}>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -371,7 +367,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
</Button>
|
||||
</IconButtonWithTooltip>
|
||||
)}
|
||||
{isPausing && (
|
||||
{task.status === 'pausing' && (
|
||||
<IconButtonWithTooltip label={pausingLabel}>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -401,7 +397,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
</Button>
|
||||
</IconButtonWithTooltip>
|
||||
)}
|
||||
{(task.status === 'paused' || task.status === 'interrupted' || (pauseFailed && task.resumable !== false)) && onResume && !isResuming && (
|
||||
{(task.status === 'paused' || task.status === 'interrupted') && onResume && !isResuming && (
|
||||
<IconButtonWithTooltip label={resumeActionLabel}>
|
||||
<Button
|
||||
type="button"
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
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,8 +5,7 @@ export function getGlobalTransferBatchEligibility(tasks: readonly TransferTask[]
|
||||
return {
|
||||
cancellableCount: listGloballyCancellableTransferIds(tasks).length,
|
||||
pausableCount: topLevel.filter((task) => (
|
||||
(["pending", "queued", "transferring"].includes(task.status)
|
||||
|| (task.status === "pausing" && !!task.pauseUnavailableReason))
|
||||
["pending", "queued", "transferring"].includes(task.status)
|
||||
&& task.resumable !== false
|
||||
&& !(task.ownerId === "dedicated-resume" && task.reconnectRequired)
|
||||
)).length,
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { normalizeAnthropicSdkBaseURL } from './anthropicCompatBaseUrl';
|
||||
import { buildModelDiscoveryHeaders } from './modelDiscoveryHeaders';
|
||||
import { createModelFromConfig } from './sdk/providers';
|
||||
|
||||
const origin = 'https://ark.cn-beijing.volces.com';
|
||||
const bases = ['/api/plan', '/api/plan/', '/api/plan/v1', '/api/plan/v1/'];
|
||||
|
||||
test('Agent Plan official Anthropic bases normalize and use Bearer discovery auth', () => {
|
||||
for (const suffix of bases) {
|
||||
const base = origin + suffix;
|
||||
assert.equal(normalizeAnthropicSdkBaseURL(base), origin + '/api/plan/v1');
|
||||
assert.deepEqual(buildModelDiscoveryHeaders('anthropic', 'fake-key', {}, base), {
|
||||
Authorization: 'Bearer fake-key', 'anthropic-version': '2023-06-01',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('Agent Plan special handling does not change other origins, paths or protocols', () => {
|
||||
for (const base of [
|
||||
'http://ark.cn-beijing.volces.com/api/plan', origin + ':444/api/plan',
|
||||
'https://ark.cn-beijing.volces.com.example/api/plan', 'https://proxy.example/api/plan',
|
||||
origin + '/api/coding', origin + '/api/plan/v3', origin + '/api/planner',
|
||||
origin + '/api/plan?route=other', origin + '/api/plan#other',
|
||||
'https://user@ark.cn-beijing.volces.com/api/plan',
|
||||
]) {
|
||||
assert.equal(normalizeAnthropicSdkBaseURL(base), base);
|
||||
assert.equal(buildModelDiscoveryHeaders('anthropic', 'fake-key', {}, base)['x-api-key'], 'fake-key');
|
||||
}
|
||||
assert.equal(buildModelDiscoveryHeaders('openai', 'fake-key', {}, origin + '/api/plan').Authorization, 'Bearer fake-key');
|
||||
assert.deepEqual(buildModelDiscoveryHeaders('anthropic', 'fake-key', { authorization: 'custom', 'X-Tenant': 'tenant' }, origin + '/api/plan'), {
|
||||
'anthropic-version': '2023-06-01', authorization: 'custom', 'X-Tenant': 'tenant',
|
||||
});
|
||||
});
|
||||
|
||||
test('Agent Plan SDK stream and nonstream use the placeholder and exact messages path', async t => {
|
||||
const old = Reflect.get(globalThis, 'window');
|
||||
t.after(() => Reflect.set(globalThis, 'window', old));
|
||||
const requests: {url: string; headers: Headers}[] = [];
|
||||
const capture = (url: string, headers: Record<string,string>) => requests.push({ url, headers: new Headers(headers) });
|
||||
Reflect.set(globalThis, 'window', { netcatty: {
|
||||
aiFetch: async (url: string, _method: string, headers: Record<string,string>) => {
|
||||
capture(url, headers); return { ok: false, status: 400, data: '{"error":{"message":"captured"}}' };
|
||||
},
|
||||
aiChatStream: async (_id: string, url: string, headers: Record<string,string>) => {
|
||||
capture(url, headers); return { ok: false, error: 'captured' };
|
||||
},
|
||||
onAiStreamData: () => () => {}, onAiStreamEnd: () => () => {}, onAiStreamError: () => () => {},
|
||||
}});
|
||||
for (const suffix of bases) {
|
||||
for (const streaming of [false, true]) {
|
||||
const model = createModelFromConfig({id:'p',providerId:'custom',name:'Test',enabled:true,style:'anthropic',apiKey:'not-a-real-secret',baseURL:origin+suffix,defaultModel:'test-model',customHeaders:{'X-Tenant':'tenant'}});
|
||||
const params = {prompt:[{role:'user' as const,content:[{type:'text' as const,text:'hello'}]}]};
|
||||
if (streaming) {
|
||||
try { const result = await model.doStream(params); await result.stream.pipeTo(new WritableStream()); } catch { /* deliberately rejected at IPC boundary */ }
|
||||
} else await assert.rejects(Promise.resolve(model.doGenerate(params)));
|
||||
const request = requests.at(-1)!;
|
||||
assert.equal(request.url, origin + '/api/plan/v1/messages');
|
||||
assert.equal(request.headers.get('authorization'), 'Bearer __IPC_SECURED__');
|
||||
assert.equal(request.headers.get('x-api-key'), null);
|
||||
assert.equal(request.headers.get('x-tenant'), 'tenant');
|
||||
assert.ok(!JSON.stringify([...request.headers]).includes('not-a-real-secret'));
|
||||
}
|
||||
}
|
||||
assert.equal(requests.length, 8);
|
||||
});
|
||||
|
||||
test('Agent Plan Detect sends Bearer on the same origin without treating missing model listing as valid auth', async () => {
|
||||
const { probeProviderConnection } = await import('./providerConnectionProbe');
|
||||
const requests: {url: string; headers?: Record<string,string>}[] = [];
|
||||
for (const suffix of bases) {
|
||||
const result = await probeProviderConnection({
|
||||
baseURL: origin + suffix, apiKey: 'fake-key', providerId: 'custom', style: 'anthropic',
|
||||
customHeaders: { 'X-Tenant': 'tenant' },
|
||||
bridge: { aiFetch: async (url, _method, headers) => {
|
||||
requests.push({url, headers});
|
||||
return {ok:false,status:404,data:'not found'};
|
||||
} },
|
||||
});
|
||||
assert.equal(result.ok, true, 'probe ran, not an assertion that authentication succeeded');
|
||||
if (result.ok) {
|
||||
assert.equal(result.classification.statusCode, 404);
|
||||
assert.equal(result.classification.health, 'error');
|
||||
}
|
||||
assert.equal(requests.at(-1)?.url, origin + '/api/plan/v1/models');
|
||||
assert.equal(requests.at(-1)?.headers?.Authorization, 'Bearer fake-key');
|
||||
assert.equal(requests.at(-1)?.headers?.['x-api-key'], undefined);
|
||||
assert.equal(requests.at(-1)?.headers?.['X-Tenant'], 'tenant');
|
||||
}
|
||||
});
|
||||
@@ -9,6 +9,22 @@
|
||||
* working proxy bases keep working.
|
||||
*/
|
||||
|
||||
/** Official Agent Plan accepts Claude Code's /api/plan base and Bearer auth.
|
||||
* Keep this exact-origin/path exception separate from arbitrary custom proxies.
|
||||
*/
|
||||
export function isAnthropicAgentPlanEndpoint(baseURL: string | undefined): boolean {
|
||||
if (!baseURL) return false;
|
||||
try {
|
||||
const url = new URL(baseURL.trim());
|
||||
return url.protocol === "https:"
|
||||
&& url.hostname === "ark.cn-beijing.volces.com"
|
||||
&& !url.port && !url.username && !url.password && !url.search && !url.hash
|
||||
&& /^\/api\/plan(?:\/v1)?\/?$/.test(url.pathname);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Strip trailing slashes; empty input stays empty. */
|
||||
export function stripTrailingSlashes(url: string): string {
|
||||
return url.trim().replace(/\/+$/, "");
|
||||
@@ -46,6 +62,7 @@ export function normalizeAnthropicSdkBaseURL(baseURL: string): string {
|
||||
const trimmed = stripTrailingSlashes(baseURL);
|
||||
if (!trimmed) return trimmed;
|
||||
if (anthropicBaseIncludesV1(trimmed)) return trimmed;
|
||||
if (isAnthropicAgentPlanEndpoint(trimmed)) return `${trimmed}/v1`;
|
||||
if (!isBareOriginBaseURL(trimmed)) return trimmed;
|
||||
return `${trimmed}/v1`;
|
||||
}
|
||||
@@ -142,7 +142,7 @@ export async function fetchProviderModelCatalog(
|
||||
await bridge.aiAllowlistAddHost(baseURL);
|
||||
}
|
||||
const url = buildProviderProbeUrl(baseURL, endpoint);
|
||||
const headers = buildModelDiscoveryHeaders(style, apiKey, await decryptProviderHeaders(provider.customHeaders));
|
||||
const headers = buildModelDiscoveryHeaders(style, apiKey, await decryptProviderHeaders(provider.customHeaders), baseURL);
|
||||
const result = await bridge.aiFetch(
|
||||
url,
|
||||
'GET',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isAnthropicAgentPlanEndpoint } from "./anthropicCompatBaseUrl";
|
||||
import type { ProviderStyle } from "./types";
|
||||
|
||||
/**
|
||||
@@ -41,12 +42,15 @@ export function resolveModelsDiscoveryEndpoint(
|
||||
function buildDefaultModelDiscoveryHeaders(
|
||||
style: ProviderStyle,
|
||||
apiKey: string | undefined,
|
||||
baseURL?: string,
|
||||
): Record<string, string> {
|
||||
if (!apiKey) return {};
|
||||
switch (style) {
|
||||
case "anthropic":
|
||||
return {
|
||||
"x-api-key": apiKey,
|
||||
...(isAnthropicAgentPlanEndpoint(baseURL)
|
||||
? { Authorization: `Bearer ${apiKey}` }
|
||||
: { "x-api-key": apiKey }),
|
||||
"anthropic-version": "2023-06-01",
|
||||
};
|
||||
case "google":
|
||||
@@ -61,8 +65,9 @@ export function buildModelDiscoveryHeaders(
|
||||
style: ProviderStyle,
|
||||
apiKey: string | undefined,
|
||||
customHeaders: Record<string, string> = {},
|
||||
baseURL?: string,
|
||||
): Record<string, string> {
|
||||
const headers = buildDefaultModelDiscoveryHeaders(style, apiKey);
|
||||
const headers = buildDefaultModelDiscoveryHeaders(style, apiKey, baseURL);
|
||||
const overridden = new Set(Object.keys(customHeaders).map((name) => name.toLowerCase()));
|
||||
return Object.fromEntries([
|
||||
...Object.entries(headers).filter(([name]) => !overridden.has(name.toLowerCase())),
|
||||
|
||||
@@ -182,7 +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);
|
||||
const headers = buildModelDiscoveryHeaders(input.style, input.apiKey, input.customHeaders, baseURL);
|
||||
const result = await bridge.aiFetch(
|
||||
url,
|
||||
"GET",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createOpenAI } from '@ai-sdk/openai';
|
||||
import { isAnthropicAgentPlanEndpoint } from '../anthropicCompatBaseUrl';
|
||||
import { createAnthropic } from '@ai-sdk/anthropic';
|
||||
import { createGoogle } from '@ai-sdk/google';
|
||||
import { wrapLanguageModel, type LanguageModelMiddleware } from 'ai';
|
||||
@@ -776,7 +777,7 @@ function createProviderModel(
|
||||
|
||||
case 'anthropic':
|
||||
return createAnthropic({
|
||||
apiKey,
|
||||
...(isAnthropicAgentPlanEndpoint(baseURL) ? { authToken: apiKey } : { apiKey }),
|
||||
baseURL,
|
||||
fetch: customFetch,
|
||||
headers: sdkHeaders,
|
||||
|
||||
Reference in new issue
Block a user