Skip to content

Commit 3765f7b

Browse files
authored
fix: shortcuts not rebound after server restart (#21166)
1 parent 5ef557a commit 3765f7b

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

packages/vite/src/node/__tests__/shortcuts.spec.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,4 +67,49 @@ describe('bindCLIShortcuts', () => {
6767
await server.close()
6868
}
6969
})
70+
71+
test('rebinds shortcuts after server restart', async () => {
72+
const server = await createServer()
73+
74+
try {
75+
const action = vi.fn()
76+
77+
bindCLIShortcuts(
78+
server,
79+
{
80+
customShortcuts: [{ key: 'x', description: 'test', action }],
81+
},
82+
true,
83+
)
84+
85+
// Verify shortcut works initially
86+
const initialReadline = server._rl
87+
88+
expect.assert(
89+
initialReadline,
90+
'The readline interface should be defined after binding shortcuts.',
91+
)
92+
93+
initialReadline.emit('line', 'x')
94+
95+
await vi.waitFor(() => expect(action).toHaveBeenCalledOnce())
96+
97+
// Restart the server
98+
action.mockClear()
99+
await server.restart()
100+
101+
const newReadline = server._rl
102+
103+
expect.assert(
104+
newReadline && newReadline !== initialReadline,
105+
'A new readline interface should be created after server restart.',
106+
)
107+
108+
// Shortcuts should still work after restart
109+
newReadline.emit('line', 'x')
110+
await vi.waitFor(() => expect(action).toHaveBeenCalledOnce())
111+
} finally {
112+
await server.close()
113+
}
114+
})
70115
})

packages/vite/src/node/server/index.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1252,6 +1252,8 @@ async function restartServer(server: ViteDevServer) {
12521252
const middlewares = server.middlewares
12531253
newServer._configServerPort = server._configServerPort
12541254
newServer._currentServerPort = server._currentServerPort
1255+
// Ensure the new server has no stale readline reference
1256+
newServer._rl = undefined
12551257
Object.assign(server, newServer)
12561258

12571259
// Keep the same connect instance so app.use(vite.middlewares) works
@@ -1278,7 +1280,12 @@ async function restartServer(server: ViteDevServer) {
12781280

12791281
if (shortcutsOptions) {
12801282
shortcutsOptions.print = false
1281-
bindCLIShortcuts(server, shortcutsOptions)
1283+
bindCLIShortcuts(
1284+
server,
1285+
shortcutsOptions,
1286+
// Skip environment checks since shortcuts were bound before restart
1287+
true,
1288+
)
12821289
}
12831290
}
12841291

0 commit comments

Comments
 (0)