-
-
Notifications
You must be signed in to change notification settings - Fork 80.8k
Expand file tree
/
Copy pathwindows-task-restart.test.ts
More file actions
241 lines (211 loc) · 9.06 KB
/
Copy pathwindows-task-restart.test.ts
File metadata and controls
241 lines (211 loc) · 9.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Covers Windows scheduled-task gateway restart script generation.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { captureFullEnv } from "../test-utils/env.js";
import { getWindowsCmdExePath } from "./windows-install-roots.js";
const spawnMock = vi.hoisted(() => vi.fn());
const resolvePreferredOpenClawTmpDirMock = vi.hoisted(() => vi.fn(() => os.tmpdir()));
const resolveTaskScriptPathMock = vi.hoisted(() =>
vi.fn((env: Record<string, string | undefined>) => {
const home = env.USERPROFILE || env.HOME || os.homedir();
return path.join(home, ".openclaw", "gateway.cmd");
}),
);
vi.mock("node:child_process", async () => {
const { mockNodeBuiltinModule } = await import("openclaw/plugin-sdk/test-node-mocks");
return mockNodeBuiltinModule(
() => vi.importActual<typeof import("node:child_process")>("node:child_process"),
{
spawn: (...args: unknown[]) => spawnMock(...args),
},
);
});
vi.mock("./tmp-openclaw-dir.js", () => ({
resolvePreferredOpenClawTmpDir: () => resolvePreferredOpenClawTmpDirMock(),
}));
vi.mock("../daemon/schtasks.js", () => ({
resolveTaskScriptPath: (env: Record<string, string | undefined>) =>
resolveTaskScriptPathMock(env),
}));
type WindowsTaskRestartModule = typeof import("./windows-task-restart.js");
let relaunchGatewayScheduledTask: WindowsTaskRestartModule["relaunchGatewayScheduledTask"];
const envSnapshot = captureFullEnv();
const createdScriptPaths = new Set<string>();
const createdTmpDirs = new Set<string>();
function decodeCmdPathArg(value: string): string {
const trimmed = value.trim();
const withoutQuotes =
trimmed.startsWith('"') && trimmed.endsWith('"') ? trimmed.slice(1, -1) : trimmed;
return withoutQuotes.replace(/\^!/g, "!").replace(/%%/g, "%");
}
function requireFirstMockCall<T>(mock: { mock: { calls: T[][] } }, label: string): T[] {
const call = mock.mock.calls[0];
if (!call) {
throw new Error(`expected ${label} call`);
}
return call;
}
afterEach(() => {
envSnapshot.restore();
for (const scriptPath of createdScriptPaths) {
try {
fs.unlinkSync(scriptPath);
} catch {
// Best-effort cleanup for temp helper scripts created in tests.
}
}
createdScriptPaths.clear();
for (const tmpDir of createdTmpDirs) {
try {
fs.rmSync(tmpDir, { recursive: true, force: true });
} catch {
// Best-effort cleanup for test temp roots.
}
}
createdTmpDirs.clear();
});
describe("relaunchGatewayScheduledTask", () => {
beforeAll(async () => {
({ relaunchGatewayScheduledTask } = await import("./windows-task-restart.js"));
});
beforeEach(() => {
spawnMock.mockReset();
resolvePreferredOpenClawTmpDirMock.mockReset();
resolvePreferredOpenClawTmpDirMock.mockReturnValue(os.tmpdir());
resolveTaskScriptPathMock.mockReset();
resolveTaskScriptPathMock.mockImplementation((env: Record<string, string | undefined>) => {
const home = env.USERPROFILE || env.HOME || os.homedir();
return path.join(home, ".openclaw", "gateway.cmd");
});
});
it("writes a detached schtasks relaunch helper", () => {
const unref = vi.fn();
let seenCommandArg = "";
spawnMock.mockImplementation((_file: string, args: string[]) => {
seenCommandArg = args[3];
createdScriptPaths.add(decodeCmdPathArg(args[3]));
return { unref };
});
const result = relaunchGatewayScheduledTask({ OPENCLAW_PROFILE: "work" });
const cmdExePath = getWindowsCmdExePath();
expect(result.ok).toBe(true);
expect(result.method).toBe("schtasks");
expect(result.tried).toContain('schtasks /Run /TN "OpenClaw Gateway (work)"');
expect(result.tried).toContain(`${cmdExePath} /d /s /c ${seenCommandArg}`);
const spawnCall = requireFirstMockCall(spawnMock, "restart helper spawn");
expect(spawnCall[0]).toBe(cmdExePath);
expect(spawnCall[1]).toStrictEqual(["/d", "/s", "/c", seenCommandArg]);
expect(spawnCall[2]).toStrictEqual({
detached: true,
stdio: "ignore",
windowsHide: true,
});
expect(unref).toHaveBeenCalledOnce();
const scriptPath = [...createdScriptPaths][0];
if (scriptPath === undefined) {
throw new Error("expected restart helper script path");
}
expect(fs.statSync(scriptPath).isFile()).toBe(true);
const script = fs.readFileSync(scriptPath, "utf8");
expect(script).toContain("timeout /t 1 /nobreak >nul");
expect(script).toContain("gateway-restart.log");
expect(script).toContain(
'openclaw restart attempt source=windows-task-handoff target="OpenClaw Gateway (work)"',
);
expect(script).toContain(
`powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "$task = Get-ScheduledTask -TaskName 'OpenClaw Gateway (work)' -ErrorAction SilentlyContinue; if ($null -ne $task -and $task.State -eq 'Running') { exit 0 }; exit 1" >nul 2>&1`,
);
expect(script).not.toContain("findstr");
expect(script).toContain('schtasks /Run /TN "OpenClaw Gateway (work)" >>');
expect(script.indexOf("powershell.exe -NoProfile")).toBeLessThan(
script.indexOf('schtasks /Run /TN "OpenClaw Gateway (work)"'),
);
expect(script).toContain('del "%~f0" >nul 2>&1');
});
it("prefers OPENCLAW_WINDOWS_TASK_NAME overrides", () => {
spawnMock.mockImplementation((_file: string, args: string[]) => {
createdScriptPaths.add(decodeCmdPathArg(args[3]));
return { unref: vi.fn() };
});
relaunchGatewayScheduledTask({
OPENCLAW_PROFILE: "work",
OPENCLAW_WINDOWS_TASK_NAME: "OpenClaw Gateway (custom)",
});
const scriptPath = [...createdScriptPaths][0];
const script = fs.readFileSync(scriptPath, "utf8");
expect(script).toContain('schtasks /Run /TN "OpenClaw Gateway (custom)" >>');
});
it("escapes custom task names in the PowerShell running-task probe", () => {
spawnMock.mockImplementation((_file: string, args: string[]) => {
createdScriptPaths.add(decodeCmdPathArg(args[3]));
return { unref: vi.fn() };
});
relaunchGatewayScheduledTask({
OPENCLAW_WINDOWS_TASK_NAME: "OpenClaw Gateway (Bob's work)",
});
const scriptPath = [...createdScriptPaths][0];
const script = fs.readFileSync(scriptPath, "utf8");
expect(script).toContain(
`-Command "$task = Get-ScheduledTask -TaskName 'OpenClaw Gateway (Bob''s work)' -ErrorAction SilentlyContinue; if ($null -ne $task -and $task.State -eq 'Running') { exit 0 }; exit 1"`,
);
expect(script).not.toContain("findstr");
});
it("returns failed when the helper cannot be spawned", () => {
spawnMock.mockImplementation(() => {
throw new Error("spawn failed");
});
const result = relaunchGatewayScheduledTask({ OPENCLAW_PROFILE: "work" });
expect(result.ok).toBe(false);
expect(result.method).toBe("schtasks");
expect(result.detail).toContain("spawn failed");
});
it("quotes the cmd /c script path when temp paths contain metacharacters", () => {
const unref = vi.fn();
const metacharTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw&(restart)-"));
createdTmpDirs.add(metacharTmpDir);
resolvePreferredOpenClawTmpDirMock.mockReturnValue(metacharTmpDir);
spawnMock.mockReturnValue({ unref });
relaunchGatewayScheduledTask({ OPENCLAW_PROFILE: "work" });
expect(spawnMock).toHaveBeenCalledOnce();
const spawnCall = requireFirstMockCall(spawnMock, "restart helper spawn");
const commandArgs = spawnCall[1];
if (!Array.isArray(commandArgs)) {
throw new Error("expected cmd.exe argument array");
}
const commandArg = commandArgs[3];
if (typeof commandArg !== "string") {
throw new Error("expected quoted restart helper path");
}
expect(spawnCall[0]).toBe(getWindowsCmdExePath());
expect(commandArgs).toStrictEqual(["/d", "/s", "/c", commandArg]);
expect(commandArg.startsWith('"')).toBe(true);
expect(commandArg.endsWith('"')).toBe(true);
expect(commandArg).toContain("&");
expect(spawnCall[2]).toStrictEqual({
detached: true,
stdio: "ignore",
windowsHide: true,
});
});
it("includes startup fallback", () => {
const taskScriptDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-state-"));
createdTmpDirs.add(taskScriptDir);
const taskScriptPath = path.join(taskScriptDir, "gateway.cmd");
fs.writeFileSync(taskScriptPath, "@echo off\r\nrem placeholder\r\n", "utf8");
resolveTaskScriptPathMock.mockReturnValue(taskScriptPath);
spawnMock.mockImplementation((_file: string, args: string[]) => {
createdScriptPaths.add(decodeCmdPathArg(args[3]));
return { unref: vi.fn() };
});
const result = relaunchGatewayScheduledTask({ OPENCLAW_PROFILE: "work" });
expect(result.ok).toBe(true);
const scriptPath = [...createdScriptPaths][0];
const script = fs.readFileSync(scriptPath, "utf8");
expect(script).toContain(`schtasks /Query /TN`);
expect(script).toContain(":fallback");
expect(script).toContain(`start "" /min ${getWindowsCmdExePath()} /d /c`);
expect(script).toContain(taskScriptPath);
});
});