дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-23 18:10:45 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
451e46a337 |
No files matched your search
@@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::{Condvar, Mutex, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Listing and lifecycle commands normally answer in well under a second; a
|
||||
@@ -315,9 +315,56 @@ pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContain
|
||||
parse_container_stats(&out).ok_or_else(|| IdeError::not_found("no container stats returned"))
|
||||
}
|
||||
|
||||
/// How long log lines collect before they are handed on together.
|
||||
const LOG_BATCH: Duration = Duration::from_millis(30);
|
||||
|
||||
/// Streams a container's logs (`tail` last lines, then follows while `follow`)
|
||||
/// until it ends or `cancel` fires.
|
||||
/// until it ends or `cancel` fires. Lines arrive in batches, at most one per
|
||||
/// [`LOG_BATCH`]: a webview delivers each IPC message on its own, so a message
|
||||
/// per line made a 1000-line tail take tens of seconds on Windows.
|
||||
pub fn logs(
|
||||
ep: &DockerEndpoint,
|
||||
id: &str,
|
||||
tail: u32,
|
||||
follow: bool,
|
||||
timestamps: bool,
|
||||
cancel: &CancellationToken,
|
||||
on_lines: &(dyn Fn(Vec<DockerLogLine>) + Sync),
|
||||
) -> IdeResult<()> {
|
||||
batched(LOG_BATCH, on_lines, |on_line| stream_logs(ep, id, tail, follow, timestamps, cancel, on_line))
|
||||
}
|
||||
|
||||
/// Runs `produce` with a per-item callback and hands the items to `emit` in order,
|
||||
/// collected over `every`, from a second thread so a quiet stream still flushes.
|
||||
fn batched<T: Send, R>(every: Duration, emit: &(dyn Fn(Vec<T>) + Sync), produce: impl FnOnce(&dyn Fn(T)) -> R) -> R {
|
||||
let pending = Mutex::new(Vec::new());
|
||||
let finished = (Mutex::new(false), Condvar::new());
|
||||
let flush = || {
|
||||
let items = std::mem::take(&mut *pending.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
if !items.is_empty() {
|
||||
emit(items);
|
||||
}
|
||||
};
|
||||
std::thread::scope(|scope| {
|
||||
scope.spawn(|| {
|
||||
let (done, wake) = &finished;
|
||||
let mut stop = done.lock().unwrap_or_else(|e| e.into_inner());
|
||||
loop {
|
||||
stop = wake.wait_timeout(stop, every).unwrap_or_else(|e| e.into_inner()).0;
|
||||
flush();
|
||||
if *stop {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let result = produce(&|item| pending.lock().unwrap_or_else(|e| e.into_inner()).push(item));
|
||||
*finished.0.lock().unwrap_or_else(|e| e.into_inner()) = true;
|
||||
finished.1.notify_one();
|
||||
result
|
||||
})
|
||||
}
|
||||
|
||||
fn stream_logs(
|
||||
ep: &DockerEndpoint,
|
||||
id: &str,
|
||||
tail: u32,
|
||||
@@ -606,6 +653,22 @@ pub fn cli(
|
||||
mod local_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn log_lines_arrive_in_order_as_few_batches() {
|
||||
let batches = Mutex::new(Vec::<Vec<u32>>::new());
|
||||
let result = batched(Duration::from_millis(30), &|b| batches.lock().unwrap().push(b), |line| {
|
||||
(0..1000).for_each(line);
|
||||
std::thread::sleep(Duration::from_millis(80));
|
||||
line(1000);
|
||||
"done"
|
||||
});
|
||||
assert_eq!(result, "done");
|
||||
let batches = batches.into_inner().unwrap();
|
||||
assert_eq!(batches.concat(), (0..=1000).collect::<Vec<_>>(), "every line once, in order");
|
||||
assert!(batches.len() <= 3, "a burst is one message, not one per line: {} batches", batches.len());
|
||||
assert_eq!(batches.last().unwrap(), &[1000], "a line after a quiet spell is flushed on its own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selected_context_overrides_docker_host() {
|
||||
let local = "unix:///var/run/docker.sock";
|
||||
|
||||
@@ -130,7 +130,7 @@ pub async fn docker_container_stats(
|
||||
blocking(move || ide_docker::container_stats(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// Streams a container's log lines until it stops or the request is cancelled.
|
||||
/// Streams a container's log lines, in batches, until it stops or the request is cancelled.
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -143,12 +143,12 @@ pub async fn docker_logs(
|
||||
tail: u32,
|
||||
follow: bool,
|
||||
timestamps: bool,
|
||||
on_line: Channel<DockerLogLine>,
|
||||
on_lines: Channel<Vec<DockerLogLine>>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(&state, endpoint).await?;
|
||||
cancellable(&state, request, move |cancel| {
|
||||
ide_docker::logs(&endpoint, &id, tail, follow, timestamps, cancel, &|line| {
|
||||
let _ = on_line.send(line);
|
||||
ide_docker::logs(&endpoint, &id, tail, follow, timestamps, cancel, &|lines| {
|
||||
let _ = on_lines.send(lines);
|
||||
})
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -599,8 +599,8 @@ export const commands = {
|
||||
dockerImageHistory: (endpoint: DockerEndpoint, id: string) => typedError<DockerImageLayer[], IdeError>(__TAURI_INVOKE("docker_image_history", { endpoint, id })),
|
||||
/** Pretty-printed `docker inspect` JSON. */
|
||||
dockerInspect: (endpoint: DockerEndpoint, object: DockerObject, id: string) => typedError<string, IdeError>(__TAURI_INVOKE("docker_inspect", { endpoint, object, id })),
|
||||
/** Streams a container's log lines until it stops or the request is cancelled. */
|
||||
dockerLogs: (request: RequestId, endpoint: DockerEndpoint, id: string, tail: number, follow: boolean, timestamps: boolean, onLine: Channel<DockerLogLine>) => typedError<null, IdeError>(__TAURI_INVOKE("docker_logs", { request, endpoint, id, tail, follow, timestamps, onLine })),
|
||||
/** Streams a container's log lines, in batches, until it stops or the request is cancelled. */
|
||||
dockerLogs: (request: RequestId, endpoint: DockerEndpoint, id: string, tail: number, follow: boolean, timestamps: boolean, onLines: Channel<DockerLogLine[]>) => typedError<null, IdeError>(__TAURI_INVOKE("docker_logs", { request, endpoint, id, tail, follow, timestamps, onLines })),
|
||||
dockerPrune: (request: RequestId, endpoint: DockerEndpoint, target: PruneTarget, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("docker_prune", { request, endpoint, target, onOutput })),
|
||||
/** `docker pull`, logging in first when a saved registry with a password serves the image. */
|
||||
dockerPull: (request: RequestId, endpoint: DockerEndpoint, reference: string, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("docker_pull", { request, endpoint, reference, onOutput })),
|
||||
|
||||
@@ -326,8 +326,8 @@ function LogView({ conn, container, running }: { conn: string; container: Docker
|
||||
ariaLabel={tx("Container log")}
|
||||
start={(onLine, onError, on) => {
|
||||
const request = nextRequestId();
|
||||
const channel = new Channel<DockerLogLine>();
|
||||
channel.onmessage = onLine;
|
||||
const channel = new Channel<DockerLogLine[]>();
|
||||
channel.onmessage = (lines) => lines.forEach(onLine);
|
||||
call(commands.dockerLogs(request, endpointOf(conn), id, 1000, running, on.has("timestamps"), channel)).catch(
|
||||
(e) => {
|
||||
if (!isCancelled(e)) onError(errorMessage(e));
|
||||
|
||||
@@ -398,10 +398,10 @@ function DockerLogEditorBody({ input, data }: { input: EditorInput; data: Docker
|
||||
};
|
||||
|
||||
const request = nextRequestId();
|
||||
const channel = new Channel<DockerLogLine>();
|
||||
channel.onmessage = (line) => {
|
||||
const channel = new Channel<DockerLogLine[]>();
|
||||
channel.onmessage = (lines) => {
|
||||
if (stopped) return;
|
||||
buffer.push(line.text.replace(ANSI, ""));
|
||||
for (const line of lines) buffer.push(line.text.replace(ANSI, ""));
|
||||
frame ||= requestAnimationFrame(flush);
|
||||
};
|
||||
call(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { LogPane, type LogLine } from "./LogPane";
|
||||
|
||||
type Push = (l: LogLine) => void;
|
||||
@@ -42,6 +43,7 @@ beforeEach(() => {
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
useProject.setState({ settings: null });
|
||||
});
|
||||
|
||||
describe("LogPane", () => {
|
||||
@@ -105,4 +107,35 @@ describe("LogPane", () => {
|
||||
unmount();
|
||||
expect(s.stops.at(0)).toHaveBeenCalled();
|
||||
});
|
||||
it("shows ANSI colours and log level colours instead of escape codes", () => {
|
||||
useProject.setState({ settings: { console: { logColors: { enabled: true } } } as never });
|
||||
const s = source();
|
||||
render(<LogPane start={s.start} sourceKey="a" live ariaLabel="Log" />);
|
||||
s.push("\x1b[32mstarted\x1b[0m on port 8080");
|
||||
s.push("2026-11-21 ERROR boom");
|
||||
runFrames();
|
||||
const log = screen.getByRole("log", { name: "Log" });
|
||||
expect(log.textContent).not.toContain("\x1b");
|
||||
expect(screen.getByText("started")).toHaveStyle({ color: "var(--ansi-green)" });
|
||||
expect(screen.getByText("2026-11-21 ERROR boom").closest("div")!.style.color).not.toBe("");
|
||||
});
|
||||
|
||||
it("stops following when scrolled up and follows again from Scroll to End", () => {
|
||||
const s = source();
|
||||
render(<LogPane start={s.start} sourceKey="a" live ariaLabel="Log" />);
|
||||
const end = screen.getByRole("button", { name: "Scroll to End" });
|
||||
expect(end).toHaveAttribute("aria-pressed", "true");
|
||||
const log = screen.getByRole("log", { name: "Log" });
|
||||
Object.defineProperty(log, "scrollHeight", { configurable: true, value: 1000 });
|
||||
Object.defineProperty(log, "clientHeight", { configurable: true, value: 100 });
|
||||
log.scrollTop = 200;
|
||||
fireEvent.scroll(log);
|
||||
expect(end).toHaveAttribute("aria-pressed", "false");
|
||||
s.push("more");
|
||||
runFrames();
|
||||
expect(log.scrollTop).toBe(200);
|
||||
fireEvent.click(end);
|
||||
expect(end).toHaveAttribute("aria-pressed", "true");
|
||||
expect(log.scrollTop).toBe(1000);
|
||||
});
|
||||
});
|
||||
+43
-11
@@ -1,7 +1,10 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { useWorkflowSettings } from "@/platform/workflowSettings";
|
||||
import { AnsiStream, spanStyle, stripAnsi, type Span } from "./ansi";
|
||||
import { IconButton } from "./Button";
|
||||
import { logLineColor } from "./logColors";
|
||||
import { Toggle } from "./Checkbox";
|
||||
import { copySelectionOnKeyDown } from "./selectableText";
|
||||
import styles from "./LogPane.module.css";
|
||||
@@ -36,10 +39,16 @@ export interface LogPaneProps {
|
||||
ariaLabel: string;
|
||||
}
|
||||
|
||||
const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g; // eslint-disable-line no-control-regex
|
||||
/** A line as shown: its ANSI-coloured spans and the plain text (level detection, copy). */
|
||||
interface ShownLine {
|
||||
stderr: boolean;
|
||||
text: string;
|
||||
spans: Span[];
|
||||
}
|
||||
|
||||
const MAX_LINES = 5000;
|
||||
|
||||
/** A followed log (container, program output) with toggles, Soft-wrap and Clear. */
|
||||
/** A followed log (container, program output) in ANSI and log level colours, with toggles, Soft-wrap, Scroll to End and Clear. */
|
||||
export function LogPane({ sourceKey, ...props }: LogPaneProps) {
|
||||
const [on, setOn] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const [wrap, setWrap] = useState(true);
|
||||
@@ -58,15 +67,20 @@ function LogStream(
|
||||
) {
|
||||
const tx = useTx();
|
||||
const { toggles = [], live, ariaLabel, on, setOn, wrap, setWrap } = props;
|
||||
const [lines, setLines] = useState<LogLine[]>([]);
|
||||
// As in the Run console: a line whose log level is recognised takes that level's colour.
|
||||
const levelColors = useWorkflowSettings((s) => s.console.logColors);
|
||||
const [lines, setLines] = useState<ShownLine[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [exit, setExit] = useState<number | null | undefined>(undefined);
|
||||
const scroller = useRef<HTMLDivElement>(null);
|
||||
const stick = useRef(true);
|
||||
// Scroll to End: follows new output; scrolling up turns it off, back to the end turns it on.
|
||||
const [follow, setFollow] = useState(true);
|
||||
const source = useRef({ start: props.start, on });
|
||||
|
||||
useEffect(() => {
|
||||
let buffer: LogLine[] = [];
|
||||
let buffer: ShownLine[] = [];
|
||||
// One parser per stream: a colour set on one line carries to the next of the same stream.
|
||||
const ansi = [new AnsiStream(), new AnsiStream()];
|
||||
let frame = 0;
|
||||
// Output that arrives after the stop (a source that already ran) is dropped.
|
||||
let stopped = false;
|
||||
@@ -82,7 +96,8 @@ function LogStream(
|
||||
const stop = source.current.start(
|
||||
(line) => {
|
||||
if (stopped) return;
|
||||
buffer.push({ stderr: line.stderr, text: line.text.replace(ANSI, "") });
|
||||
const spans = ansi[line.stderr ? 1 : 0]!.parse(line.text);
|
||||
buffer.push({ stderr: line.stderr, text: stripAnsi(line.text), spans });
|
||||
frame ||= requestAnimationFrame(flush);
|
||||
},
|
||||
(message) => !stopped && setError(message),
|
||||
@@ -102,8 +117,8 @@ function LogStream(
|
||||
|
||||
useEffect(() => {
|
||||
const el = scroller.current;
|
||||
if (el && stick.current) el.scrollTop = el.scrollHeight;
|
||||
}, [lines]);
|
||||
if (el && follow) el.scrollTop = el.scrollHeight;
|
||||
}, [lines, follow]);
|
||||
|
||||
const toggle = (id: string, checked: boolean) => {
|
||||
const next = new Set(on);
|
||||
@@ -121,6 +136,13 @@ function LogStream(
|
||||
<Toggle checked={wrap} onChange={setWrap} label="Soft-wrap" />
|
||||
<span className={styles.flex} />
|
||||
{props.actions}
|
||||
<IconButton
|
||||
icon="scroll-to-end"
|
||||
size="small"
|
||||
title="Scroll to End"
|
||||
pressed={follow}
|
||||
onClick={() => setFollow((v) => !v)}
|
||||
/>
|
||||
<IconButton icon="trash" size="small" title="Clear" onClick={() => setLines([])} />
|
||||
</div>
|
||||
<div
|
||||
@@ -132,12 +154,22 @@ function LogStream(
|
||||
aria-label={ariaLabel}
|
||||
onScroll={(e) => {
|
||||
const el = e.currentTarget;
|
||||
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
|
||||
setFollow(el.scrollHeight - el.scrollTop - el.clientHeight < 24);
|
||||
}}
|
||||
>
|
||||
{lines.map((l, i) => (
|
||||
<div key={i} className={clsx(l.stderr && styles.stderr)}>
|
||||
{l.text || " "}
|
||||
<div
|
||||
key={i}
|
||||
className={clsx(l.stderr && styles.stderr)}
|
||||
style={{ color: logLineColor(l.text, l.stderr ? "stderr" : "stdout", levelColors) }}
|
||||
>
|
||||
{l.spans.length
|
||||
? l.spans.map((span, j) => (
|
||||
<span key={j} style={spanStyle(span)}>
|
||||
{span.text}
|
||||
</span>
|
||||
))
|
||||
: " "}
|
||||
</div>
|
||||
))}
|
||||
{error && <div className={styles.stderr}>{error}</div>}
|
||||
|
||||
Reference in new issue
Заблокувати користувача