", rowOffset) + 1);
}
function deviceRowActionButton(markup, deviceId) {
const deviceOffset = markup.indexOf(`
${deviceId}`);
assert.notEqual(deviceOffset, -1, `${deviceId} must be rendered`);
const buttonOffset = markup.indexOf("
".length);
}
function renderProvisioning(props) {
return renderToStaticMarkup(createElement(K1ProvisioningPipeline, props));
}
function captureProvisioningTree(props) {
let capturedTree = null;
function CaptureHarness() {
capturedTree = K1ProvisioningPipeline(props);
return capturedTree;
}
renderToStaticMarkup(createElement(CaptureHarness));
assert.ok(capturedTree);
return capturedTree;
}
function captureProvisioningTreeAfterSearch(
props,
{ completedDiscoveryGeneration } = {},
) {
let capturedTree = null;
function SearchCompletedCaptureHarness() {
const internals =
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
const dispatcher = internals?.H;
assert.equal(typeof dispatcher?.useState, "function");
const originalUseState = dispatcher.useState;
dispatcher.useState = (initialState) => {
if (initialState === emptySearchPresentation) {
const state = props.controller.state;
return [{
sequence: 1,
snapshotRuntimeId: state.snapshot_runtime_id ?? null,
connectionMode: props.desiredMode,
desiredModeRevision: state.desired_connection_mode_revision ?? null,
active: false,
completedDiscoveryGeneration: completedDiscoveryGeneration
?? state.ble_discovery_generation
?? null,
}, () => undefined];
}
return originalUseState(initialState);
};
try {
capturedTree = K1ProvisioningPipeline(props);
return capturedTree;
} finally {
dispatcher.useState = originalUseState;
}
}
renderToStaticMarkup(createElement(SearchCompletedCaptureHarness));
assert.ok(capturedTree);
return capturedTree;
}
function elementByProp(node, propName, expectedValue) {
if (Array.isArray(node)) {
for (const child of node) {
const found = elementByProp(child, propName, expectedValue);
if (found) return found;
}
return null;
}
if (!React.isValidElement(node)) return null;
if (node.props[propName] === expectedValue) return node;
return elementByProp(node.props.children, propName, expectedValue);
}
function createStatefulProvisioningHarness(initialProps, Component = K1ProvisioningPipeline) {
const hookSlots = [];
let currentProps = initialProps;
let capturedTree = null;
let pendingEffects = [];
const dependenciesMatch = (left, right) => Boolean(
left
&& right
&& left.length === right.length
&& left.every((value, index) => Object.is(value, right[index])),
);
const render = (nextProps = currentProps) => {
currentProps = nextProps;
pendingEffects = [];
function StatefulCaptureHarness() {
const internals =
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
const dispatcher = internals?.H;
assert.equal(typeof dispatcher?.useState, "function");
const originals = {
useState: dispatcher.useState,
useRef: dispatcher.useRef,
useMemo: dispatcher.useMemo,
useCallback: dispatcher.useCallback,
useEffect: dispatcher.useEffect,
};
let hookIndex = 0;
dispatcher.useState = (initialState) => {
const index = hookIndex;
hookIndex += 1;
if (!hookSlots[index]) {
hookSlots[index] = {
kind: "state",
initializer: initialState,
value: typeof initialState === "function"
? initialState()
: initialState,
};
}
const slot = hookSlots[index];
assert.equal(slot.kind, "state");
const setValue = (nextValue) => {
slot.value = typeof nextValue === "function"
? nextValue(slot.value)
: nextValue;
};
return [slot.value, setValue];
};
dispatcher.useRef = (initialValue) => {
const index = hookIndex;
hookIndex += 1;
if (!hookSlots[index]) {
hookSlots[index] = {
kind: "ref",
value: { current: initialValue },
};
}
const slot = hookSlots[index];
assert.equal(slot.kind, "ref");
return slot.value;
};
dispatcher.useMemo = (factory, dependencies) => {
const index = hookIndex;
hookIndex += 1;
const previous = hookSlots[index];
if (
!previous
|| previous.kind !== "memo"
|| !dependenciesMatch(previous.dependencies, dependencies)
) {
hookSlots[index] = {
kind: "memo",
dependencies,
value: factory(),
};
}
return hookSlots[index].value;
};
dispatcher.useCallback = (callback, dependencies) => {
const index = hookIndex;
hookIndex += 1;
const previous = hookSlots[index];
if (
!previous
|| previous.kind !== "callback"
|| !dependenciesMatch(previous.dependencies, dependencies)
) {
hookSlots[index] = {
kind: "callback",
dependencies,
value: callback,
};
}
return hookSlots[index].value;
};
dispatcher.useEffect = (effect, dependencies) => {
const index = hookIndex;
hookIndex += 1;
const previous = hookSlots[index];
const changed = !previous
|| previous.kind !== "effect"
|| !dependenciesMatch(previous.dependencies, dependencies);
hookSlots[index] = {
kind: "effect",
dependencies,
cleanup: previous?.kind === "effect" ? previous.cleanup : undefined,
};
if (changed) pendingEffects.push({ index, effect });
};
try {
capturedTree = Component(currentProps);
} finally {
dispatcher.useState = originals.useState;
dispatcher.useRef = originals.useRef;
dispatcher.useMemo = originals.useMemo;
dispatcher.useCallback = originals.useCallback;
dispatcher.useEffect = originals.useEffect;
}
return null;
}
renderToStaticMarkup(createElement(StatefulCaptureHarness));
assert.ok(capturedTree);
return capturedTree;
};
const flushEffects = () => {
const effects = pendingEffects;
pendingEffects = [];
for (const { index, effect } of effects) {
const slot = hookSlots[index];
slot.cleanup?.();
const cleanup = effect();
slot.cleanup = typeof cleanup === "function" ? cleanup : undefined;
}
};
const stateValue = (initializer) => hookSlots.find(
(slot) => slot?.kind === "state" && slot.initializer === initializer,
)?.value;
const dispose = () => {
for (const slot of hookSlots) {
if (slot?.kind === "effect") slot.cleanup?.();
}
};
return { dispose, flushEffects, render, stateValue };
}
function reactNodeText(node) {
if (typeof node === "string" || typeof node === "number") return String(node);
if (Array.isArray(node)) return node.map(reactNodeText).join("");
if (!React.isValidElement(node)) return "";
return reactNodeText(node.props.children);
}
function actionByLabel(node, label) {
if (Array.isArray(node)) {
for (const child of node) {
const found = actionByLabel(child, label);
if (found) return found;
}
return null;
}
if (!React.isValidElement(node)) return null;
if (
typeof node.props.onClick === "function"
&& reactNodeText(node.props.children).includes(label)
) return node;
return actionByLabel(node.props.children, label);
}
function renderProvisioningWithAttempt(props, presentation, afterSearch = false) {
function AttemptHarness() {
const internals =
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
const dispatcher = internals?.H;
assert.equal(typeof dispatcher?.useState, "function");
const originalUseState = dispatcher.useState;
dispatcher.useState = (initialState) => {
if (afterSearch && initialState === emptySearchPresentation) {
const state = props.controller.state;
return [{ sequence: 1, snapshotRuntimeId: state.snapshot_runtime_id,
connectionMode: props.desiredMode, desiredModeRevision: state.desired_connection_mode_revision,
active: false, completedDiscoveryGeneration: state.ble_discovery_generation }, () => undefined];
}
if (initialState === emptyProvisioningAttemptPresentation) {
return [presentation, () => undefined];
}
return originalUseState(initialState);
};
try {
return K1ProvisioningPipeline(props);
} finally {
dispatcher.useState = originalUseState;
}
}
return renderToStaticMarkup(createElement(AttemptHarness));
}
function captureProvisioningTreeWithAttempt(props, presentation) {
let capturedTree = null;
function AttemptCaptureHarness() {
const internals =
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
const dispatcher = internals?.H;
assert.equal(typeof dispatcher?.useState, "function");
const originalUseState = dispatcher.useState;
dispatcher.useState = (initialState) => {
if (initialState === emptyProvisioningAttemptPresentation) {
return [presentation, () => undefined];
}
return originalUseState(initialState);
};
try {
capturedTree = K1ProvisioningPipeline(props);
return capturedTree;
} finally {
dispatcher.useState = originalUseState;
}
}
renderToStaticMarkup(createElement(AttemptCaptureHarness));
assert.ok(capturedTree);
return capturedTree;
}
function renderProvisioningAfterSearch(
props,
{ completedDiscoveryGeneration } = {},
) {
function SearchCompletedHarness() {
const internals =
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
const dispatcher = internals?.H;
assert.equal(typeof dispatcher?.useState, "function");
const originalUseState = dispatcher.useState;
dispatcher.useState = (initialState) => {
if (initialState === emptySearchPresentation) {
const state = props.controller.state;
return [{
sequence: 1,
snapshotRuntimeId: state.snapshot_runtime_id ?? null,
connectionMode: props.desiredMode,
desiredModeRevision: state.desired_connection_mode_revision ?? null,
active: false,
completedDiscoveryGeneration: completedDiscoveryGeneration
?? state.ble_discovery_generation
?? null,
}, () => undefined];
}
return originalUseState(initialState);
};
try {
return K1ProvisioningPipeline(props);
} finally {
dispatcher.useState = originalUseState;
}
}
return renderToStaticMarkup(createElement(SearchCompletedHarness));
}
function renderProvisioningWithCurrentPendingAction(
props,
{ publicSearch = true } = {},
) {
function CurrentPendingActionHarness() {
const state = props.controller.state;
const fence = {
snapshotRuntimeId: state.snapshot_runtime_id,
connectionMode: props.desiredMode,
desiredModeRevision: state.desired_connection_mode_revision,
reconfigurationRevision: state.connection_reconfiguration?.revision ?? 0,
reconfigurationIntentId: state.connection_reconfiguration?.intent_id ?? null,
activeBindingKey: state.connection_lifecycle?.active_binding_key ?? null,
discoveryGeneration: state.ble_discovery_generation,
clickToken: 1,
};
return createElement(
RuntimeActionFenceTestContext.Provider,
{ value: fence },
publicSearch
? createElement(SearchCompletedPendingHarness, { props })
: createElement(K1ProvisioningPipeline, props),
);
}
function SearchCompletedPendingHarness({ props: childProps }) {
const internals =
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
const dispatcher = internals?.H;
assert.equal(typeof dispatcher?.useState, "function");
const originalUseState = dispatcher.useState;
dispatcher.useState = (initialState) => {
if (initialState === emptySearchPresentation) {
const state = childProps.controller.state;
return [{
sequence: 1,
snapshotRuntimeId: state.snapshot_runtime_id ?? null,
connectionMode: childProps.desiredMode,
desiredModeRevision: state.desired_connection_mode_revision ?? null,
active: true,
completedDiscoveryGeneration: null,
}, () => undefined];
}
return originalUseState(initialState);
};
try {
return K1ProvisioningPipeline(childProps);
} finally {
dispatcher.useState = originalUseState;
}
}
return renderToStaticMarkup(createElement(CurrentPendingActionHarness));
}
function renderProvisioningWithRetainedDraft(
props,
{ device, draft, ssid, password },
) {
function RetainedDraftHarness() {
const internals =
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
const dispatcher = internals?.H;
assert.equal(typeof dispatcher?.useState, "function");
const originalUseState = dispatcher.useState;
let emptyStringStateIndex = 0;
let nullStateIndex = 0;
dispatcher.useState = (initialState) => {
if (initialState === "") {
emptyStringStateIndex += 1;
const seededValue = emptyStringStateIndex === 1
? device.device_id
: emptyStringStateIndex === 2
? ssid
: emptyStringStateIndex === 3
? password
: initialState;
return [seededValue, () => undefined];
}
if (initialState === null) {
nullStateIndex += 1;
if (nullStateIndex === 1) return [device, () => undefined];
if (nullStateIndex === 8) return [draft, () => undefined];
}
return originalUseState(initialState);
};
try {
return K1ProvisioningPipeline(props);
} finally {
dispatcher.useState = originalUseState;
}
}
return renderToStaticMarkup(createElement(RetainedDraftHarness));
}
test("K1 provisioning password authority is scoped to one exact operator draft", () => {
const draft = {
snapshotRuntimeId: "runtime-a",
deviceId: "ble-k1-001",
connectionMode: "bridge",
desiredModeRevision: 7,
discoveryGeneration: 13,
reconfigurationRevision: 5,
reconfigurationIntentId: "reconfigure-001",
activeBindingKey: null,
requiredTransportRef: "ble-k1-001",
requiredConnectionMode: "bridge",
};
const current = {
snapshotRuntimeId: "runtime-a",
deviceId: "ble-k1-001",
connectionMode: "bridge",
desiredModeRevision: 7,
discoveryGeneration: 13,
reconfigurationRevision: 5,
reconfigurationIntentId: "reconfigure-001",
activeBindingKey: null,
requiredTransportRef: "ble-k1-001",
requiredConnectionMode: "bridge",
};
assert.equal(explicitProvisioningDraftMatches(draft, current), true);
for (const drifted of [
{ ...current, snapshotRuntimeId: "runtime-b" },
{ ...current, deviceId: "another-k1" },
{ ...current, connectionMode: "direct-connect" },
{ ...current, desiredModeRevision: 8 },
{ ...current, discoveryGeneration: 14 },
{ ...current, reconfigurationRevision: 6 },
{ ...current, reconfigurationIntentId: "reconfigure-002" },
{ ...current, activeBindingKey: "binding-new" },
{ ...current, requiredTransportRef: "ble-k1-002" },
{ ...current, requiredConnectionMode: "direct-connect" },
{ ...current, deviceId: null },
]) {
assert.equal(explicitProvisioningDraftMatches(draft, drifted), false);
}
});
test("K1 provisioning local credential fence changes with backend runtime authority", () => {
const fence = {
snapshotRuntimeId: "runtime-a",
reconfigurationRevision: 5,
reconfigurationIntentId: "reconfigure-001",
activeBindingKey: null,
requiredTransportRef: "ble-k1-001",
requiredConnectionMode: "bridge",
};
assert.notEqual(
localProvisioningDraftFenceKey(fence),
localProvisioningDraftFenceKey({
...fence,
snapshotRuntimeId: "runtime-b",
}),
);
});
test("K1 click-owned action requests disappear across runtime and click interleavings", () => {
const authorityA = {
snapshotRuntimeId: "runtime-a",
connectionMode: "bridge",
desiredModeRevision: 7,
reconfigurationRevision: 10,
reconfigurationIntentId: "reconfigure-a",
activeBindingKey: "binding-a",
discoveryGeneration: 5,
};
const firstClick = {
...authorityA,
clickToken: 17,
};
const awaitingScan = {
...firstClick,
deviceId: "ble-k1-001",
previousDiscoveryGeneration: 5,
expectedDiscoveryGeneration: null,
scanTransportRefs: [],
stage: "awaiting-scan",
};
let latestAuthority = authorityA;
const latestAuthorityMatches = (fence) =>
connectionActionAuthorityMatches(fence, latestAuthority);
assert.equal(
runtimeActionFenceMatches(
firstClick,
"runtime-a",
firstClick,
latestAuthorityMatches,
),
true,
);
assert.equal(
currentRuntimeActionRequest(
awaitingScan,
"runtime-a",
firstClick,
latestAuthorityMatches,
),
awaitingScan,
);
// Same-runtime authority drift must invalidate the old click before the new
// React render commits. A late Quick candidate cannot re-arm or auto-submit.
latestAuthority = { ...authorityA, discoveryGeneration: 6 };
assert.equal(
runtimeActionFenceMatches(
firstClick,
"runtime-a",
firstClick,
latestAuthorityMatches,
),
false,
);
assert.equal(
currentRuntimeActionRequest(
awaitingScan,
"runtime-a",
firstClick,
latestAuthorityMatches,
),
null,
);
// Simulate acceptState(runtime-b) updating latestState.current before React
// commits the runtime-b render.
latestAuthority = { ...authorityA, snapshotRuntimeId: "runtime-b" };
const secondClick = {
...latestAuthority,
clickToken: 18,
};
assert.equal(
runtimeActionFenceMatches(
firstClick,
"runtime-b",
secondClick,
latestAuthorityMatches,
),
false,
);
assert.equal(
runtimeActionFenceMatches(
secondClick,
"runtime-b",
secondClick,
latestAuthorityMatches,
),
true,
);
});
test("K1 reconfiguration continuation requires exact correlated +1 revisions", () => {
const fence = {
snapshotRuntimeId: "runtime-a",
connectionMode: "bridge",
desiredModeRevision: 7,
reconfigurationRevision: 10,
reconfigurationIntentId: null,
activeBindingKey: "binding-a",
discoveryGeneration: 5,
};
const preparedState = {
snapshot_runtime_id: "runtime-a",
desired_connection_mode: "bridge",
desired_connection_mode_revision: 7,
ble_discovery_generation: 6,
connection_reconfiguration: connectionReconfiguration({
intent: "select-device",
status: "awaiting-fresh-scan",
revision: 11,
intentId: "reconfigure-b",
discoveryGeneration: 6,
}),
connection_lifecycle: {
active_binding_key: null,
active_binding: null,
},
};
const preparedAuthority = {
...fence,
reconfigurationRevision: 11,
reconfigurationIntentId: "reconfigure-b",
activeBindingKey: null,
discoveryGeneration: 6,
};
assert.deepEqual(
reconfigurationContinuationAuthority(
fence,
preparedState,
"select-device",
preparedAuthority,
),
preparedAuthority,
);
for (const drifted of [
{ ...preparedAuthority, discoveryGeneration: 7 },
{ ...preparedAuthority, reconfigurationRevision: 12 },
{ ...preparedAuthority, desiredModeRevision: 8 },
{ ...preparedAuthority, activeBindingKey: "foreign-binding" },
]) {
assert.equal(
reconfigurationContinuationAuthority(
fence,
preparedState,
"select-device",
drifted,
),
null,
);
}
assert.equal(
reconfigurationContinuationAuthority(
fence,
preparedState,
"change-network",
preparedAuthority,
),
null,
);
const contaminatedPreparedState = {
...preparedState,
connection_lifecycle: {
active_binding_key: "binding-foreign",
active_binding: {
binding_key: "binding-foreign",
transport_ref: "ble-k1-foreign",
connection_mode: "bridge",
},
},
};
assert.equal(
reconfigurationContinuationAuthority(
fence,
contaminatedPreparedState,
"select-device",
{ ...preparedAuthority, activeBindingKey: "binding-foreign" },
),
null,
);
const cancelFence = preparedAuthority;
const cancelledState = {
...preparedState,
ble_discovery_generation: 7,
connection_reconfiguration: connectionReconfiguration({ revision: 12 }),
};
const cancelledAuthority = {
...cancelFence,
reconfigurationRevision: 12,
reconfigurationIntentId: null,
discoveryGeneration: 7,
};
assert.deepEqual(
reconfigurationContinuationAuthority(
cancelFence,
cancelledState,
"cancel",
cancelledAuthority,
),
cancelledAuthority,
);
});
test("separately explicit Verify rejects a foreign same-runtime binding", () => {
const exact = {
selected_device_id: "ble-k1-001",
connection_mode: "bridge",
connection_lifecycle: {
active_binding_key: "binding-a",
active_binding: {
binding_key: "binding-a",
transport_ref: "ble-k1-001",
connection_mode: "bridge",
},
},
};
assert.equal(
observedConnectionAuthorityAllowsTarget(
exact,
"ble-k1-001",
"bridge",
),
true,
);
assert.equal(
observedConnectionAuthorityAllowsTarget(
{
...exact,
selected_device_id: "ble-k1-foreign",
connection_lifecycle: {
active_binding_key: "binding-b",
active_binding: {
binding_key: "binding-b",
transport_ref: "ble-k1-foreign",
connection_mode: "bridge",
},
},
},
"ble-k1-001",
"bridge",
{ allowUnbound: true },
),
false,
);
assert.equal(
observedConnectionAuthorityAllowsTarget(
{
selected_device_id: null,
connection_mode: null,
connection_lifecycle: {
active_binding_key: null,
active_binding: null,
},
},
"ble-k1-001",
"bridge",
{ allowUnbound: true },
),
true,
);
});
test("K1 Connect continuation accepts only unchanged or exactly consumed authority", () => {
const ordinaryFence = {
snapshotRuntimeId: "runtime-a",
connectionMode: "bridge",
desiredModeRevision: 7,
reconfigurationRevision: 10,
reconfigurationIntentId: null,
activeBindingKey: null,
discoveryGeneration: 5,
};
const connectedState = ({
deviceId = "ble-k1-001",
reconfigurationRevision = 10,
discoveryGeneration = 5,
} = {}) => ({
snapshot_runtime_id: "runtime-a",
desired_connection_mode: "bridge",
desired_connection_mode_revision: 7,
ble_discovery_generation: discoveryGeneration,
selected_device_id: deviceId,
connection_mode: "bridge",
connection_reconfiguration: connectionReconfiguration({
revision: reconfigurationRevision,
}),
connection_lifecycle: {
active_binding_key: `binding-${deviceId}`,
active_binding: {
binding_key: `binding-${deviceId}`,
transport_ref: deviceId,
connection_mode: "bridge",
},
},
});
const ordinaryState = connectedState();
const ordinaryCurrent = {
...ordinaryFence,
activeBindingKey: "binding-ble-k1-001",
};
assert.deepEqual(
connectContinuationAuthority(
ordinaryFence,
ordinaryState,
ordinaryCurrent,
"ble-k1-001",
"bridge",
),
ordinaryCurrent,
);
const reconfigurationFence = {
...ordinaryFence,
reconfigurationIntentId: "reconfigure-a",
};
const consumedState = connectedState({
reconfigurationRevision: 11,
discoveryGeneration: 6,
});
const consumedCurrent = {
...reconfigurationFence,
reconfigurationRevision: 11,
reconfigurationIntentId: null,
activeBindingKey: "binding-ble-k1-001",
discoveryGeneration: 6,
};
assert.deepEqual(
connectContinuationAuthority(
reconfigurationFence,
consumedState,
consumedCurrent,
"ble-k1-001",
"bridge",
),
consumedCurrent,
);
const skippedState = connectedState({
reconfigurationRevision: 12,
discoveryGeneration: 7,
});
const skippedCurrent = {
...consumedCurrent,
reconfigurationRevision: 12,
discoveryGeneration: 7,
};
assert.equal(
connectContinuationAuthority(
reconfigurationFence,
skippedState,
skippedCurrent,
"ble-k1-001",
"bridge",
),
null,
);
const foreignState = connectedState({ deviceId: "ble-k1-foreign" });
assert.equal(
connectContinuationAuthority(
ordinaryFence,
foreignState,
{
...ordinaryCurrent,
activeBindingKey: "binding-ble-k1-foreign",
},
"ble-k1-001",
"bridge",
),
null,
);
});
test("K1 runtime replacement retires A and isolates a new B action from late settlement", () => {
const arbiter = new SnapshotRuntimeActionArbiter();
const actionA = arbiter.begin(4);
assert.ok(actionA);
let pendingAction = "verify";
let acceptedState = "runtime-a";
let surfacedError = null;
assert.equal(
arbiter.retireForSnapshotChange("runtime-a", "runtime-b"),
true,
);
pendingAction = null;
acceptedState = "runtime-b";
assert.equal(pendingAction, null, "runtime-b controls are enabled without A loader");
const actionB = arbiter.begin(4);
assert.ok(actionB, "runtime-b click is admitted before action A settles");
pendingAction = "scan";
const acceptLateResult = (token, nextState) => {
if (!arbiter.isCurrent(token)) return false;
acceptedState = nextState;
return true;
};
const surfaceLateFailure = (token, message) => {
if (!arbiter.isCurrent(token)) return false;
surfacedError = message;
return true;
};
const finish = (token) => {
if (!arbiter.settle(token)) return false;
pendingAction = null;
return true;
};
assert.equal(acceptLateResult(actionA, "runtime-a-late"), false);
assert.equal(surfaceLateFailure(actionA, "late A error"), false);
assert.equal(finish(actionA), false);
assert.equal(acceptedState, "runtime-b");
assert.equal(surfacedError, null);
assert.equal(pendingAction, "scan", "late A finally cannot clear B pending state");
assert.equal(finish(actionB), true);
assert.equal(pendingAction, null);
});
test("successful action response may be superseded only by the same runtime revision", () => {
const response = {
snapshot_runtime_id: "runtime-a",
snapshot_revision: 41,
};
assert.equal(runtimeActionResponseAlreadyAccepted(response, {
snapshot_runtime_id: "runtime-a",
snapshot_revision: 42,
}), true);
assert.equal(runtimeActionResponseAlreadyAccepted(response, {
snapshot_runtime_id: "runtime-a",
snapshot_revision: 40,
}), false);
assert.equal(runtimeActionResponseAlreadyAccepted(response, {
snapshot_runtime_id: "runtime-b",
snapshot_revision: 99,
}), false);
assert.equal(runtimeActionResponseAlreadyAccepted(response, null), false);
});
test("explicit scenario reset B supersedes pending callback A in one runtime", () => {
const arbiter = new SnapshotRuntimeActionArbiter();
const actionA = arbiter.begin(12);
assert.ok(actionA);
const actionB = arbiter.begin(12, true);
assert.ok(actionB, "reset B is admitted while A is still pending");
assert.equal(arbiter.isCurrent(actionA), false);
assert.equal(arbiter.settle(actionA), false, "late A cannot clear B loader");
assert.equal(arbiter.isCurrent(actionB), true);
assert.equal(arbiter.settle(actionB), true);
});
test("acquisition and spatial STOP surfaces share one runtime action slot", () => {
const arbiter = new SnapshotRuntimeActionArbiter();
let physicalStopCallCount = 0;
const clickPhysicalStop = () => {
const token = arbiter.begin(7);
if (!token) return null;
physicalStopCallCount += 1;
return token;
};
const acquisitionSurface = clickPhysicalStop();
const spatialSurface = clickPhysicalStop();
assert.ok(acquisitionSurface);
assert.equal(spatialSurface, null);
assert.equal(physicalStopCallCount, 1);
assert.equal(arbiter.settle(acquisitionSurface), true);
});
test("change-network exact lookup never substitutes a neighboring UUID", () => {
const reconfiguration = connectionReconfiguration({
intent: "change-network",
status: "fresh-scan-completed",
revision: 8,
requiredTransportRef: "ble-k1-original",
requiredConnectionMode: "bridge",
discoveryGeneration: 11,
requiredTransportObserved: true,
});
const devices = [
{ device_id: "ble-k1-foreign", name: "Nearby", connectable: true },
{ device_id: "ble-k1-original", name: "Original", connectable: true },
];
assert.equal(
exactChangeNetworkCandidate(reconfiguration, devices, 11)?.device_id,
"ble-k1-original",
);
assert.equal(exactChangeNetworkCandidate(reconfiguration, devices, 12), null);
assert.equal(
exactChangeNetworkCandidate(
{ ...reconfiguration, required_transport_observed: false },
devices,
11,
),
null,
);
});
test("cold connection workflow exposes the mode selector and explicit Scan immediately", () => {
const state = durableTopologyState();
state.semantic_topology_store = {
status: "empty",
configured_offline_evidence: false,
live_connection_authority: false,
reason_code: null,
record: null,
};
state.devices = [{
device_id: "ble-k1-001",
name: "XGR-A46BE7",
rssi: -45,
connectable: true,
likely_k1: true,
}];
state.connection_policy = {
schema_version: "missioncore.xgrids-k1-connection-policy/v1",
facts: { retained_context_is_presence: false },
allowed_actions: ["scan-ble", "provision-fresh-device"],
actions: {
"scan-ble": {
allowed: true,
reason_codes: [],
target_source: "none",
required_transport_ref: null,
required_connection_mode: null,
requires_live_gatt_validation: false,
automatic_retry: false,
},
"provision-fresh-device": {
allowed: true,
reason_codes: [],
target_source: "fresh-scan",
required_transport_ref: null,
required_connection_mode: null,
requires_live_gatt_validation: true,
automatic_retry: false,
},
"prepare-select-device": {
allowed: false,
reason_codes: ["acquisition-active"],
target_source: "local-prestart-handoff",
required_transport_ref: null,
required_connection_mode: null,
requires_live_gatt_validation: false,
device_write_performed: false,
automatic_retry: false,
},
"prepare-change-network": {
allowed: false,
reason_codes: ["acquisition-active"],
target_source: "local-prestart-handoff",
required_transport_ref: "ble-k1-001",
required_connection_mode: "bridge",
requires_live_gatt_validation: false,
device_write_performed: false,
automatic_retry: false,
},
},
};
const markup = renderToStaticMarkup(createElement(K1ProvisioningPipeline, {
controller: provisioningController(state),
desiredMode: "bridge",
}));
assert.equal(physicalRecoveryConnectionDetail(state), null);
assert.match(markup, /ПОДКЛЮЧЕНИЕ · ШАГИ 01–02/);
assert.match(markup, /
01<\/span>/);
assert.match(markup, /Подключение<\/h3>/);
assert.doesNotMatch(markup, /02<\/span>|03<\/span>/);
assert.doesNotMatch(markup, /Питание|индикатор горит/);
assert.doesNotMatch(markup, /Название общей сети Wi‑Fi|Пароль Wi‑Fi/);
assert.doesNotMatch(markup, /class="nodedc-activity-indicator"/);
const scanButton = buttonMarkupWithText(markup, "Найти по Bluetooth")[0];
assert.ok(scanButton);
assert.doesNotMatch(scanButton, /\bdisabled(?:=|\s|>)/);
assert.equal(
buttonMarkupWithText(markup, "Подключить новый K1").length,
0,
);
const modeToggle = markup.match(
/