Skip to content

Commit ff275fe

Browse files
committed
fix: sync terminal size with backend PTY, avoid connecting with placeholder container ID
Fixes Dokploy#5092 — typing in the database/docker terminal overwrote text instead of continuing on new lines. The xterm.js client never told the backend PTY its actual size (node-pty/ssh2 always defaulted to 80x24 and were never resized), so whenever the rendered terminal width differed from that, the remote shell's cursor math diverged from what the client displayed. - docker-container-terminal.ts / terminal.ts: pass the client's initial cols/rows into node-pty spawn and ssh2 exec/shell, and resize the PTY on a {type:"resize"} control message sent over the same ws channel. - docker-terminal.tsx / settings/web-server/terminal.tsx: send cols/rows on connect and on every term.onResize, and watch the container with a ResizeObserver to refit on dialog/window resize. Also fixes two related terminal/logs bugs surfaced while testing this: - docker-terminal.tsx no longer opens a connection with the "select-a-container" placeholder ID before a real container is selected, and defers terminal creation a frame so React StrictMode's dev-only phantom mount doesn't hit a known xterm.js dispose race (xtermjs/xterm.js#5011, "Cannot read properties of undefined (reading 'dimensions')"). - docker-logs-id.tsx (shared by application/compose/compose-stack logs) had the same placeholder-ID issue, surfacing Docker's raw "No such container: select-a-container" daemon error instead of a proper empty state.
1 parent ca578ed commit ff275fe

6 files changed

Lines changed: 219 additions & 63 deletions

File tree

‎apps/dokploy/components/dashboard/docker/logs/docker-logs-id.tsx‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ interface Props {
2626
serviceId?: string;
2727
}
2828

29+
// Sentinel the container-picker views fall back to before a real container
30+
// is selected/auto-selected — querying logs for it just surfaces Docker's
31+
// raw "No such container: select-a-container" daemon error.
32+
const PLACEHOLDER_CONTAINER_ID = "select-a-container";
33+
2934
export const priorities = [
3035
{
3136
label: "Info",
@@ -55,13 +60,16 @@ export const DockerLogsId: React.FC<Props> = ({
5560
runType,
5661
serviceId,
5762
}) => {
63+
const hasContainer =
64+
!!containerId && containerId !== PLACEHOLDER_CONTAINER_ID;
65+
5866
const { data } = api.docker.getConfig.useQuery(
5967
{
6068
containerId,
6169
serverId: serverId ?? undefined,
6270
},
6371
{
64-
enabled: !!containerId,
72+
enabled: hasContainer,
6573
},
6674
);
6775

@@ -134,7 +142,7 @@ export const DockerLogsId: React.FC<Props> = ({
134142
};
135143

136144
useEffect(() => {
137-
if (!containerId) return;
145+
if (!hasContainer) return;
138146

139147
let isCurrentConnection = true;
140148
let noDataTimeout: NodeJS.Timeout;
@@ -425,10 +433,15 @@ export const DockerLogsId: React.FC<Props> = ({
425433
<div className="flex justify-center items-center h-full text-muted-foreground">
426434
<Loader2 className="h-6 w-6 animate-spin" />
427435
</div>
428-
) : (
436+
) : hasContainer ? (
429437
<div className="flex justify-center items-center h-full text-muted-foreground">
430438
No logs found
431439
</div>
440+
) : (
441+
<div className="flex justify-center items-center h-full text-center text-sm text-muted-foreground px-8">
442+
Select a container above to view its logs. If none are listed,
443+
make sure the service is deployed and running.
444+
</div>
432445
)}
433446
</div>
434447
</div>

‎apps/dokploy/components/dashboard/docker/terminal/docker-terminal.tsx‎

Lines changed: 93 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ interface Props {
1515
serviceId?: string;
1616
}
1717

18+
// Sentinel the container-picker modal renders with before a real container
19+
// is selected/auto-selected — never worth opening a connection for.
20+
const PLACEHOLDER_CONTAINER_ID = "select-a-container";
21+
1822
export const DockerTerminal: React.FC<Props> = ({
1923
id,
2024
containerId,
@@ -25,59 +29,105 @@ export const DockerTerminal: React.FC<Props> = ({
2529
const [activeWay, setActiveWay] = React.useState<string | undefined>("bash");
2630
const { resolvedTheme } = useTheme();
2731
useEffect(() => {
28-
const container = document.getElementById(id);
29-
if (container) {
30-
container.innerHTML = "";
32+
if (!containerId || containerId === PLACEHOLDER_CONTAINER_ID) {
33+
return;
3134
}
32-
const term = new Terminal({
33-
cursorBlink: true,
34-
lineHeight: 1.4,
35-
convertEol: true,
36-
theme: {
37-
cursor: resolvedTheme === "light" ? "#000000" : "transparent",
38-
background: "rgba(0, 0, 0, 0)",
39-
foreground: "currentColor",
40-
},
41-
});
42-
const addonFit = new FitAddon();
43-
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
4435

45-
const wsUrl = `${protocol}//${window.location.host}/docker-container-terminal?containerId=${containerId}&activeWay=${activeWay}${serverId ? `&serverId=${serverId}` : ""}${serviceId ? `&serviceId=${serviceId}` : ""}`;
36+
let cancelled = false;
37+
let term: Terminal | null = null;
38+
let ws: WebSocket | null = null;
39+
let resizeObserver: ResizeObserver | null = null;
40+
41+
// Deferred a frame so React StrictMode's dev-only phantom mount+cleanup
42+
// (which runs synchronously, before anything paints) never creates a
43+
// terminal in the first place — dodges a known xterm.js dispose race
44+
// (xtermjs/xterm.js#5011) where a deferred internal callback outlives
45+
// term.dispose() and reads renderer state that's already gone.
46+
const frame = requestAnimationFrame(() => {
47+
if (cancelled) return;
48+
49+
const container = document.getElementById(id);
50+
if (container) {
51+
container.innerHTML = "";
52+
}
53+
term = new Terminal({
54+
cursorBlink: true,
55+
lineHeight: 1.4,
56+
convertEol: true,
57+
theme: {
58+
cursor: resolvedTheme === "light" ? "#000000" : "transparent",
59+
background: "rgba(0, 0, 0, 0)",
60+
foreground: "currentColor",
61+
},
62+
});
63+
const addonFit = new FitAddon();
64+
const clipboardAddon = new ClipboardAddon();
65+
term.loadAddon(clipboardAddon);
66+
fixMacOsAltKeys(term);
67+
// @ts-expect-error
68+
term.open(termRef.current);
69+
term.loadAddon(addonFit);
70+
addonFit.fit();
71+
72+
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
73+
const wsUrl = `${protocol}//${window.location.host}/docker-container-terminal?containerId=${containerId}&activeWay=${activeWay}&cols=${term.cols}&rows=${term.rows}${serverId ? `&serverId=${serverId}` : ""}${serviceId ? `&serviceId=${serviceId}` : ""}`;
4674

47-
const ws = new WebSocket(wsUrl);
75+
ws = new WebSocket(wsUrl);
76+
const addonAttach = new AttachAddon(ws);
77+
term.loadAddon(addonAttach);
78+
79+
const sendResize = (cols: number, rows: number) => {
80+
if (ws && ws.readyState === WebSocket.OPEN) {
81+
ws.send(JSON.stringify({ type: "resize", cols, rows }));
82+
}
83+
};
84+
term.onResize(({ cols, rows }) => sendResize(cols, rows));
85+
86+
resizeObserver = new ResizeObserver(() => addonFit.fit());
87+
if (termRef.current) {
88+
resizeObserver.observe(termRef.current);
89+
}
90+
});
4891

49-
const addonAttach = new AttachAddon(ws);
50-
const clipboardAddon = new ClipboardAddon();
51-
term.loadAddon(clipboardAddon);
52-
fixMacOsAltKeys(term);
53-
// @ts-ignore
54-
term.open(termRef.current);
55-
// @ts-ignore
56-
term.loadAddon(addonFit);
57-
term.loadAddon(addonAttach);
58-
addonFit.fit();
5992
return () => {
60-
ws.readyState === WebSocket.OPEN && ws.close();
61-
term.dispose();
93+
cancelled = true;
94+
cancelAnimationFrame(frame);
95+
resizeObserver?.disconnect();
96+
if (ws && ws.readyState === WebSocket.OPEN) {
97+
ws.close();
98+
}
99+
term?.dispose();
62100
};
63101
}, [containerId, activeWay, id]);
64102

103+
const hasContainer =
104+
!!containerId && containerId !== PLACEHOLDER_CONTAINER_ID;
105+
65106
return (
66107
<div className="flex flex-col gap-4">
67-
<div className="flex flex-col gap-2 mt-4">
68-
<span>
69-
Select way to connect to <b>{containerId}</b>
70-
</span>
71-
<Tabs value={activeWay} onValueChange={setActiveWay}>
72-
<TabsList>
73-
<TabsTrigger value="bash">Bash</TabsTrigger>
74-
<TabsTrigger value="sh">/bin/sh</TabsTrigger>
75-
</TabsList>
76-
</Tabs>
77-
</div>
78-
<div className="w-full h-full rounded-lg p-2 bg-transparent border">
79-
<div id={id} ref={termRef} />
80-
</div>
108+
{hasContainer && (
109+
<div className="flex flex-col gap-2 mt-4">
110+
<span>
111+
Select way to connect to <b>{containerId}</b>
112+
</span>
113+
<Tabs value={activeWay} onValueChange={setActiveWay}>
114+
<TabsList>
115+
<TabsTrigger value="bash">Bash</TabsTrigger>
116+
<TabsTrigger value="sh">/bin/sh</TabsTrigger>
117+
</TabsList>
118+
</Tabs>
119+
</div>
120+
)}
121+
{hasContainer ? (
122+
<div className="w-full h-[420px] rounded-lg p-2 bg-transparent border">
123+
<div id={id} ref={termRef} className="h-full" />
124+
</div>
125+
) : (
126+
<div className="flex h-[420px] w-full items-center justify-center rounded-lg border border-dashed p-4 text-center text-sm text-muted-foreground">
127+
Select a container above to open a terminal. If none are listed, make
128+
sure the service is deployed and running.
129+
</div>
130+
)}
81131
</div>
82132
);
83133
};

‎apps/dokploy/components/dashboard/settings/web-server/terminal.tsx‎

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,22 @@ export const Terminal: React.FC<Props> = ({ id, serverId }) => {
4141
});
4242

4343
const addonFit = new FitAddon();
44+
const clipboardAddon = new ClipboardAddon();
45+
term.loadAddon(clipboardAddon);
46+
fixMacOsAltKeys(term);
47+
48+
// @ts-ignore
49+
term.open(termRef.current);
50+
// @ts-ignore
51+
term.loadAddon(addonFit);
52+
addonFit.fit();
4453

4554
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
4655

4756
const urlParams = new URLSearchParams();
4857
urlParams.set("serverId", serverId);
58+
urlParams.set("cols", term.cols.toString());
59+
urlParams.set("rows", term.rows.toString());
4960

5061
if (serverId === "local") {
5162
const { port, username } = getLocalServerData();
@@ -57,17 +68,22 @@ export const Terminal: React.FC<Props> = ({ id, serverId }) => {
5768

5869
const ws = new WebSocket(wsUrl);
5970
const addonAttach = new AttachAddon(ws);
60-
const clipboardAddon = new ClipboardAddon();
61-
term.loadAddon(clipboardAddon);
62-
fixMacOsAltKeys(term);
63-
64-
// @ts-ignore
65-
term.open(termRef.current);
66-
// @ts-ignore
67-
term.loadAddon(addonFit);
6871
term.loadAddon(addonAttach);
69-
addonFit.fit();
72+
73+
const sendResize = (cols: number, rows: number) => {
74+
if (ws.readyState === WebSocket.OPEN) {
75+
ws.send(JSON.stringify({ type: "resize", cols, rows }));
76+
}
77+
};
78+
term.onResize(({ cols, rows }) => sendResize(cols, rows));
79+
80+
const resizeObserver = new ResizeObserver(() => addonFit.fit());
81+
if (termRef.current) {
82+
resizeObserver.observe(termRef.current);
83+
}
84+
7085
return () => {
86+
resizeObserver.disconnect();
7187
ws.readyState === WebSocket.OPEN && ws.close();
7288
};
7389
}, [id, serverId]);

‎apps/dokploy/server/wss/docker-container-terminal.ts‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@ import { spawn } from "node-pty";
44
import { Client } from "ssh2";
55
import { WebSocketServer } from "ws";
66
import { canAccessDockerOverWss } from "./authorize";
7-
import { isValidContainerId, isValidShell } from "./utils";
7+
import {
8+
isValidContainerId,
9+
isValidShell,
10+
parseResizeMessage,
11+
parseTerminalSize,
12+
} from "./utils";
813

914
export const setupDockerContainerTerminalWebSocketServer = (
1015
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>,
@@ -34,6 +39,10 @@ export const setupDockerContainerTerminalWebSocketServer = (
3439
const activeWay = url.searchParams.get("activeWay");
3540
const serverId = url.searchParams.get("serverId");
3641
const serviceId = url.searchParams.get("serviceId");
42+
const { cols, rows } = parseTerminalSize(
43+
url.searchParams.get("cols"),
44+
url.searchParams.get("rows"),
45+
);
3746
const { user, session } = await validateRequest(req);
3847

3948
if (!containerId) {
@@ -92,7 +101,7 @@ export const setupDockerContainerTerminalWebSocketServer = (
92101
containerId,
93102
shell,
94103
].join(" ");
95-
conn.exec(dockerCommand, { pty: true }, (err, stream) => {
104+
conn.exec(dockerCommand, { pty: { cols, rows } }, (err, stream) => {
96105
if (err) {
97106
console.error("SSH exec error:", err);
98107
ws.close();
@@ -123,7 +132,13 @@ export const setupDockerContainerTerminalWebSocketServer = (
123132
} else {
124133
command = message;
125134
}
126-
stream.write(command.toString());
135+
const text = command.toString();
136+
const resize = parseResizeMessage(text);
137+
if (resize) {
138+
stream.setWindow(resize.rows, resize.cols, 0, 0);
139+
return;
140+
}
141+
stream.write(text);
127142
} catch (error) {
128143
// @ts-ignore
129144
const errorMessage = error?.message as unknown as string;
@@ -161,7 +176,7 @@ export const setupDockerContainerTerminalWebSocketServer = (
161176
const ptyProcess = spawn(
162177
"docker",
163178
["exec", "-it", "-w", "/", containerId, shell],
164-
{},
179+
{ cols, rows },
165180
);
166181

167182
ptyProcess.onData((data) => {
@@ -178,7 +193,13 @@ export const setupDockerContainerTerminalWebSocketServer = (
178193
} else {
179194
command = message;
180195
}
181-
ptyProcess.write(command.toString());
196+
const text = command.toString();
197+
const resize = parseResizeMessage(text);
198+
if (resize) {
199+
ptyProcess.resize(resize.cols, resize.rows);
200+
return;
201+
}
202+
ptyProcess.write(text);
182203
} catch (error) {
183204
// @ts-ignore
184205
const errorMessage = error?.message as unknown as string;

‎apps/dokploy/server/wss/terminal.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,11 @@ import { Client, type ConnectConfig } from "ssh2";
1010
import { WebSocketServer } from "ws";
1111
import { getDockerHost } from "../utils/docker";
1212
import { canAccessTerminalOverWss } from "./authorize";
13-
import { setupLocalServerSSHKey } from "./utils";
13+
import {
14+
parseResizeMessage,
15+
parseTerminalSize,
16+
setupLocalServerSSHKey,
17+
} from "./utils";
1418

1519
const COMMAND_TO_ALLOW_LOCAL_ACCESS = `
1620
# ----------------------------------------
@@ -88,6 +92,10 @@ export const setupTerminalWebSocketServer = (
8892
wssTerm.on("connection", async (ws, req) => {
8993
const url = new URL(req.url || "", `http://${req.headers.host}`);
9094
const serverId = url.searchParams.get("serverId");
95+
const { cols, rows } = parseTerminalSize(
96+
url.searchParams.get("cols"),
97+
url.searchParams.get("rows"),
98+
);
9199
const { user, session } = await validateRequest(req);
92100
if (!user || !session || !serverId) {
93101
ws.close();
@@ -190,7 +198,7 @@ export const setupTerminalWebSocketServer = (
190198
// Clear terminal content once connected
191199
ws.send("\x1bc");
192200

193-
conn.shell({}, (err, stream) => {
201+
conn.shell({ cols, rows }, (err, stream) => {
194202
if (err) throw err;
195203

196204
stream
@@ -216,7 +224,13 @@ export const setupTerminalWebSocketServer = (
216224
} else {
217225
command = message;
218226
}
219-
stream.write(command.toString());
227+
const text = command.toString();
228+
const resize = parseResizeMessage(text);
229+
if (resize) {
230+
stream.setWindow(resize.rows, resize.cols, 0, 0);
231+
return;
232+
}
233+
stream.write(text);
220234
} catch (error) {
221235
// @ts-ignore
222236
const errorMessage = error?.message as unknown as string;

0 commit comments

Comments
 (0)