Compare commits

..
28 changed files with 802 additions and 526 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
.configuration-tree{margin-top:.25rem}.configuration-tree>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.configuration-card{min-width:0px}.configuration-card-header{top:var(--configuration-sticky-top, 0px)}.configuration-card .configuration-card{margin-left:1rem;width:calc(100% - 1rem)}.configuration-card-body>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.configuration-card-body{padding:.125rem}.configuration-children>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.configuration-line{display:grid;min-width:0px;grid-template-columns:repeat(1,minmax(0,1fr));align-items:flex-start;gap:.125rem;border-radius:.375rem;--tw-bg-opacity: 1;background-color:rgb(38 38 38 / var(--tw-bg-opacity));padding:.125rem}@media(min-width:640px){.configuration-line{grid-template-columns:minmax(9rem,16rem) minmax(12rem,40rem)}}.configuration-line{justify-content:start}.configuration-key,.configuration-value{min-width:0px}.configuration-key-label{font-size:1rem;line-height:1.5rem;font-weight:600;line-height:1.375;--tw-text-opacity: 1;color:rgb(241 245 249 / var(--tw-text-opacity))}.configuration-root-description,.configuration-branch-description,.configuration-item-description,.configuration-value-description{display:block;font-size:.875rem;line-height:1.25rem;line-height:1.375;--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity));margin-top:.125rem}.configuration-root-description{margin-bottom:.25rem}.configuration-branch-description,.configuration-item-description{max-width:56rem}.configuration-value-description{margin-bottom:.125rem;max-width:40rem}.configuration-value input:not([type=checkbox]),.configuration-value select,.configuration-value textarea{width:100%;border-radius:.375rem;border-width:1px;--tw-border-opacity: 1;border-color:rgb(82 82 82 / var(--tw-border-opacity));--tw-bg-opacity: 1;background-color:rgb(64 64 64 / var(--tw-bg-opacity));padding:.125rem;--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.configuration-value input:not([type=checkbox])::-moz-placeholder,.configuration-value select::-moz-placeholder,.configuration-value textarea::-moz-placeholder{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity))}.configuration-value input:not([type=checkbox])::placeholder,.configuration-value select::placeholder,.configuration-value textarea::placeholder{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity))}.configuration-value input:not([type=checkbox]):focus,.configuration-value select:focus,.configuration-value textarea:focus{outline:2px solid transparent;outline-offset:2px;--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000);--tw-ring-opacity: 1;--tw-ring-color: rgb(14 165 233 / var(--tw-ring-opacity))}.configuration-value input[type=checkbox]{height:1rem;width:1rem;vertical-align:middle;accent-color:#0ea5e9}.configuration-value .checkbox label{display:flex;min-height:1.75rem;align-items:center;--tw-text-opacity: 1;color:rgb(241 245 249 / var(--tw-text-opacity))}.configuration-value .error-detail{margin-top:.125rem;font-size:.75rem;line-height:1rem;--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity))}.configuration-value .help-block{margin-top:.125rem;display:block;font-size:.7rem;--tw-text-opacity: 1;color:rgb(100 116 139 / var(--tw-text-opacity))}.configuration-secret{min-width:0px}.configuration-item-actions,.configuration-array-actions{display:flex;flex-wrap:wrap;gap:.125rem}
@@ -0,0 +1 @@
.configuration-tree{margin-top:.25rem}.configuration-tree>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.configuration-card{min-width:0px}.configuration-card-header{top:var(--configuration-sticky-top, 0px)}.configuration-card .configuration-card{margin-left:1rem;width:calc(100% - 1rem)}.configuration-card-body>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.configuration-card-body{padding:.125rem}.configuration-children>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.configuration-line{display:grid;min-width:0px;grid-template-columns:repeat(1,minmax(0,1fr));align-items:flex-start;gap:.125rem;border-radius:.375rem;--tw-bg-opacity: 1;background-color:rgb(38 38 38 / var(--tw-bg-opacity, 1));padding:.125rem}@media(min-width:640px){.configuration-line{grid-template-columns:minmax(9rem,16rem) minmax(12rem,40rem)}}.configuration-line{justify-content:start}.configuration-key,.configuration-value{min-width:0px}.configuration-key-label{font-size:1rem;line-height:1.5rem;font-weight:600;line-height:1.375;--tw-text-opacity: 1;color:rgb(241 245 249 / var(--tw-text-opacity, 1))}.configuration-root-description,.configuration-branch-description,.configuration-item-description,.configuration-value-description{display:block;font-size:.875rem;line-height:1.25rem;line-height:1.375;--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity, 1));margin-top:.125rem}.configuration-root-description{margin-bottom:.25rem}.configuration-branch-description,.configuration-item-description{max-width:56rem}.configuration-value-description{margin-bottom:.125rem;max-width:40rem}.configuration-value input:not([type=checkbox]),.configuration-value select,.configuration-value textarea{width:100%;border-radius:.375rem;border-width:1px;--tw-border-opacity: 1;border-color:rgb(82 82 82 / var(--tw-border-opacity, 1));--tw-bg-opacity: 1;background-color:rgb(64 64 64 / var(--tw-bg-opacity, 1));padding:.125rem;--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.configuration-value input:not([type=checkbox])::-moz-placeholder,.configuration-value select::-moz-placeholder,.configuration-value textarea::-moz-placeholder{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity, 1))}.configuration-value input:not([type=checkbox])::placeholder,.configuration-value select::placeholder,.configuration-value textarea::placeholder{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity, 1))}.configuration-value input:not([type=checkbox]):focus,.configuration-value select:focus,.configuration-value textarea:focus{outline:2px solid transparent;outline-offset:2px;--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000);--tw-ring-opacity: 1;--tw-ring-color: rgb(14 165 233 / var(--tw-ring-opacity, 1))}.configuration-value input[type=checkbox]{height:1rem;width:1rem;vertical-align:middle;accent-color:#0ea5e9}.configuration-value .checkbox label{display:flex;min-height:1.75rem;align-items:center;--tw-text-opacity: 1;color:rgb(241 245 249 / var(--tw-text-opacity, 1))}.configuration-value .error-detail{margin-top:.125rem;font-size:.75rem;line-height:1rem;--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.configuration-value .help-block{margin-top:.125rem;display:block;font-size:.7rem;--tw-text-opacity: 1;color:rgb(100 116 139 / var(--tw-text-opacity, 1))}.configuration-secret{min-width:0px}.configuration-item-actions,.configuration-array-actions{display:flex;flex-wrap:wrap;gap:.125rem}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,2 +1,2 @@
import{e as F,r as s,j as e,S as P,C as c,L as q}from"./index-n0JxE1Mv.js";import{o as $,p as D,q as I}from"./api-B8GGCEeo.js";function R(){const l=F(),[a,m]=s.useState(null),[n,b]=s.useState(""),[d,C]=s.useState(""),[p,N]=s.useState(""),[r,S]=s.useState(""),[f,v]=s.useState(""),[o,w]=s.useState(null),[x,h]=s.useState(!1),[g,i]=s.useState("");s.useEffect(()=>{$(l).then(t=>m(t.required)).catch(t=>i(t.message))},[l]);async function j(t){h(!0),i("");try{await t(),m(!1),i("Setup completed. You can now open the administration application and log in.")}catch(u){const E=Array.isArray(u.validationErrors)?` ${u.validationErrors.map(y=>`${y.path}: ${y.message}`).join("; ")}`:"";i(`${u.message}${E}`)}finally{h(!1)}}function k(t){if(t.preventDefault(),r!==f){i("Passwords do not match.");return}j(()=>D(l,{setupCode:n,username:d,discordId:p,password:r}))}function A(t){t.preventDefault(),o&&j(async()=>I(l,{setupCode:n,fileName:o.name,yaml:await o.text()}))}return e.jsxs("div",{className:"min-h-screen bg-neutral-950 p-1 text-slate-100",children:[e.jsx(P,{}),e.jsxs("main",{className:"mx-auto flex min-h-screen w-full max-w-3xl flex-col justify-center gap-0.5",children:[e.jsxs(c,{title:"MultiRover setup",meta:a===null?"checking":a?"required":"complete",bodyClassName:"space-y-0.5 p-1 text-sm",children:[a?e.jsx("p",{children:"Enter the one-time code from setup-code.txt in the server data folder, then create the first lockdown administrator or import an existing configuration."}):null,a===!1?e.jsx(q,{className:"button-dark inline-block",to:"/admin",children:"Open administration"}):null,g?e.jsx("p",{className:"surface p-1 text-sm text-slate-200",children:g}):null]}),a?e.jsxs(e.Fragment,{children:[e.jsxs(c,{title:"Setup authorization",bodyClassName:"p-1",children:[e.jsx("label",{className:"block text-xs font-semibold text-slate-200",children:"One-time setup code"}),e.jsx("input",{className:"field-input mt-0.5 w-full font-mono",value:n,onChange:t=>b(t.target.value)})]}),e.jsx(c,{title:"Create first administrator",bodyClassName:"p-1",children:e.jsxs("form",{className:"grid gap-0.5 md:grid-cols-2",onSubmit:k,children:[e.jsx("input",{className:"field-input",placeholder:"Username",value:d,onChange:t=>C(t.target.value)}),e.jsx("input",{className:"field-input",placeholder:"Discord id (optional)",value:p,onChange:t=>N(t.target.value)}),e.jsx("input",{className:"field-input",type:"password",placeholder:"Password",value:r,onChange:t=>S(t.target.value)}),e.jsx("input",{className:"field-input",type:"password",placeholder:"Confirm password",value:f,onChange:t=>v(t.target.value)}),e.jsx("button",{className:"button-dark md:col-span-2",type:"submit",disabled:x||!n||!d||!r,children:"Create lockdown administrator"})]})}),e.jsxs(c,{title:"Import configuration file",bodyClassName:"space-y-0.5 p-1 text-sm",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Choose an existing YAML configuration explicitly. The server validates and imports it once, and its secrets are never displayed back in the browser."}),e.jsxs("form",{className:"flex flex-col gap-0.5 md:flex-row",onSubmit:A,children:[e.jsx("input",{className:"field-input flex-1",type:"file",accept:".yaml,.yml,text/yaml",onChange:t=>w(t.target.files?.[0]||null)}),e.jsx("button",{className:"button-dark",type:"submit",disabled:x||!n||!o,children:"Import selected YAML"})]})]})]}):null]})]})}export{R as default}; import{e as F,r as s,j as e,S as P,C as c,L as q}from"./index-B5v0jIZV.js";import{o as $,p as D,q as I}from"./api-B8GGCEeo.js";function R(){const l=F(),[a,m]=s.useState(null),[n,b]=s.useState(""),[d,C]=s.useState(""),[p,N]=s.useState(""),[r,S]=s.useState(""),[f,v]=s.useState(""),[o,w]=s.useState(null),[x,h]=s.useState(!1),[g,i]=s.useState("");s.useEffect(()=>{$(l).then(t=>m(t.required)).catch(t=>i(t.message))},[l]);async function j(t){h(!0),i("");try{await t(),m(!1),i("Setup completed. You can now open the administration application and log in.")}catch(u){const E=Array.isArray(u.validationErrors)?` ${u.validationErrors.map(y=>`${y.path}: ${y.message}`).join("; ")}`:"";i(`${u.message}${E}`)}finally{h(!1)}}function k(t){if(t.preventDefault(),r!==f){i("Passwords do not match.");return}j(()=>D(l,{setupCode:n,username:d,discordId:p,password:r}))}function A(t){t.preventDefault(),o&&j(async()=>I(l,{setupCode:n,fileName:o.name,yaml:await o.text()}))}return e.jsxs("div",{className:"min-h-screen bg-neutral-950 p-1 text-slate-100",children:[e.jsx(P,{}),e.jsxs("main",{className:"mx-auto flex min-h-screen w-full max-w-3xl flex-col justify-center gap-0.5",children:[e.jsxs(c,{title:"MultiRover setup",meta:a===null?"checking":a?"required":"complete",bodyClassName:"space-y-0.5 p-1 text-sm",children:[a?e.jsx("p",{children:"Enter the one-time code from setup-code.txt in the server data folder, then create the first lockdown administrator or import an existing configuration."}):null,a===!1?e.jsx(q,{className:"button-dark inline-block",to:"/admin",children:"Open administration"}):null,g?e.jsx("p",{className:"surface p-1 text-sm text-slate-200",children:g}):null]}),a?e.jsxs(e.Fragment,{children:[e.jsxs(c,{title:"Setup authorization",bodyClassName:"p-1",children:[e.jsx("label",{className:"block text-xs font-semibold text-slate-200",children:"One-time setup code"}),e.jsx("input",{className:"field-input mt-0.5 w-full font-mono",value:n,onChange:t=>b(t.target.value)})]}),e.jsx(c,{title:"Create first administrator",bodyClassName:"p-1",children:e.jsxs("form",{className:"grid gap-0.5 md:grid-cols-2",onSubmit:k,children:[e.jsx("input",{className:"field-input",placeholder:"Username",value:d,onChange:t=>C(t.target.value)}),e.jsx("input",{className:"field-input",placeholder:"Discord id (optional)",value:p,onChange:t=>N(t.target.value)}),e.jsx("input",{className:"field-input",type:"password",placeholder:"Password",value:r,onChange:t=>S(t.target.value)}),e.jsx("input",{className:"field-input",type:"password",placeholder:"Confirm password",value:f,onChange:t=>v(t.target.value)}),e.jsx("button",{className:"button-dark md:col-span-2",type:"submit",disabled:x||!n||!d||!r,children:"Create lockdown administrator"})]})}),e.jsxs(c,{title:"Import configuration file",bodyClassName:"space-y-0.5 p-1 text-sm",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Choose an existing YAML configuration explicitly. The server validates and imports it once, and its secrets are never displayed back in the browser."}),e.jsxs("form",{className:"flex flex-col gap-0.5 md:flex-row",onSubmit:A,children:[e.jsx("input",{className:"field-input flex-1",type:"file",accept:".yaml,.yml,text/yaml",onChange:t=>w(t.target.files?.[0]||null)}),e.jsx("button",{className:"button-dark",type:"submit",disabled:x||!n||!o,children:"Import selected YAML"})]})]})]}):null]})]})}export{R as default};
//# sourceMappingURL=SetupApp-CaWv689i.js.map //# sourceMappingURL=SetupApp-BIEDeUVT.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -12,8 +12,8 @@
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<!-- site-metadata:inject --> <!-- site-metadata:inject -->
<!-- analytics:inject --> <!-- analytics:inject -->
<script type="module" crossorigin src="/assets/index-n0JxE1Mv.js"></script> <script type="module" crossorigin src="/assets/index-B5v0jIZV.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-xCRVLGjq.css"> <link rel="stylesheet" crossorigin href="/assets/index-CsoONCTh.css">
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
@@ -6,12 +6,14 @@ const { MessageFlags } = require('discord.js');
function createChannelIO({ client, logger, sanitizeMentions }) { function createChannelIO({ client, logger, sanitizeMentions }) {
const channelCache = new Map(); const channelCache = new Map();
const typingMessageCache = new Map(); const typingMessageCache = new Map();
let stopped = false;
async function fetchChannel(id) { async function fetchChannel(id) {
if (!id) return null; if (stopped || !client.isReady() || !id) return null;
if (channelCache.has(id)) return channelCache.get(id); if (channelCache.has(id)) return channelCache.get(id);
try { try {
const channel = await client.channels.fetch(id); const channel = await client.channels.fetch(id);
if (stopped) return null;
if (channel) { if (channel) {
channelCache.set(id, channel); channelCache.set(id, channel);
return channel; return channel;
@@ -68,6 +70,7 @@ function createChannelIO({ client, logger, sanitizeMentions }) {
const content = `-# *${username} is typing...*`; const content = `-# *${username} is typing...*`;
try { try {
const message = await channel.send({ content, allowedMentions: { parse: [] }, flags: [MessageFlags.SuppressNotifications]}); const message = await channel.send({ content, allowedMentions: { parse: [] }, flags: [MessageFlags.SuppressNotifications]});
if (stopped) return;
const timeoutId = setTimeout(() => { const timeoutId = setTimeout(() => {
clearTypingMessage(entry.guildId, typingId); clearTypingMessage(entry.guildId, typingId);
}, 20000); }, 20000);
@@ -78,6 +81,12 @@ function createChannelIO({ client, logger, sanitizeMentions }) {
} }
return { return {
stop() {
stopped = true;
for (const record of typingMessageCache.values()) clearTimeout(record.timeoutId);
typingMessageCache.clear();
channelCache.clear();
},
fetchChannel, fetchChannel,
sendToChannel, sendToChannel,
clearTypingMessage, clearTypingMessage,
@@ -0,0 +1,94 @@
// Owns connection replacement and recovery from failed initial logins.
function createConnectionManager({ createRuntime, logger }) {
let desired = { enabled: false, token: '' };
let revision = 0;
let runtime = null;
let queue = Promise.resolve();
let retryTimer = null;
let retryDelay = 5000;
function enqueue(operation) {
const pending = queue.then(operation);
// Report failures without poisoning subsequent configuration changes.
queue = pending.catch((err) => logger.error('Discord connection update failed', err.message));
return pending;
}
async function stop() {
const previous = runtime;
runtime = null;
if (!previous) return;
previous.stop();
// discord.js cannot cancel login while gateway discovery is pending.
// Let that attempt settle before destroying it, otherwise it can open a
// socket after destroy() has already run and leave an orphan connection.
await previous.login;
await previous.client.destroy();
}
function scheduleRetry(version) {
if (version !== revision || !desired.enabled) return;
const delay = retryDelay;
retryDelay = Math.min(retryDelay * 2, 60000);
logger.warn('Retrying Discord login', { delayMs: delay });
retryTimer = setTimeout(() => {
retryTimer = null;
enqueue(() => start(version));
}, delay);
retryTimer.unref?.();
}
async function start(version) {
if (version !== revision || !desired.enabled) return;
await stop();
if (version !== revision || !desired.enabled) return;
const current = createRuntime();
runtime = current;
const { client } = current;
client.on('error', (err) => logger.error('Discord client error', err.message));
client.on('shardError', (err, shardId) => {
logger.warn('Discord connection error', { shardId, error: err.message });
});
client.on('shardDisconnect', (event, shardId) => {
logger.warn('Discord disconnected', { shardId, code: event.code });
});
client.on('clientReady', () => { retryDelay = 5000; });
// Login must not block configuration saves while the network is down.
// Each attempt has its own client, so stale login completion/cleanup cannot
// clear the credentials or stop the connection of its replacement.
current.login = client.login(desired.token).catch((err) => {
if (version !== revision || runtime !== current) return;
logger.error('Discord login failed', err.message);
enqueue(async () => {
if (version !== revision || runtime !== current) return;
await stop();
// Credentials require an operator edit; retry network/service failures.
if (err.code === 'TokenInvalid' || err.status === 401) return;
scheduleRetry(version);
});
});
}
function configure({ enabled, token }) {
const next = { enabled: Boolean(enabled), token };
if (next.enabled === desired.enabled && next.token === desired.token) return queue;
desired = next;
const version = ++revision;
clearTimeout(retryTimer);
retryTimer = null;
retryDelay = 5000;
return enqueue(async () => {
if (version !== revision) return;
if (desired.enabled) await start(version);
else await stop();
});
}
return {
configure,
refresh() { runtime?.refresh(); },
};
}
module.exports = { createConnectionManager };
@@ -0,0 +1,146 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { EventEmitter } = require('node:events');
const { createConnectionManager } = require('./connection');
const flush = () => new Promise((resolve) => setImmediate(resolve));
function deferred() {
let resolve;
let reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
}
function setup(t, attempts = []) {
t.mock.timers.enable({ apis: ['setTimeout'] });
const runtimes = [];
const logs = [];
const manager = createConnectionManager({
logger: {
warn: (...args) => logs.push(args),
error: (...args) => logs.push(args),
},
createRuntime() {
const attempt = attempts[runtimes.length] || {};
const client = new EventEmitter();
const runtime = {
client,
stopped: false,
destroyed: false,
refresh() {},
stop() { runtime.stopped = true; },
};
client.login = async (token) => {
runtime.token = token;
await attempt.login?.();
};
client.destroy = async () => {
await attempt.destroy?.();
runtime.destroyed = true;
};
runtimes.push(runtime);
return runtime;
},
});
return { manager, runtimes, logs };
}
test('retries a network failure at startup with a fresh client', async (t) => {
const { manager, runtimes } = setup(t, [{ login: () => { throw new Error('getaddrinfo EAI_AGAIN'); } }]);
await manager.configure({ enabled: true, token: 'token' });
await flush();
assert.equal(runtimes[0].stopped, true);
assert.equal(runtimes[0].destroyed, true);
t.mock.timers.tick(4999);
await flush();
assert.equal(runtimes.length, 1);
t.mock.timers.tick(1);
await flush();
assert.equal(runtimes.length, 2);
assert.equal(runtimes[1].token, 'token');
assert.notEqual(runtimes[0].client, runtimes[1].client);
});
test('backs off repeated failures and cancels retries when disabled', async (t) => {
const failed = { login: () => { throw new Error('Network unavailable'); } };
const { manager, runtimes, logs } = setup(t, Array(8).fill(failed));
await manager.configure({ enabled: true, token: 'token' });
await flush();
for (const delay of [5000, 10000, 20000, 40000, 60000]) {
t.mock.timers.tick(delay);
await flush();
}
assert.deepEqual(logs.filter(([message]) => message === 'Retrying Discord login').map(([, data]) => data.delayMs),
[5000, 10000, 20000, 40000, 60000, 60000]);
await manager.configure({ enabled: false, token: 'token' });
t.mock.timers.tick(120000);
await flush();
assert.equal(runtimes.length, 6);
});
test('waits for logout before logging in with a changed token', async (t) => {
const logout = deferred();
const { manager, runtimes } = setup(t, [{ destroy: () => logout.promise }]);
await manager.configure({ enabled: true, token: 'old' });
const change = manager.configure({ enabled: true, token: 'new' });
await flush();
assert.equal(runtimes[0].stopped, true);
assert.equal(runtimes.length, 1);
logout.resolve();
await change;
assert.equal(runtimes[0].destroyed, true);
assert.equal(runtimes[1].token, 'new');
});
test('retires a pending login before replacement and ignores its stale failure', async (t) => {
const login = deferred();
const { manager, runtimes } = setup(t, [{ login: () => login.promise }]);
await manager.configure({ enabled: true, token: 'old' });
const change = manager.configure({ enabled: true, token: 'new' });
await flush();
assert.equal(runtimes[0].stopped, true);
assert.equal(runtimes[0].destroyed, false);
login.reject(new Error('Old connection failed'));
await change;
assert.equal(runtimes[0].destroyed, true);
assert.equal(runtimes[1].token, 'new');
t.mock.timers.tick(120000);
await flush();
assert.equal(runtimes.length, 2);
});
test('re-enabling creates a fresh client; unrelated config edits do not reconnect', async (t) => {
const { manager, runtimes } = setup(t);
await manager.configure({ enabled: true, token: 'token' });
await manager.configure({ enabled: true, token: 'token', channels: { general: 'new-channel' } });
assert.equal(runtimes.length, 1);
await manager.configure({ enabled: false, token: 'token' });
assert.equal(runtimes[0].destroyed, true);
await manager.configure({ enabled: true, token: 'token' });
assert.equal(runtimes.length, 2);
});
test('invalid credentials wait for a token edit instead of retrying', async (t) => {
const { manager, runtimes } = setup(t, [{ login: () => {
throw Object.assign(new Error('Invalid token'), { code: 'TokenInvalid' });
} }]);
await manager.configure({ enabled: true, token: 'bad' });
await flush();
t.mock.timers.tick(120000);
await flush();
assert.equal(runtimes.length, 1);
await manager.configure({ enabled: true, token: 'fixed' });
assert.equal(runtimes[1].token, 'fixed');
});
test('client and gateway errors are logged without throwing', async (t) => {
const { manager, runtimes, logs } = setup(t);
await manager.configure({ enabled: true, token: 'token' });
runtimes[0].client.emit('error', new Error('Client failure'));
runtimes[0].client.emit('shardError', new Error('Gateway failure'), 0);
runtimes[0].client.emit('shardDisconnect', { code: 1006 }, 0);
assert.deepEqual(logs.map(([message]) => message), [
'Discord client error', 'Discord connection error', 'Discord disconnected',
]);
});
+38 -36
View File
@@ -67,6 +67,7 @@ const {
} = require('../privateRoverAccessRequestService'); } = require('../privateRoverAccessRequestService');
const { subscribe } = require('../eventBus'); const { subscribe } = require('../eventBus');
const { createPresenceManager } = require('./presence'); const { createPresenceManager } = require('./presence');
const { createConnectionManager } = require('./connection');
const { createChannelIO } = require('./channelIO'); const { createChannelIO } = require('./channelIO');
const { createCommandHandlers } = require('../operatorCommandService'); const { createCommandHandlers } = require('../operatorCommandService');
const greenModeService = require('../greenModeService'); const greenModeService = require('../greenModeService');
@@ -86,9 +87,7 @@ const {
buildStatusMessage, buildStatusMessage,
} = require('../replayDeliveryService/workflow'); } = require('../replayDeliveryService/workflow');
// Discord helper modules retain references to these objects. Mutating those // Keep configuration object identities stable for the active runtime's helpers.
// references on configuration application updates command and integration
// behavior without registering a second tree of Discord/event listeners.
const config = structuredClone(loadConfig()); const config = structuredClone(loadConfig());
const discordConfig = config.discord || {}; const discordConfig = config.discord || {};
let enabled = Boolean(discordConfig.enabled); let enabled = Boolean(discordConfig.enabled);
@@ -106,11 +105,6 @@ const intents = [
GatewayIntentBits.MessageContent, GatewayIntentBits.MessageContent,
]; ];
const client = new Client({
intents,
partials: [Partials.Channel, Partials.Message, Partials.Reaction, Partials.User],
});
function sanitizeMentions(text) { function sanitizeMentions(text) {
if (!text) return ''; if (!text) return '';
return String(text) return String(text)
@@ -156,6 +150,13 @@ function countReady() {
return { ready, total }; return { ready, total };
} }
// Each connection owns its listeners, timers, and cached Discord objects.
// Rebuilding them prevents a reconnect from retaining a destroyed client.
function createDiscordRuntime() {
const client = new Client({
intents,
partials: [Partials.Channel, Partials.Message, Partials.Reaction, Partials.User],
});
const channelIO = createChannelIO({ const channelIO = createChannelIO({
client, client,
logger, logger,
@@ -181,7 +182,7 @@ const replayCaption = createReplayCaptionBuilder({
// Discord is the preferred replay host only while this optional feature is // Discord is the preferred replay host only while this optional feature is
// active. The core replay delivery service owns generation and automatically // active. The core replay delivery service owns generation and automatically
// falls back to its local media store when any operation below fails. // falls back to its local media store when any operation below fails.
registerPreferredDeliveryProvider({ const unregisterReplayProvider = registerPreferredDeliveryProvider({
async begin(job) { async begin(job) {
const channelId = discordConfig.channels?.replay; const channelId = discordConfig.channels?.replay;
if (!enabled || !channelId) throw new Error('Discord replay delivery is disabled'); if (!enabled || !channelId) throw new Error('Discord replay delivery is disabled');
@@ -405,7 +406,7 @@ function restartFleetDailyReports() {
fleetDailyReports.start(); fleetDailyReports.start();
} }
client.on('ready', () => { client.on('clientReady', () => {
logger.info('Discord bot logged in', { tag: client.user?.tag }); logger.info('Discord bot logged in', { tag: client.user?.tag });
presence.schedulePresenceRotation(); presence.schedulePresenceRotation();
// Discord is only a delivery consumer. Starting its scheduler after the bot // Discord is only a delivery consumer. Starting its scheduler after the bot
@@ -414,42 +415,45 @@ client.on('ready', () => {
restartFleetDailyReports(); restartFleetDailyReports();
}); });
return {
client,
refresh() {
if (client.isReady()) restartFleetDailyReports();
},
stop() {
for (const event of ['clientReady', 'messageCreate', 'typingStart', 'messageReactionAdd']) {
client.removeAllListeners(event);
}
integrationHandlers.stop();
unregisterReplayProvider();
presence.stop();
channelIO.stop();
fleetDailyReports?.stop();
},
};
}
const connection = createConnectionManager({ createRuntime: createDiscordRuntime, logger });
function replaceObject(target, source = {}) { function replaceObject(target, source = {}) {
Object.keys(target).forEach((key) => delete target[key]); Object.keys(target).forEach((key) => delete target[key]);
Object.assign(target, structuredClone(source)); Object.assign(target, structuredClone(source));
} }
function applyDiscordConfig(nextDiscordConfig = {}) { async function applyDiscordConfig(nextDiscordConfig = {}) {
const wasEnabled = enabled;
const previousToken = discordConfig.token;
replaceObject(discordConfig, nextDiscordConfig); replaceObject(discordConfig, nextDiscordConfig);
config.discord = discordConfig; config.discord = discordConfig;
enabled = Boolean(discordConfig.enabled); enabled = Boolean(discordConfig.enabled);
await connection.configure(discordConfig);
if (!enabled) { connection.refresh();
fleetDailyReports?.stop();
fleetDailyReports = null;
if (wasEnabled) client.destroy();
return;
}
if (!wasEnabled || previousToken !== discordConfig.token) {
if (wasEnabled) client.destroy();
// Login health is reported by Discord itself; do not hold the committed
// configuration request open while an external network service connects.
client.login(discordConfig.token).catch((err) => {
logger.error('Discord login failed after configuration change', err.message);
});
} else if (client.isReady()) {
restartFleetDailyReports();
}
} }
function applySharedConfigSection(section, value) { function applySharedConfigSection(section, value) {
config[section] = structuredClone(value); config[section] = structuredClone(value);
// Fleet delivery owns a timer derived from both Discord and fleet settings. // Fleet delivery owns a timer derived from both Discord and fleet settings.
// Reconnecting is unnecessary; rebuild only that scheduler when ready. // Reconnecting is unnecessary; rebuild only that scheduler when ready.
if (section === 'fleetReports' && client.isReady()) { if (section === 'fleetReports') {
restartFleetDailyReports(); connection.refresh();
} }
} }
@@ -458,10 +462,8 @@ registerConfigurationHandler('discord', applyDiscordConfig);
registerConfigurationHandler(section, (value) => applySharedConfigSection(section, value)); registerConfigurationHandler(section, (value) => applySharedConfigSection(section, value));
}); });
if (enabled) { connection.configure(discordConfig).catch((err) => {
client.login(discordConfig.token).catch((err) => { logger.error('Discord startup failed', err.message);
logger.error('Discord login failed', err.message);
}); });
}
module.exports = {}; module.exports = {};
@@ -24,6 +24,7 @@ function createIntegrations(deps) {
const userAnnouncements = createUserAnnouncements({ ...deps, sendToChannel, schedulePresenceRotation }); const userAnnouncements = createUserAnnouncements({ ...deps, sendToChannel, schedulePresenceRotation });
function register() { function register() {
let stopped = false;
client.on('typingStart', (typing) => { client.on('typingStart', (typing) => {
chat.handleDiscordTypingStart(typing).catch((err) => logger.warn('Error handling Discord typing', err.message)); chat.handleDiscordTypingStart(typing).catch((err) => logger.warn('Error handling Discord typing', err.message));
}); });
@@ -33,14 +34,31 @@ function createIntegrations(deps) {
dm.handlePrivateAccessReaction(reaction, user).catch((err) => logger.warn('Error handling private access reaction', err.message)); dm.handlePrivateAccessReaction(reaction, user).catch((err) => logger.warn('Error handling private access reaction', err.message));
}); });
subscribe('*', handleBusEvent); // Only the active, ready connection consumes server events. Retain each
subscribe('*', userAnnouncements.handleBusEvent); // unsubscribe function so replacement clients never duplicate deliveries.
subscribe('verification.requested', dm.sendVerificationRequestDms); const unsubscribe = [];
subscribe('privateRoverAccess.requested', dm.sendPrivateRoverAccessRequestDms); function subscribeWhileReady(type, handler) {
subscribe('chat:message', chat.handleChatBridgeOutbound); unsubscribe.push(subscribe(type, (event) => {
subscribe('chat:typing', chat.handleChatTypingOutbound); Promise.resolve().then(() => {
if (!stopped && client.isReady()) return handler(event);
}).catch((err) => {
logger.warn('Error handling Discord integration event', { type, error: err.message });
});
}));
}
subscribeWhileReady('*', handleBusEvent);
subscribeWhileReady('*', userAnnouncements.handleBusEvent);
subscribeWhileReady('verification.requested', dm.sendVerificationRequestDms);
subscribeWhileReady('privateRoverAccess.requested', dm.sendPrivateRoverAccessRequestDms);
subscribeWhileReady('chat:message', chat.handleChatBridgeOutbound);
subscribeWhileReady('chat:typing', chat.handleChatTypingOutbound);
return { return {
stop() {
stopped = true;
unsubscribe.forEach((remove) => remove());
},
handleBridgeInbound: chat.handleBridgeInbound, handleBridgeInbound: chat.handleBridgeInbound,
handleBusEvent, handleBusEvent,
}; };
@@ -7,6 +7,7 @@ function createPresenceManager({ client, logger, getMode, getGlobalObjective, co
const PRESENCE_ROTATE_MS = 20000; const PRESENCE_ROTATE_MS = 20000;
let presenceInterval = null; let presenceInterval = null;
let presenceShowObjective = false; let presenceShowObjective = false;
let stopped = false;
function truncatePresenceText(text, maxLength) { function truncatePresenceText(text, maxLength) {
if (!text) return ''; if (!text) return '';
@@ -40,6 +41,7 @@ function createPresenceManager({ client, logger, getMode, getGlobalObjective, co
} }
function schedulePresenceRotation() { function schedulePresenceRotation() {
if (stopped) return;
if (presenceInterval) { if (presenceInterval) {
clearInterval(presenceInterval); clearInterval(presenceInterval);
presenceInterval = null; presenceInterval = null;
@@ -59,6 +61,11 @@ function createPresenceManager({ client, logger, getMode, getGlobalObjective, co
} }
return { return {
stop() {
stopped = true;
clearInterval(presenceInterval);
presenceInterval = null;
},
schedulePresenceRotation, schedulePresenceRotation,
}; };
} }
+1 -1
View File
@@ -4,7 +4,7 @@
"version": "0.0.0", "version": "0.0.0",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "VITE_ROVERD_URL=https://rover.otter.land vite", "dev": "VITE_ROVERD_URL=http://192.168.0.86:8080 vite",
"build": "vite build", "build": "vite build",
"lint": "eslint .", "lint": "eslint .",
"test": "node --test src/controls/inputs/*.test.js src/components/GamepadMappingSettings/*.test.js", "test": "node --test src/controls/inputs/*.test.js src/components/GamepadMappingSettings/*.test.js",
+3
View File
@@ -7,6 +7,7 @@ import { shallowArrayEqual, shallowObjectEqual } from './TelemetryContext.jsx';
const EMPTY_BATTERY_TELEMETRY = Object.freeze({ const EMPTY_BATTERY_TELEMETRY = Object.freeze({
batteryChargeMah: null, batteryChargeMah: null,
batteryCapacityMah: null, batteryCapacityMah: null,
batteryVoltage: null,
}); });
const EMPTY_DOCK_TELEMETRY = Object.freeze({ const EMPTY_DOCK_TELEMETRY = Object.freeze({
@@ -89,6 +90,8 @@ export function selectBatteryTelemetry(frame) {
return { return {
batteryChargeMah: sensors.batteryChargeMah ?? null, batteryChargeMah: sensors.batteryChargeMah ?? null,
batteryCapacityMah: sensors.batteryCapacityMah ?? null, batteryCapacityMah: sensors.batteryCapacityMah ?? null,
batteryVoltage: (sensors.voltageMv/1000).toPrecision(4) ?? null,
batteryCurrent: (sensors.currentMa) ?? null,
}; };
} }
@@ -25,10 +25,14 @@ export default function DisplayRoverCell({ rover, session }) {
const driver = findDriverForRover({ roverId: rover?.id, session }); const driver = findDriverForRover({ roverId: rover?.id, session });
const stateText = buildRoverStateText(rover, visual); const stateText = buildRoverStateText(rover, visual);
const batteryText = formatBatteryText(visual); const batteryText = formatBatteryText(visual);
const batteryVoltage = frame?.sensors.batteryVoltage;
const batteryCurrent = frame?.sensors.batteryCurrent;
const active = Boolean(driver); const active = Boolean(driver);
const urgent = Boolean(visual?.urgentActive); const urgent = Boolean(visual?.urgentActive);
const warn = Boolean(visual?.warnActive); const warn = Boolean(visual?.warnActive);
const locked = Boolean(rover?.locked); const locked = Boolean(rover?.locked);
// console.log(batteryTelemetry)
// console.log(batteryVoltage)
return ( return (
<article <article
@@ -80,16 +84,19 @@ export default function DisplayRoverCell({ rover, session }) {
{driver?.label || 'Idle'} {driver?.label || 'Idle'}
</AutoFitText> </AutoFitText>
</div> </div>
<div className="min-w-0"> <div className="min-w-0 bg-black/50 rounded">
<AutoFitText <AutoFitText
className={classNames( className={classNames(
'font-black leading-none', 'font-black leading-none',
urgent ? 'text-red-100' : warn ? 'text-amber-100' : 'text-slate-100', urgent ? 'text-red-100' : warn ? 'text-amber-100' : 'text-slate-100',
)} )}
maxSize={136} maxSize={70}
minSize={32} minSize={32}
> >
{batteryText} <div className='border-b'>{batteryText}</div>
<div>{batteryVoltage}v</div>
{/* <div className=''>{batteryCurrent}mA</div> */}
{(Math.abs(batteryCurrent) > 10) ? (<div className='border-t'> {batteryCurrent + 'mA'}</div>) : null}
</AutoFitText> </AutoFitText>
</div> </div>
</div> </div>
@@ -98,9 +105,6 @@ export default function DisplayRoverCell({ rover, session }) {
{stateText} {stateText}
</div> </div>
) : ( ) : (
// This empty line keeps cells with and without exceptional states the
// same height. The grid should not jump just because one rover becomes
// locked or low battery while people are reading the board.
<div aria-hidden="true" /> <div aria-hidden="true" />
)} )}
</div> </div>