Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: wait for Tailcat forward exit before retrying (#8827)
[._.]/ Adam Eivy88372136676d
diff --git a/server/services/tailcatPeer.js b/server/services/tailcatPeer.jsindex f1807841f4..4f332f3b43 100644--- a/server/services/tailcatPeer.js+++ b/server/services/tailcatPeer.js@@ -17,6 +17,7 @@ import { randomUUID } from 'node:crypto';import { createServer } from 'node:net';import { spawn } from '../lib/childProcess.js';import { dataPath, readJSONFile, ensureDir, PATHS, atomicWrite } from '../lib/fileUtils.js';+import { killWithEscalation } from '../lib/killWithEscalation.js';import { createMutex } from '../lib/asyncMutex.js';import { isPortReachable } from '../lib/connectivity.js';import { peerFetch } from '../lib/peerHttpClient.js';@@ -444,7 +445,7 @@ export function stopForwardForPeer(peerId) {const entries = await readForwards();const entry = entries.find((f) => f.peerId === peerId);if (!entry) return;- killLiveForward(entry.id);+ await killLiveForward(entry.id);await deleteForward(entry.id);});}@@ -455,7 +456,7 @@ export function forgetTailcatForward(id, { removePeerFn = removeInstancePeer } =const entries = await readForwards();const entry = entries.find((f) => f.id === id);if (!entry) throw new ServerError('Tailcat forward not found', { status: 404 });- killLiveForward(id);+ await killLiveForward(id);await deleteForward(id);if (entry.peerId) {// stopTransport:false — this lifecycle operation already owns the child@@ -466,16 +467,42 @@ export function forgetTailcatForward(id, { removePeerFn = removeInstancePeer } =});}-function killLiveForward(id) {+async function killLiveForward(id) {const live = liveForwards.get(id);- if (live?.child && !live.child.killed) {- try {- live.child.kill('SIGTERM');- } catch {- // best-effort- }+ const child = live?.child;+ if (!child) return;+ // `killed` only means a signal was sent, not that the process released its port.+ if (child.exitCode == null && child.signalCode == null) {+ await new Promise((resolve, reject) => {+ let escalation;+ let settled = false;+ const finish = (error) => {+ settled = true;+ clearTimeout(escalation);+ clearTimeout(deadline);+ child.removeListener('exit', onExit);+ if (error) reject(error);+ else resolve();+ };+ const onExit = () => finish();+ const deadline = setTimeout(() => finish(new ServerError(+ 'Previous Tailcat forward did not exit; retry was not started',+ { status: 503, code: 'TAILCAT_STOP_TIMEOUT' }+ )), 16_000);+ child.once('exit', onExit);+ try {+ escalation = killWithEscalation(child, {+ label: 'Tailcat forward', stillRunning: () => liveForwards.get(id) === live,+ });+ if (settled) clearTimeout(escalation);+ } catch (error) {+ finish(error);+ }+ });}- liveForwards.delete(id);+ // A failed stop retains ownership so another retry cannot orphan this child.+ if (liveForwards.get(id) === live) liveForwards.delete(id);+ ownedChildren.delete(child);}/** Track a started child so shutdown and retry can find it again. */@@ -723,7 +750,7 @@ async function retryForward(id, {}// A live child on a stale mapping would keep the port and mask the retry.- killLiveForward(entry.id);+ await killLiveForward(entry.id);const peers = await getPeersFn();// Match the transport too, exactly as the boot-time restore does: a stale entrydiff --git a/server/services/tailcatPeer.test.js b/server/services/tailcatPeer.test.jsindex 4ab855724d..30fcac2c16 100644--- a/server/services/tailcatPeer.test.js+++ b/server/services/tailcatPeer.test.js@@ -504,6 +504,73 @@ describe('saved tailcat forwards', () => {expect(patches).toEqual([['fwd_1', expect.objectContaining({ peerId: 'peer-9', status: 'active', lastError: null })]]);});+ it('waits for process exit across concurrent retries, escalating even after a prior signal', async () => {+ vi.useFakeTimers();+ const child = fakeChild();+ child.exitCode = null;+ child.signalCode = null;+ child.kill.mockImplementation(() => { child.killed = true; return true; });+ readJSONFile.mockResolvedValue({ version: 1, forwards: [{+ id: 'fwd_1', peerId: 'peer-1', tcAddress: EXAMPLE_TC, localPort: 15555, remotePort: 5555,+ }] });+ const replacement = fakeChild();+ const startForward = vi.fn().mockResolvedValueOnce(child).mockResolvedValue(replacement);+ const options = {+ ensureInstalled: async () => ({ bin: 'tailcat' }),+ primeDerpMap: async () => null,+ allocatePort: vi.fn(async () => 15555), startForward,+ getPeersFn: async () => [{ id: 'peer-1', transport: 'tailcat', port: 15555 }],+ patchForwardEntry: async (id, patch) => ({ id, ...patch }),+ };+ try {+ await retryTailcatForward('fwd_1', options);+ child.kill('SIGTERM'); // A sent signal must never stand in for an exit.+ const retry = retryTailcatForward('fwd_1', options);+ const concurrentRetry = retryTailcatForward('fwd_1', options);+ await vi.advanceTimersByTimeAsync(8000);+ expect(child.kill).toHaveBeenLastCalledWith('SIGKILL');+ expect(startForward).toHaveBeenCalledTimes(1);+ expect(options.allocatePort).toHaveBeenCalledTimes(1);+ child.signalCode = 'SIGKILL';+ child.emit('exit', null, 'SIGKILL');+ await Promise.all([retry, concurrentRetry]);+ expect(startForward).toHaveBeenCalledTimes(3);+ expect(_liveForwardCountForTests()).toBe(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it('retains a child that will not exit and refuses to spawn a replacement', async () => {+ vi.useFakeTimers();+ const child = fakeChild();+ child.exitCode = null;+ child.signalCode = null;+ child.kill.mockImplementation(() => { child.killed = true; return true; });+ readJSONFile.mockResolvedValue({ version: 1, forwards: [{+ id: 'fwd_1', peerId: 'peer-1', tcAddress: EXAMPLE_TC, localPort: 15555, remotePort: 5555,+ }] });+ const startForward = vi.fn(async () => child);+ const options = {+ ensureInstalled: async () => ({ bin: 'tailcat' }), primeDerpMap: async () => null,+ allocatePort: async () => 15555, startForward,+ getPeersFn: async () => [{ id: 'peer-1', transport: 'tailcat', port: 15555 }],+ patchForwardEntry: async (id, patch) => ({ id, ...patch }),+ };+ try {+ await retryTailcatForward('fwd_1', options);+ const result = expect(retryTailcatForward('fwd_1', options))+ .rejects.toMatchObject({ code: 'TAILCAT_STOP_TIMEOUT' });+ await vi.advanceTimersByTimeAsync(16000);+ await result;+ expect(startForward).toHaveBeenCalledTimes(1);+ expect(_liveForwardCountForTests()).toBe(1);+ } finally {+ child.emit('exit', null, 'SIGKILL');+ vi.useRealTimers();+ }+ });+it('replaces a stale relay address without recreating its paired peer', async () => {const replacement = 'tcEXAMPLE' + 'B'.repeat(40);const savedPeer = { id: 'peer-1', transport: 'tailcat', port: 15555, syncSecret: 'example-pair-secret', syncCategories: { brain: true } };