diff --git a/.impeccable/config.json b/.impeccable/config.json
new file mode 100644
index 0000000000..1950c4da5c
--- /dev/null
+++ b/.impeccable/config.json
@@ -0,0 +1,15 @@
+{
+ "detector": {
+ "ignoreRules": [],
+ "ignoreFiles": [],
+ "ignoreValues": [
+ {
+ "rule": "gradient-text",
+ "value": "*",
+ "files": ["src/features/agents/Session.module.css"],
+ "createdAt": "2026-11-24T14:58:12.514Z",
+ "reason": "agent: .shimmer is an animated in-progress sweep on running-step labels (commit 18b286e7e, comment documents intent), not decorative gradient text"
+ }
+ ]
+ }
+}
diff --git a/.impeccable/design.json b/.impeccable/design.json
new file mode 100644
index 0000000000..92277b928d
--- /dev/null
+++ b/.impeccable/design.json
@@ -0,0 +1,557 @@
+{
+ "schemaVersion": 2,
+ "generatedAt": "2026-11-24T15:06:05+00:00",
+ "title": "Design System: OpenIDEA",
+ "extensions": {
+ "colorMeta": {
+ "workbench-blue": {
+ "role": "primary",
+ "displayName": "Workbench Blue",
+ "canonical": "#3871e1",
+ "tonalRamp": [
+ "oklch(15% 0.073 262)",
+ "oklch(25% 0.121 262)",
+ "oklch(35% 0.17 262)",
+ "oklch(48% 0.17 262)",
+ "oklch(60% 0.17 262)",
+ "oklch(72% 0.136 262)",
+ "oklch(84% 0.078 262)",
+ "oklch(95% 0.024 262)"
+ ]
+ },
+ "link-blue": {
+ "role": "primary",
+ "displayName": "Link Blue",
+ "canonical": "#2f5eb9",
+ "tonalRamp": [
+ "oklch(15% 0.064 262)",
+ "oklch(25% 0.107 262)",
+ "oklch(35% 0.15 262)",
+ "oklch(48% 0.15 262)",
+ "oklch(60% 0.15 262)",
+ "oklch(72% 0.12 262)",
+ "oklch(84% 0.069 262)",
+ "oklch(95% 0.021 262)"
+ ]
+ },
+ "selection-wash": {
+ "role": "primary",
+ "displayName": "Selection Wash",
+ "canonical": "#d0dffe",
+ "tonalRamp": [
+ "oklch(15% 0.034 262)",
+ "oklch(25% 0.057 262)",
+ "oklch(35% 0.08 262)",
+ "oklch(48% 0.08 262)",
+ "oklch(60% 0.08 262)",
+ "oklch(72% 0.064 262)",
+ "oklch(84% 0.037 262)",
+ "oklch(95% 0.011 262)"
+ ]
+ },
+ "tab-wash": {
+ "role": "primary",
+ "displayName": "Tab Wash",
+ "canonical": "#e3ebfe",
+ "tonalRamp": [
+ "oklch(15% 0.026 262)",
+ "oklch(25% 0.043 262)",
+ "oklch(35% 0.06 262)",
+ "oklch(48% 0.06 262)",
+ "oklch(60% 0.06 262)",
+ "oklch(72% 0.048 262)",
+ "oklch(84% 0.027 262)",
+ "oklch(95% 0.009 262)"
+ ]
+ },
+ "danger": {
+ "role": "status",
+ "displayName": "Danger",
+ "canonical": "#c54e58",
+ "tonalRamp": [
+ "oklch(15% 0.064 18)",
+ "oklch(25% 0.107 18)",
+ "oklch(35% 0.15 18)",
+ "oklch(48% 0.15 18)",
+ "oklch(60% 0.15 18)",
+ "oklch(72% 0.12 18)",
+ "oklch(84% 0.069 18)",
+ "oklch(95% 0.021 18)"
+ ]
+ },
+ "warning": {
+ "role": "status",
+ "displayName": "Warning",
+ "canonical": "#a56906",
+ "tonalRamp": [
+ "oklch(15% 0.056 70)",
+ "oklch(25% 0.093 70)",
+ "oklch(35% 0.13 70)",
+ "oklch(48% 0.13 70)",
+ "oklch(60% 0.13 70)",
+ "oklch(72% 0.104 70)",
+ "oklch(84% 0.059 70)",
+ "oklch(95% 0.019 70)"
+ ]
+ },
+ "success": {
+ "role": "status",
+ "displayName": "Success",
+ "canonical": "#338555",
+ "tonalRamp": [
+ "oklch(15% 0.047 152)",
+ "oklch(25% 0.079 152)",
+ "oklch(35% 0.11 152)",
+ "oklch(48% 0.11 152)",
+ "oklch(60% 0.11 152)",
+ "oklch(72% 0.088 152)",
+ "oklch(84% 0.05 152)",
+ "oklch(95% 0.016 152)"
+ ]
+ },
+ "frame-grey": {
+ "role": "neutral",
+ "displayName": "Frame Grey",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "island-white": {
+ "role": "neutral",
+ "displayName": "Island White",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "raised-paper": {
+ "role": "neutral",
+ "displayName": "Raised Paper",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "ink": {
+ "role": "neutral",
+ "displayName": "Ink",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "ink-secondary": {
+ "role": "neutral",
+ "displayName": "Ink Secondary",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "ink-muted": {
+ "role": "neutral",
+ "displayName": "Ink Muted",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "ink-faint": {
+ "role": "neutral",
+ "displayName": "Ink Faint",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "hairline": {
+ "role": "neutral",
+ "displayName": "Hairline",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "control-edge": {
+ "role": "neutral",
+ "displayName": "Control Edge",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "frame-grey-dark": {
+ "role": "neutral",
+ "displayName": "Frame Grey (Dark)",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "island-dark": {
+ "role": "neutral",
+ "displayName": "Island (Dark)",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "ink-dark": {
+ "role": "neutral",
+ "displayName": "Ink (Dark)",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "ink-strong-dark": {
+ "role": "neutral",
+ "displayName": "Ink Strong (Dark)",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "ink-muted-dark": {
+ "role": "neutral",
+ "displayName": "Ink Muted (Dark)",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "control-edge-dark": {
+ "role": "neutral",
+ "displayName": "Control Edge (Dark)",
+ "tonalRamp": [
+ "oklch(15% 0.005 265)",
+ "oklch(25% 0.009 265)",
+ "oklch(35% 0.012 265)",
+ "oklch(48% 0.012 265)",
+ "oklch(60% 0.012 265)",
+ "oklch(72% 0.01 265)",
+ "oklch(84% 0.005 265)",
+ "oklch(95% 0.002 265)"
+ ]
+ },
+ "selection-wash-dark": {
+ "role": "primary",
+ "displayName": "Selection Wash (Dark)",
+ "canonical": "#2a4371",
+ "tonalRamp": [
+ "oklch(15% 0.034 262)",
+ "oklch(25% 0.057 262)",
+ "oklch(35% 0.08 262)",
+ "oklch(48% 0.08 262)",
+ "oklch(60% 0.08 262)",
+ "oklch(72% 0.064 262)",
+ "oklch(84% 0.037 262)",
+ "oklch(95% 0.011 262)"
+ ]
+ }
+ },
+ "typographyMeta": {
+ "title": {
+ "displayName": "Title",
+ "purpose": "Tool window titles, section headers, dialog titles; weight 600 is the main emphasis."
+ },
+ "body": {
+ "displayName": "Body",
+ "purpose": "Default UI text, menus, rows, buttons."
+ },
+ "label": {
+ "displayName": "Label",
+ "purpose": "Secondary metadata, chips, status bar, table cells; the most-used size."
+ },
+ "label-tiny": {
+ "displayName": "Label Tiny",
+ "purpose": "Stripe labels, counters, badges."
+ },
+ "input-large": {
+ "displayName": "Input Large",
+ "purpose": "Search Everywhere and other large query fields."
+ },
+ "code": {
+ "displayName": "Code",
+ "purpose": "Editor, console, terminal and every monospace preview; size and weights are user settings."
+ }
+ },
+ "shadows": [
+ {
+ "name": "shadow-popup",
+ "value": "0 6px 20px rgba(0, 0, 0, 0.12)",
+ "purpose": "Popups, menus, completion, floating toolbar (Light; Dark uses 0.45 alpha)."
+ },
+ {
+ "name": "shadow-dialog",
+ "value": "0 0 0 0.5px rgba(0, 0, 0, 0.1), 0 10px 24px rgba(0, 0, 0, 0.1), 0 24px 72px rgba(0, 0, 0, 0.2)",
+ "purpose": "Window-style shadow for dialogs (Light)."
+ },
+ {
+ "name": "shadow-tooltip",
+ "value": "0 4px 12px rgba(0, 0, 0, 0.12)",
+ "purpose": "Hover tooltips (Light)."
+ },
+ {
+ "name": "shadow-balloon",
+ "value": "0 8px 24px rgba(0, 0, 0, 0.14)",
+ "purpose": "Notification balloons (Light)."
+ }
+ ],
+ "motion": [
+ {
+ "name": "ease",
+ "value": "cubic-bezier(0.2, 0, 0, 1)",
+ "purpose": "Default easing for every state transition."
+ },
+ {
+ "name": "dur-fast",
+ "value": "80ms",
+ "purpose": "Hover, press and focus changes on controls."
+ },
+ {
+ "name": "dur",
+ "value": "140ms",
+ "purpose": "Standard transitions such as popup fades."
+ },
+ {
+ "name": "dur-slow",
+ "value": "220ms",
+ "purpose": "Upper bound for any state transition."
+ }
+ ],
+ "density": [
+ {
+ "name": "default",
+ "value": "rows 24px, fields/buttons 28px, titlebar 40px, tab bar 38px, status bar 30px, island gap 6px, island radius 10px"
+ },
+ {
+ "name": "compact",
+ "value": "rows 22px, fields/buttons 24px, titlebar/headers 32px, tab bar 32px, status bar 24px, island gap 4px, island radius 8px, chrome text -1px"
+ }
+ ]
+ },
+ "components": [
+ {
+ "name": "Primary Button",
+ "kind": "button",
+ "refersTo": "button-primary",
+ "description": "The one default action in a dialog or form.",
+ "html": "OK ",
+ "css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-primary { background:var(--bg-button-primary,#3871e1); color:var(--fg-button-primary,#fff); } .ds-btn-primary:hover { background:var(--bg-button-primary-hover,#3366cc); }"
+ },
+ {
+ "name": "Secondary Button",
+ "kind": "button",
+ "refersTo": "button-secondary",
+ "description": "Every other dialog action: Cancel, Apply, Browse.",
+ "html": "Cancel ",
+ "css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-secondary { background:var(--bg-button,#fff); color:var(--fg-strong,#000); box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); } .ds-btn-secondary:hover { background:color-mix(in srgb, var(--bg-button,#fff) 94%, var(--fg-strong,#000)); }"
+ },
+ {
+ "name": "Ghost Button",
+ "kind": "button",
+ "refersTo": "button-ghost",
+ "description": "Low-emphasis text actions in headers and inline rows.",
+ "html": "Show all ",
+ "css": ".ds-btn-ghost { display:inline-flex; align-items:center; height:var(--h-button,28px); padding:0 8px; border:0; background:transparent; border-radius:var(--radius-control,4px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-ui,13px); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-btn-ghost:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-btn-ghost:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-btn-ghost:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; }"
+ },
+ {
+ "name": "Toolbar Icon Button",
+ "kind": "button",
+ "refersTo": "icon-button",
+ "description": "Toolbar and tool window header actions; frameless at rest, toggles show Selection Wash.",
+ "html": "
",
+ "css": ".ds-iconbar { display:flex; gap:2px; } .ds-icon-btn { display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; padding:0; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-muted,#6c707e); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-icon-btn:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-icon-btn:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-icon-btn[aria-pressed=\"true\"] { background:var(--bg-toolbar-selected,#d0dffe); color:var(--fg-strong,#000); } .ds-icon-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
+ },
+ {
+ "name": "Text Field",
+ "kind": "input",
+ "refersTo": "input",
+ "description": "Framed text field; the frame doubles in Workbench Blue on focus.",
+ "html": " ",
+ "css": ".ds-input { height:var(--h-field,28px); padding:0 8px; border:0; appearance:none; border-radius:var(--radius-control,4px); background:var(--bg-field,#fff); color:var(--fg-strong,#000); font-family:var(--font-ui); font-size:var(--fs-ui,13px); outline:none; box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); transition:box-shadow var(--dur-fast,80ms) var(--ease); } .ds-input::placeholder { color:var(--fg-faint,#9fa2a8); } .ds-input:focus { box-shadow:inset 0 0 0 1px var(--focus-ring,#3871e1), 0 0 0 1px var(--focus-ring,#3871e1); }"
+ },
+ {
+ "name": "Chip",
+ "kind": "chip",
+ "refersTo": "chip",
+ "description": "Flat read-only fact or picker trigger, sized like the toolbar widgets.",
+ "html": "main ",
+ "css": ".ds-chip { display:inline-flex; align-items:center; gap:var(--space-1,4px); height:22px; padding:0 6px; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-small,12px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease); } .ds-chip svg { color:var(--fg-muted,#6c707e); } .ds-chip:hover { background:var(--bg-toolbar-hover,#00000012); } .ds-chip:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
+ },
+ {
+ "name": "Tree Rows",
+ "kind": "custom",
+ "refersTo": "list-row-selected",
+ "description": "24px rows with an inset rounded selection wash; unfocused selection turns neutral.",
+ "html": "",
+ "css": ".ds-tree { width:220px; padding:4px var(--tree-inset,6px); background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); color:var(--fg,#000); outline:none; } .ds-row { height:var(--h-row,24px); display:flex; align-items:center; padding:0 8px; border-radius:var(--radius-row,4px); } .ds-row:hover { background:var(--bg-tree-hover,#0000000a); } .ds-row-sel, .ds-row-sel:hover { background:var(--bg-tree-selected-inactive,#e9eaee); } .ds-tree:focus .ds-row-sel { background:var(--bg-tree-selected,#d0dffe); }"
+ },
+ {
+ "name": "Island on Frame",
+ "kind": "card",
+ "description": "The signature layout unit: rounded islands 6px apart on the grey frame, flat at rest.",
+ "html": "",
+ "css": ".ds-frame { display:flex; gap:var(--island-gap,6px); padding:var(--island-gap,6px); background:var(--bg-frame,#e9eaee); height:160px; } .ds-island { background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); } .ds-side { width:140px; } .ds-main { flex:1; padding:12px; font-family:var(--font-mono); font-size:var(--fs-code,13px); color:var(--fg-editor,#080808); } .ds-head { height:40px; display:flex; align-items:center; padding:0 12px; font-family:var(--font-ui); font-size:var(--fs-ui,13px); font-weight:600; color:var(--fg-strong,#000); }"
+ },
+ {
+ "name": "Tooltip",
+ "kind": "custom",
+ "refersTo": "tooltip",
+ "description": "Floating hover help: one of the few surfaces allowed a shadow.",
+ "html": "Run 'main' ⌃R
",
+ "css": ".ds-tooltip { display:inline-flex; gap:8px; align-items:center; padding:6px 10px; border-radius:var(--radius-tooltip,6px); background:var(--bg-tooltip,#fff); color:var(--fg-tooltip,#000); border:1px solid var(--border-tooltip,#d1d3d9); box-shadow:var(--shadow-tooltip,0 4px 12px rgba(0,0,0,.12)); font-family:var(--font-ui); font-size:var(--fs-ui,13px); } .ds-kbd { font-family:var(--font-keys); color:var(--fg-muted,#6c707e); }"
+ }
+ ],
+ "narrative": {
+ "northStar": "The Quiet Workbench",
+ "overview": "The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.\n\nThe visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.\n\nEvery panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.\n\nThe tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.\n\nExpression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.",
+ "keyCharacteristics": [
+ "JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.",
+ "Grey frame, rounded content islands, tonal layering only.",
+ "A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.",
+ "High density on a 4px grid. Compact mode is a first-class variant.",
+ "Controls are quiet at rest: toolbar buttons and chips have no frame until hover.",
+ "Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.",
+ "Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins."
+ ],
+ "rules": [
+ {
+ "name": "The IDEA Reference Rule",
+ "body": "When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.",
+ "section": "overview"
+ },
+ {
+ "name": "The One Accent Rule",
+ "body": "Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.",
+ "section": "colors"
+ },
+ {
+ "name": "The Token Only Rule",
+ "body": "Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.",
+ "section": "colors"
+ },
+ {
+ "name": "The Flat Scale Rule",
+ "body": "The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.",
+ "section": "typography"
+ },
+ {
+ "name": "The User Owns Size Rule",
+ "body": "Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.",
+ "section": "typography"
+ },
+ {
+ "name": "The Flat at Rest Rule",
+ "body": "No docked panel, island, row or control gets a shadow. A shadow means \"this floats over the workbench and will go away\". Depth inside the layout is only ever a tonal step.",
+ "section": "elevation"
+ }
+ ],
+ "dos": [
+ "**Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).",
+ "**Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.",
+ "**Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.",
+ "**Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.",
+ "**Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.",
+ "**Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.",
+ "**Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.",
+ "**Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`."
+ ],
+ "donts": [
+ "**Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.",
+ "**Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.",
+ "**Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.",
+ "**Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.",
+ "**Don't** put shadows on docked panels, islands, rows or controls.",
+ "**Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.",
+ "**Don't** use hex, `rgb()` or named colours in component CSS or inline styles.",
+ "**Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature."
+ ]
+ }
+}
diff --git a/.oxlintrc.json b/.oxlintrc.json
index 6acbb45dbc..5a0af2061f 100644
--- a/.oxlintrc.json
+++ b/.oxlintrc.json
@@ -147,6 +147,22 @@
"prefer-rest-params": "error",
"prefer-spread": "error"
}
+ },
+ {
+ "files": [
+ "evals/**/*.ts",
+ "perf/**/*.ts",
+ "smoke/**/*.ts",
+ "src/features/vcs/**/*.ts",
+ "src/features/vcs/**/*.tsx",
+ "src/features/run/**/*.ts",
+ "src/features/run/**/*.tsx",
+ "src/features/database/**/*.ts",
+ "src/features/database/**/*.tsx"
+ ],
+ "rules": {
+ "no-await-in-loop": "error"
+ }
}
]
}
diff --git a/Cargo.lock b/Cargo.lock
index 6efae27195..d7d2699c5d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4189,6 +4189,7 @@ dependencies = [
"ide-core",
"serde",
"specta",
+ "tempfile",
"which",
]
@@ -4320,6 +4321,7 @@ dependencies = [
"ide-http",
"ide-sdk",
"ide-ssh",
+ "libc",
"notify",
"open",
"oracledb",
@@ -4339,6 +4341,7 @@ dependencies = [
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"uuid",
+ "windows-sys 0.61.2",
"zeroize",
"zip",
]
@@ -4515,6 +4518,7 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
"tracing",
"tracing-subscriber",
+ "url",
"uuid",
"windows-sys 0.61.2",
"zip",
diff --git a/DESIGN.md b/DESIGN.md
new file mode 100644
index 0000000000..b27ef66307
--- /dev/null
+++ b/DESIGN.md
@@ -0,0 +1,323 @@
+---
+name: OpenIDEA
+description: The IDE you know, rebuilt in Rust.
+colors:
+ workbench-blue: "#3871e1"
+ link-blue: "#2f5eb9"
+ frame-grey: "#e9eaee"
+ island-white: "#ffffff"
+ raised-paper: "#f7f8f9"
+ ink: "#000000"
+ ink-secondary: "#5f6269"
+ ink-muted: "#6c707e"
+ ink-faint: "#9fa2a8"
+ hairline: "#e9eaee"
+ control-edge: "#d1d3d9"
+ selection-wash: "#d0dffe"
+ tab-wash: "#e3ebfe"
+ danger: "#c54e58"
+ warning: "#a56906"
+ success: "#338555"
+ frame-grey-dark: "#26282c"
+ island-dark: "#191a1c"
+ ink-dark: "#d1d3d9"
+ ink-strong-dark: "#dfe1e5"
+ ink-muted-dark: "#8c8f95"
+ control-edge-dark: "#40434a"
+ selection-wash-dark: "#2a4371"
+typography:
+ title:
+ fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
+ fontSize: "13px"
+ fontWeight: 600
+ lineHeight: 1.4
+ body:
+ fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
+ fontSize: "13px"
+ fontWeight: 400
+ lineHeight: 1.4
+ label:
+ fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
+ fontSize: "12px"
+ fontWeight: 400
+ lineHeight: 1.4
+ label-tiny:
+ fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
+ fontSize: "11px"
+ fontWeight: 400
+ lineHeight: 1.4
+ input-large:
+ fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
+ fontSize: "15px"
+ fontWeight: 400
+ code:
+ fontFamily: "JetBrains Mono, JetBrains Mono Variable, ui-monospace, Menlo, monospace"
+ fontSize: "13px"
+ fontWeight: 400
+ lineHeight: "22px"
+ fontFeature: "\"liga\" 0"
+rounded:
+ small: "4px"
+ control: "4px"
+ row: "4px"
+ selection: "5px"
+ tab: "6px"
+ toolbar-button: "6px"
+ tooltip: "6px"
+ popup: "8px"
+ island: "10px"
+ popup-large: "10px"
+ dialog: "10px"
+spacing:
+ space-0-5: "2px"
+ space-1: "4px"
+ space-1-5: "6px"
+ space-2: "8px"
+ space-3: "12px"
+ space-4: "16px"
+components:
+ button-primary:
+ backgroundColor: "{colors.workbench-blue}"
+ textColor: "{colors.island-white}"
+ typography: "{typography.body}"
+ rounded: "{rounded.control}"
+ padding: "0 16px"
+ height: "28px"
+ button-secondary:
+ backgroundColor: "{colors.island-white}"
+ textColor: "{colors.ink}"
+ typography: "{typography.body}"
+ rounded: "{rounded.control}"
+ padding: "0 16px"
+ height: "28px"
+ button-ghost:
+ textColor: "{colors.ink-secondary}"
+ typography: "{typography.body}"
+ rounded: "{rounded.control}"
+ padding: "0 8px"
+ height: "28px"
+ icon-button:
+ textColor: "{colors.ink-muted}"
+ rounded: "{rounded.toolbar-button}"
+ size: "24px"
+ icon-button-selected:
+ backgroundColor: "{colors.selection-wash}"
+ textColor: "{colors.ink}"
+ rounded: "{rounded.toolbar-button}"
+ size: "24px"
+ input:
+ backgroundColor: "{colors.island-white}"
+ textColor: "{colors.ink}"
+ typography: "{typography.body}"
+ rounded: "{rounded.control}"
+ padding: "0 8px"
+ height: "28px"
+ chip:
+ textColor: "{colors.ink-secondary}"
+ typography: "{typography.label}"
+ rounded: "{rounded.toolbar-button}"
+ padding: "0 6px"
+ height: "22px"
+ tooltip:
+ backgroundColor: "{colors.island-white}"
+ textColor: "{colors.ink}"
+ typography: "{typography.body}"
+ rounded: "{rounded.tooltip}"
+ padding: "6px 10px"
+ list-row-selected:
+ backgroundColor: "{colors.selection-wash}"
+ textColor: "{colors.ink}"
+ rounded: "{rounded.row}"
+ height: "24px"
+---
+
+# Design System: OpenIDEA
+
+## Overview
+
+**Creative North Star: "The Quiet Workbench"**
+
+The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.
+
+The visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.
+
+Every panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.
+
+The tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.
+
+Expression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.
+
+### Named Rules
+
+**The IDEA Reference Rule.** When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.
+
+**Key Characteristics:**
+
+- JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.
+- Grey frame, rounded content islands, tonal layering only.
+- A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.
+- High density on a 4px grid. Compact mode is a first-class variant.
+- Controls are quiet at rest: toolbar buttons and chips have no frame until hover.
+- Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.
+- Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins.
+
+## Colors
+
+A near-neutral grey ramp with one cool blue accent. Status, VCS and syntax colours are functional vocabularies with fixed meanings. Values in the frontmatter are Islands Light (the default), and `-dark` keys are the Islands Dark counterparts. High Contrast, the Solarized themes, imported IntelliJ themes and plugin themes override the same tokens, so the names describe roles, not hexes.
+
+### Project colour
+
+- **Project wash** (`--project-color`): a radial tint of the project's colour (22% strength, 600 × 300px) that fades in from the frame's top-left corner, as the IDEA project gradient does. It identifies the project window. It is the one gradient in the chrome.
+
+### Primary
+
+- **Workbench Blue** (`--accent`): primary buttons, the focus ring, the selected-and-active stripe button, and search-match emphasis. The appearance setting can override it, so components reference `--accent`, never the hex.
+- **Link Blue** (`--link`): inline links. In Dark it lightens to stay readable on the dark islands.
+
+### Neutral
+
+- **Frame Grey** (`--bg-frame`): the window frame behind the islands, and the stripes (the tool window button bars).
+- **Island White** (`--bg-island`, `--bg-app`): editor and tool window surfaces. This is where the work lives.
+- **Raised Paper** (`--bg-elev`, `--bg-dialog`): dialog bodies and inline popups, one tonal step off the island.
+- **Ink** (`--fg`, `--fg-strong`): primary text. **Ink Secondary / Muted / Faint** (`--fg-secondary`, `--fg-muted`, `--fg-faint`): metadata, icons and placeholders, then disabled text.
+- **Hairline** (`--border`): dividers between regions inside an island. **Control Edge** (`--border-button`, `--border-strong`): the 1px inset frame of fields and secondary buttons.
+- **Selection Wash** (`--bg-tree-selected`, `--bg-selected`, `--bg-toolbar-selected`): the selected row in focused trees and lists, and pressed-on toolbar toggles. When the tree loses focus, the selection drops to the neutral `--bg-tree-selected-inactive`.
+
+### Functional vocabularies
+
+- **Status:** `--danger`, `--warning`, `--success` and `--info`, each with `--bg-feedback-*` and `--border-feedback-*` pairs for banners.
+- **VCS and diff:** `--vcs-*` for file status in trees and tabs, `--gutter-*` for gutter marks, and `--diff-*` for diff fills and their error-stripe marks.
+- **Syntax:** `--syn-*`, from the editor colour scheme. Users and plugins replace these per scheme.
+
+### Named Rules
+
+**The One Accent Rule.** Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.
+
+**The Token Only Rule.** Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.
+
+## Typography
+
+**UI Font:** Inter Variable (with system-ui and -apple-system fallbacks)
+**Code Font:** JetBrains Mono (with ui-monospace and Menlo fallbacks)
+**Key Glyph Font:** the system UI font (`--font-keys`), so shortcut glyphs such as ⌘⇧⌥⌃↵ render as they do in native menus
+
+**Character:** a neutral sans for chrome and a coding mono for content. Neither performs. Hierarchy comes from weight and colour, not size.
+
+### Hierarchy
+
+- **Title** (600, 13px, 1.4): tool window titles, section headers, dialog titles and emphasised names. Weight 600 is the system's main emphasis.
+- **Body** (400, 13px, 1.4): default UI text, menus, tree and list rows, and buttons.
+- **Label** (400, 12px): the most common size. It covers secondary metadata, chips, status bar items, table cells and hints.
+- **Label Tiny** (400, 11px): stripe labels, counters and badges.
+- **Input Large** (400, 15px): Search Everywhere and similar large query fields.
+- **Code** (400, 13px, 22px line height): the editor, console, terminal and every monospace preview. Ligatures are off by default and follow the `editor.ligatures` setting. Users set the weights (`--fw-code`, `--fw-code-bold`) and the size.
+
+### Named Rules
+
+**The Flat Scale Rule.** The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.
+
+**The User Owns Size Rule.** Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.
+
+## Layout
+
+The window is a grey frame holding docked islands: the editor in the centre, tool windows around it, stripes of tool window buttons on the edges (58px wide), a titlebar with the main toolbar (40px), and a status bar (30px). The status bar sits directly on the frame with no divider. Islands sit 6px apart and have 10px corners. Trees are inset 6px inside their island.
+
+Spacing follows a 4px grid (`--space-0-5` to `--space-4`, 2–16px). It is used for gaps, with component heights doing most of the rhythm work: rows 24px, fields and buttons 28px, small controls 24px or 20px, tabs 28px in a 38px tab bar, and tool window headers 40px.
+
+**Compact mode** (`data-compact`) is a full variant, not an afterthought. Rows drop to 22px, fields and buttons to 24px, the titlebar and headers to 32px, the status bar to 24px, the island gap to 4px and island corners to 8px, and chrome text gets 1px smaller. Every layout must hold in both modes.
+
+The app is a desktop window. It is never a scrolling page: the document never scrolls, and every scroll region is its own scroller inside an island. Dialogs open about 10vh from the top and below the titlebar. Wide reading surfaces, such as an agent conversation, cap their width (900px) inside the island.
+
+## Elevation & Depth
+
+Static layout is flat and layered by tone. The grey frame sits under white islands (in Dark, a lighter frame under darker islands). Shadows exist only on surfaces that float above the layout: popups, menus, dialogs, tooltips, balloons, undocked tool windows and drag ghosts. Dialogs use a window-style shadow, because they are separate windows in spirit.
+
+### Shadow Vocabulary
+
+- **Popup** (`--shadow-popup`; Light `0 6px 20px rgba(0,0,0,0.12)`): popups, menus, completion and the floating editor toolbar.
+- **Dialog** (`--shadow-dialog`): a hairline ring plus two soft drops, like a native window shadow.
+- **Tooltip** (`--shadow-tooltip`) and **Balloon** (`--shadow-balloon`): small and medium drops for hover help and notifications.
+
+### Named Rules
+
+**The Flat at Rest Rule.** No docked panel, island, row or control gets a shadow. A shadow means "this floats over the workbench and will go away". Depth inside the layout is only ever a tonal step.
+
+## Shapes
+
+Corners scale with the size of the surface. Small controls get 4px (buttons, fields, combos, rows, small icon buttons). Toolbar buttons, chips, tabs and tooltips get 6px, and selection highlights get 5px. Popups get 8–10px, and islands and dialogs get 10px. Compact mode tightens island corners to 8px and combo corners to 2px. Frames are drawn as 1px inset box-shadows rather than borders, so they never shift layout and can double on focus. There are no pills, circles (apart from macOS window buttons and status dots), or rounding beyond 10px.
+
+## Components
+
+Quiet and dependable. Components don't call attention to themselves, they behave the same everywhere, and they come from `src/ui/` primitives before anything custom.
+
+### Buttons
+
+- **Shape:** gently rounded (4px). Minimum width 72px, 28px tall, 16px horizontal padding. The small variant is 24px tall with 10px padding.
+- **Primary:** Workbench Blue fill with white text. Hover mixes it toward the strong ink colour (`--accent-hover`). Use it for one default action per dialog.
+- **Secondary:** island-coloured with a 1px Control Edge inset frame. Hover darkens the fill by about 6%.
+- **Ghost:** no fill or frame, secondary ink colour, 8px padding. Hover shows the toolbar hover wash and strong ink. Pressed is a stronger wash.
+- **Focus:** a 2px Workbench Blue outline, 1px outside the button. **Disabled:** transparent fill, faint text and a hairline frame.
+- **Motion:** background, colour and frame change over 80ms (`--dur-fast`) with `--ease`. There are no transitions under `prefers-reduced-motion`, and forced-colours mode gets a real border.
+
+### Icon Buttons (toolbar actions)
+
+- 20, 24 or 28px square, with 6px corners (4px at 20px). The icon is muted at rest.
+- Hover shows the toolbar hover wash (`--bg-toolbar-hover`, a translucent ink) across the full hit target, and the icon turns strong ink. Pressed shows `--bg-toolbar-pressed`.
+- A toggled-on button (`aria-pressed`) shows Selection Wash. The focus ring is drawn 2px inside the button.
+- Tone variants (`danger`, `accent`) recolour only the icon.
+
+### Chips
+
+- **Style:** flat, like the main toolbar's project and branch widgets. They are 22px tall with 6px corners, have no fill or frame at rest, and use 12px secondary ink with a muted icon.
+- **State:** a chip that opens a picker gets the toolbar hover wash. A read-only chip never changes on hover.
+
+### Inputs / Fields
+
+- **Style:** 28px tall with 8px horizontal padding and 4px corners. Island fill with a 1px Control Edge inset frame. Placeholders use the faint ink.
+- **Focus:** the frame turns Workbench Blue and doubles with a 1px outer ring, drawn entirely with box-shadow.
+- **Error:** the same doubled ring in `--danger`. **Disabled:** transparent fill, faint text and a hairline frame.
+- Search fields have a muted leading icon. Monospace fields use the code font.
+
+### Lists and Trees
+
+- Rows are 24px (22px compact). The selection is a 4–5px rounded wash inset from the island edge, not a full-bleed bar.
+- A focused selection uses Selection Wash, and an unfocused one drops to a neutral grey. Hover is a faint translucent wash. Search matches use `--bg-search-match`.
+
+### Popups, Menus and Dialogs
+
+- **Popups and menus:** `--bg-popup` with a 1px popup frame, 10px corners (`--radius-popup-large`) and the popup shadow.
+- **Dialogs:** Raised Paper body with 10px corners and the dialog shadow. They behave like IDEA's dialogs, which are separate windows: the modal layer blocks the workbench but never dims it. The footer actions are right-aligned buttons. Focus returns to wherever it came from when the dialog closes.
+
+### Tabs
+
+- 28px tabs (24px compact) in a 38px bar, with 6px corners and 8px horizontal padding.
+- As in IDEA, only the part holding focus accents its selected tab (`--bg-tab-selected` with `--border-tab-selected`). Elsewhere the selected tab drops to the neutral inactive pair.
+- **Tooltips:** 6px corners with 6px × 10px padding, using `--bg-tooltip` (white in Light, dark grey in Dark) and the tooltip shadow.
+
+### Tool Window Stripes (signature)
+
+The edge bars of tool window buttons are 58px wide on Frame Grey, with icons over 11px labels. Hover and selected states are translucent ink washes. The selected button of the active tool window fills with Workbench Blue and white content. This is the one place the accent fills a large shape in the chrome, and it marks the active tool window.
+
+## Do's and Don'ts
+
+### Do:
+
+- **Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).
+- **Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.
+- **Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.
+- **Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.
+- **Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.
+- **Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.
+- **Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.
+- **Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`.
+
+### Don't:
+
+- **Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.
+- **Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.
+- **Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.
+- **Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.
+- **Don't** put shadows on docked panels, islands, rows or controls.
+- **Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.
+- **Don't** use hex, `rgb()` or named colours in component CSS or inline styles.
+- **Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature.
diff --git a/PRODUCT.md b/PRODUCT.md
new file mode 100644
index 0000000000..a5b2b2d763
--- /dev/null
+++ b/PRODUCT.md
@@ -0,0 +1,73 @@
+# Product
+
+
+
+## Platform
+
+web
+
+The IDE is a Tauri desktop app for macOS, Windows and Linux. Its UI is a web frontend (React, CSS Modules) inside the system webview, with its own design language rather than each operating system's native one. Scope: this record covers the IDE application only. The openidea.sh docs site and home page (`docs/`) are out of scope.
+
+## Users
+
+- **Primary: JetBrains users who want something lighter.** They already know the IntelliJ IDEA keymap, tool windows and search-everything habits, and find IDEA heavy and slow. They do everyday multi-language development on the desktop: editing, navigating, refactoring, running and debugging, Git, terminal, database and HTTP clients.
+- **Primary: developers working with AI coding agents.** They run CLI agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor and others over ACP) inside the IDE as tasks, often several at once, each in its own Git worktree or in the checkout. They review the agents' diffs, answer their permission requests, and give agents the IDE's own tools through the built-in MCP server.
+- **Secondary: people moving from VS Code or Eclipse.** Their keymaps are built in.
+
+## Product Purpose
+
+OpenIDEA brings the IntelliJ IDEA way of working to a native app with a Rust core: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages. Success means people who know the IDEA way of working can switch without relearning anything, and it opens, responds and quits much faster while using a fraction of the memory.
+
+## Positioning
+
+"The IDE you know, rebuilt in Rust." The habits are familiar (keymap, tool windows, Search Everywhere, Alt+Enter), the app is open source (Apache 2.0), and performance is measured: on the published benchmark, the window opens in 0.9 s against 3.1 s and the app uses 169 MB against 2011 MB. Coding agents are part of the IDE (tasks, worktrees, diffs and the IDE's tools over MCP) rather than a separate chat app.
+
+## Operating Context
+
+- Long sessions in one desktop window: the editor in the middle, tool windows docked around it, and keyboard-first navigation (Search Everywhere, Find Action, Go to Class/File/Symbol).
+- Local projects, and remote development over SSH or in dev containers through the `openidea-server` backend.
+- Agent tasks running alongside the developer's own work, with diff review and permission prompts.
+- Built-in themes: Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark, with an option to follow the OS's light or dark mode. Users can import IntelliJ themes and `.icls` colour schemes, and plugins add more themes.
+
+## Capabilities and Constraints
+
+Hard constraints future work must preserve:
+
+1. The default keymap and interaction habits stay the same as IDEA's.
+2. All user-visible text is written in English and must also have a Chinese translation, through the text catalog (`T`, translated `aria-label`).
+3. WebKit floor is Safari 15.4 (macOS 12). No regex lookbehind or `v` flag, no import attributes, and no newer runtime APIs in startup code. `scripts/check-webkit.ts` enforces this.
+4. Design tokens in `src/styles/tokens.css` are the public theme API for plugins. Components use tokens only and never colour literals. A new token needs a value for every theme variant, and the docs must be regenerated with `pnpm gen:theme-docs`.
+5. Every user operation is an action with a stable id, reachable from the keyboard and Find Action, not only by mouse.
+6. No emoji as icons or decoration, in the UI or in user-visible text. Icons come from the `src/ui/icons.tsx` registry.
+7. Performance (startup, memory, idle CPU) is the core selling point. UI work must not slow it down.
+
+Other facts:
+
+- Plugins are sandboxed WebAssembly components that add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. The plugin API is still a preview.
+- UI is built from the primitives in `src/ui/` (Button, Dialog, Popup, Menu, List, Tree, Tabs and others). Workbench pieces come from contributions, not custom layout.
+
+## Brand Commitments
+
+- Name: OpenIDEA. Wordmarks are in `src-tauri/icons/source/` (`openidea-wordmark.svg` and `openidea-wordmark-dark.svg`).
+- Not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.
+- Voice is plain, short and factual. It states measurements with their conditions rather than superlatives.
+
+## Evidence on Hand
+
+- Benchmark table and method: `README.md`, `perf/compare`. The conditions are stated with it: freqtrade, warm caches, median of 5 runs, Windows 11, 32-core AMD.
+- Demo video linked from `README.md`.
+- No testimonials, customer logos or user counts exist. Do not fabricate them.
+
+## Product Principles
+
+1. **Familiar first.** Existing IDEA habits must keep working. New behaviour must not break that muscle memory.
+2. **Speed is a feature.** Every surface is judged by how much it costs in startup time, memory and responsiveness.
+3. **Keyboard reachable.** If something can be done, it is an action that can be found and bound.
+4. **Agents work inside the IDE.** Agent work is reviewed and controlled with the IDE's own tools: diffs, worktrees and permissions.
+5. **Themeable by contract.** Visual decisions go through tokens that themes and plugins can rely on.
+
+## Accessibility & Inclusion
+
+- Use real `` and ` ` elements or the primitives that render them. Every icon-only button has a translated `aria-label`.
+- Keep focus visible and predictable. Dialogs and popups return focus to where it came from.
+- A dark high-contrast theme (`dark-hc`) ships and must be kept working.
diff --git a/crates/ide-agent/src/images.rs b/crates/ide-agent/src/images.rs
new file mode 100644
index 0000000000..3fd6c1b4e9
--- /dev/null
+++ b/crates/ide-agent/src/images.rs
@@ -0,0 +1,143 @@
+//! Images in agent content: ACP content blocks, `data:` URLs and image files on disk.
+
+use crate::model::AgentImage;
+use base64::Engine;
+use serde_json::{Value, json};
+use std::path::Path;
+
+/// Image files larger than this are not inlined into the conversation.
+const MAX_FILE_BYTES: u64 = 10 * 1024 * 1024;
+
+/// The image an ACP content block shows: an `image` (inline or by URI), a `resource` with an
+/// image blob, or a `resource_link` to an image file.
+pub(crate) fn from_content(content: &Value) -> Option {
+ match str_of(content, "type")? {
+ "image" => {
+ if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
+ && mime.starts_with("image/")
+ {
+ return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
+ }
+ from_uri(str_of(content, "uri")?)
+ }
+ "resource" => {
+ let resource = content.get("resource")?;
+ let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
+ mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
+ }
+ "resource_link" => {
+ let uri = str_of(content, "uri")?;
+ let declared = str_of(content, "mimeType").is_some_and(|m| m.starts_with("image/"));
+ if !declared && mime_of(Path::new(&uri_path(uri))).is_none() {
+ return None;
+ }
+ let mut image = from_uri(uri)?;
+ image.name = str_of(content, "name").map(str::to_owned);
+ Some(image)
+ }
+ _ => None,
+ }
+}
+
+fn str_of<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
+ v.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
+}
+
+/// The image at a `data:` URL or a `file://` URI.
+pub(crate) fn from_uri(uri: &str) -> Option {
+ if let Some(rest) = uri.strip_prefix("data:") {
+ let (mime, data) = rest.split_once(";base64,")?;
+ return (mime.starts_with("image/") && !data.is_empty()).then(|| AgentImage {
+ mime_type: mime.into(),
+ data: data.into(),
+ name: None,
+ });
+ }
+ uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
+}
+
+/// The image file at `path`, when it has an image extension and isn't too large.
+pub(crate) fn from_file(path: &Path) -> Option {
+ let mime = mime_of(path)?;
+ if std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES {
+ return None;
+ }
+ let bytes = std::fs::read(path).ok()?;
+ (!bytes.is_empty()).then(|| AgentImage {
+ mime_type: mime.into(),
+ data: base64::engine::general_purpose::STANDARD.encode(bytes),
+ name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
+ })
+}
+
+/// `image` as an ACP image content block.
+pub(crate) fn content(image: &AgentImage) -> Value {
+ json!({ "type": "image", "mimeType": image.media_type(), "data": image.data })
+}
+
+fn mime_of(path: &Path) -> Option<&'static str> {
+ let ext = path.extension()?.to_str()?.to_ascii_lowercase();
+ Some(match ext.as_str() {
+ "png" => "image/png",
+ "jpg" | "jpeg" => "image/jpeg",
+ "gif" => "image/gif",
+ "webp" => "image/webp",
+ "bmp" => "image/bmp",
+ "svg" => "image/svg+xml",
+ _ => return None,
+ })
+}
+
+/// The path of a `file://` URI (percent-decoded); other URIs as they are.
+pub(crate) fn uri_path(uri: &str) -> String {
+ let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
+ let bytes = rest.as_bytes();
+ let mut out = Vec::with_capacity(bytes.len());
+ let mut i = 0;
+ while i < bytes.len() {
+ if bytes[i] == b'%'
+ && let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
+ {
+ out.push(b);
+ i += 3;
+ } else {
+ out.push(bytes[i]);
+ i += 1;
+ }
+ }
+ let path = String::from_utf8_lossy(&out).into_owned();
+ // `file:///C:/x` on Windows.
+ match path.as_bytes() {
+ [b'/', drive, b':', ..] if drive.is_ascii_alphabetic() => path[1..].to_owned(),
+ _ => path,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn content_blocks_inline_data_urls_blobs_and_image_files() {
+ let dir = tempfile::tempdir().unwrap();
+ let file = dir.path().join("shot 1.png");
+ std::fs::write(&file, b"\x89PNG\r\n").unwrap();
+ std::fs::write(dir.path().join("notes.txt"), b"hi").unwrap();
+ let uri = crate::file_uri(&file);
+ let inline = json!({"type": "image", "mimeType": "image/png", "data": "aW1n"});
+ assert_eq!(from_content(&inline).unwrap().data, "aW1n");
+ let by_url = json!({"type": "image", "uri": "data:image/jpeg;base64,AAA"});
+ assert_eq!(from_content(&by_url).unwrap().mime_type, "image/jpeg");
+ let by_file = from_content(&json!({"type": "image", "uri": uri})).unwrap();
+ assert_eq!(by_file.data, base64::engine::general_purpose::STANDARD.encode(b"\x89PNG\r\n"));
+ let blob = json!({"type": "resource", "resource": {"uri": "x", "mimeType": "image/gif", "blob": "R0lG"}});
+ assert_eq!(from_content(&blob).unwrap().mime_type, "image/gif");
+ let link = from_content(&json!({"type": "resource_link", "uri": uri, "name": "shot"})).unwrap();
+ assert_eq!((link.mime_type.as_str(), link.name.as_deref()), ("image/png", Some("shot")));
+ let text = crate::file_uri(&dir.path().join("notes.txt"));
+ assert!(from_content(&json!({"type": "resource_link", "uri": text, "name": "notes"})).is_none());
+ assert!(from_content(&json!({"type": "resource", "resource": {"uri": "x", "text": "t"}})).is_none());
+ assert!(from_content(&json!({"type": "image", "uri": "https://example.com/a.png"})).is_none());
+ assert!(from_file(&dir.path().join("missing.png")).is_none());
+ }
+}
diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs
index 3d28038034..a757f7d7ca 100644
--- a/crates/ide-agent/src/lib.rs
+++ b/crates/ide-agent/src/lib.rs
@@ -16,6 +16,7 @@ mod conversation;
mod elicitation;
mod external;
pub mod hermes;
+mod images;
pub mod mcp;
mod model;
mod native;
@@ -419,9 +420,13 @@ struct TaskFile {
/// `None` for a worktree task, and a task saved before these were recorded.
#[serde(default, skip_serializing_if = "Option::is_none")]
touched: Option>,
- /// The checkout as the last turn started, its copies in the store's `.turn` folder.
- #[serde(default, skip_serializing_if = "Option::is_none")]
+ /// The checkout as the last turn started, in task files saved before every turn's was kept.
+ #[serde(default, skip_serializing)]
turn: Option,
+ /// The checkout as each turn of the conversation started (by turn, `None` where it wasn't
+ /// recorded), the copies in the store's `.turn` folder.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ turns: Vec>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
subagents: Vec,
/// Turns to drop from the session once it is loaded (a fork of an earlier point).
@@ -455,6 +460,16 @@ impl PendingModel {
/// The changed files of a checkout, stamped.
type Snapshot = BTreeMap;
+/// Holds `TaskState::busy` for the duration of an operation so concurrent prompts or rollbacks
+/// wait until it finishes.
+struct BusyGuard(Arc);
+
+impl Drop for BusyGuard {
+ fn drop(&mut self) {
+ self.0.state.lock().busy = false;
+ }
+}
+
struct TaskState {
task: AgentTask,
session_id: Option,
@@ -467,8 +482,8 @@ struct TaskState {
saved: Option,
/// See `TaskFile::touched`.
touched: Option>>,
- /// See `TaskFile::turn`.
- turn: Option>,
+ /// See `TaskFile::turns`.
+ turns: Vec>>,
pending_rollback: u32,
/// The user named the task; see `TaskFile::title_renamed`.
title_renamed: bool,
@@ -989,6 +1004,7 @@ impl AgentManager {
saved: None,
touched: Some(BTreeSet::new()),
turn: None,
+ turns: Vec::new(),
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: true,
@@ -1116,6 +1132,7 @@ impl AgentManager {
saved,
touched: (req.isolation == Isolation::Local).then(BTreeSet::new),
turn: None,
+ turns: Vec::new(),
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: false,
@@ -1478,8 +1495,9 @@ impl AgentManager {
before: (*s.before).clone(),
saved: s.saved.clone(),
touched: s.touched.as_deref().cloned(),
- // The source's next turn replaces its copies: the fork's last turn is one of its own.
+ // The copies are the source's: the fork's turns are recorded as it runs them.
turn: None,
+ turns: Vec::new(),
subagents: s.conversation.saved_subagents(),
pending_rollback: total - keep,
title_renamed: s.title_renamed,
@@ -1496,21 +1514,31 @@ impl AgentManager {
}
/// Drops the task's turns after its first `turns`, in the agent's session and in the
- /// conversation; returns the message that started the first dropped turn. Files the
- /// agent changed stay as they are.
- pub async fn rollback(&self, id: &str, turns: u32) -> IdeResult > {
+ /// conversation; returns the message that started the first dropped turn. With `files`,
+ /// the files the dropped turns changed go back as they were when the first of them
+ /// started; otherwise they stay as they are.
+ pub async fn rollback(&self, id: &str, turns: u32, files: bool) -> IdeResult > {
let task = self.task(id)?;
- if task.state.lock().busy {
- return Err(IdeError::invalid("wait until the agent is done"));
- }
- let starts = turn_starts(&task.state.lock().conversation.main.entries);
- let Some(&cut) = starts.get(turns as usize) else { return Ok(None) };
+ let (starts, cut) = {
+ let mut s = task.state.lock();
+ if s.busy {
+ return Err(IdeError::invalid("wait until the agent is done"));
+ }
+ let starts = turn_starts(&s.conversation.main.entries);
+ let Some(&cut) = starts.get(turns as usize) else { return Ok(None) };
+ s.busy = true;
+ (starts, cut)
+ };
+ let guard = BusyGuard(task.clone());
+ // Read and checked before anything changes: a file that can't go back stops it all.
+ let planned = if files { self.plan_rewind(&task, turns as usize, starts.len()).await? } else { Vec::new() };
// Dropping every turn starts the conversation over, which needs no agent-side
// rewind — and some agents cannot rewind past their first turn (a resumed
// Claude Code session). A fresh session avoids both.
if turns == 0 {
task.kill();
- let first = {
+ let restamped = self.write_rewind(&task, planned).await?;
+ let (first, dir, kept) = {
let mut s = task.state.lock();
let first = match s.conversation.main.entries.get(cut) {
Some(AgentEntry::User { text, .. }) => {
@@ -1527,25 +1555,29 @@ impl AgentManager {
s.task.usage = None;
s.pending_rollback = 0;
s.task.updated_ms = now_ms();
- first
+ Self::finish_rewind(&mut s, 0, restamped);
+ (first, task.turn_dir(), s.turns.clone())
};
+ drop(guard);
task.streamed.lock().clear();
task.persist();
self.shared.emit(AgentEvent::Truncated { task: id.to_owned(), length: 0 });
task.emit_task();
+ self.prune_turn_copies(dir, kept).await;
return Ok(first);
}
let live = task.ensure_session().await.map_err(IdeError::internal)?;
if !live.capabilities.rollback {
return Err(IdeError::invalid("this agent can't undo turns"));
}
- let drop = (starts.len() - turns as usize) as u32;
+ let drop_turns = (starts.len() - turns as usize) as u32;
let _: Value = live
.peer
- .request("_openidea/rollback", json!({ "sessionId": live.session, "turns": drop }), None)
+ .request("_openidea/rollback", json!({ "sessionId": live.session, "turns": drop_turns }), None)
.await
.map_err(|e| IdeError::internal(task.describe(e)))?;
- let first = {
+ let restamped = self.write_rewind(&task, planned).await?;
+ let (first, dir, kept) = {
let mut s = task.state.lock();
let first = match s.conversation.main.entries.get(cut) {
Some(AgentEntry::User { text, .. }) => Some(AgentPrompt { text: text.clone(), ..Default::default() }),
@@ -1553,12 +1585,15 @@ impl AgentManager {
};
s.conversation.truncate(cut);
s.task.updated_ms = now_ms();
- first
+ Self::finish_rewind(&mut s, turns as usize, restamped);
+ (first, task.turn_dir(), s.turns.clone())
};
+ drop(guard);
task.streamed.lock().clear();
task.persist();
self.shared.emit(AgentEvent::Truncated { task: id.to_owned(), length: cut as u32 });
task.emit_task();
+ self.prune_turn_copies(dir, kept).await;
// Undoing may have started the agent: it stops again once idle.
task.release_when_idle();
Ok(first)
@@ -1916,6 +1951,98 @@ impl AgentManager {
.await
}
+ /// What rolling the task's files back to the start of its turn `turn` writes.
+ async fn plan_rewind(
+ &self,
+ task: &Arc,
+ turn: usize,
+ total_turns: usize,
+ ) -> IdeResult> {
+ let (cwd, start, before, saved, touched, dropped_changed) = {
+ let s = task.state.lock();
+ let start = s.turns.get(turn).cloned().flatten();
+ let dropped = s.turns.get(turn..).unwrap_or(&[]);
+ let dropped_changed = (dropped.len() == total_turns - turn
+ && dropped.iter().all(|t| t.as_ref().is_some_and(|t| t.changed.is_some())))
+ .then(|| {
+ dropped
+ .iter()
+ .flatten()
+ .filter_map(|t| t.changed.as_ref())
+ .flatten()
+ .cloned()
+ .collect::>()
+ });
+ (
+ s.task.cwd.0.clone(),
+ start,
+ s.before.clone(),
+ s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)),
+ s.touched.clone(),
+ dropped_changed,
+ )
+ };
+ let Some(start) = start else {
+ // The task's own start is the first turn's.
+ if turn == 0 {
+ let at = task.base();
+ return vcs(&self.shared, move || {
+ worktree::plan_restore(&at, &before, saved.as_deref(), touched.as_deref())
+ })
+ .await;
+ }
+ return Err(IdeError::invalid(
+ "the files weren't recorded as this message was sent: roll them back in the Changes view instead",
+ ));
+ };
+ let dir = task.turn_dir();
+ vcs(&self.shared, move || {
+ let mut changed = worktree::changed_in_turn(&cwd, &start)?.1;
+ // In the project's own checkout, only files the rolled-back turns changed are put back.
+ if let Some(touched) = &touched {
+ let scope = dropped_changed.as_ref().unwrap_or(touched);
+ changed.retain(|rel| scope.contains(rel));
+ }
+ worktree::rewind(&cwd, &start, &dir, &changed)
+ })
+ .await
+ }
+
+ /// Writes what `plan_rewind` planned on the blocking VCS pool and computes any `before`
+ /// restamps off-lock.
+ async fn write_rewind(
+ &self,
+ task: &Arc,
+ planned: Vec,
+ ) -> IdeResult> {
+ if planned.is_empty() {
+ return Ok(Vec::new());
+ }
+ let (before, saved) = {
+ let s = task.state.lock();
+ (s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)))
+ };
+ vcs(&self.shared, move || worktree::put_back(planned, &before, saved.as_deref())).await
+ }
+
+ /// Drops the records of the turns from `turn` on and applies any restamps to `before`.
+ fn finish_rewind(s: &mut TaskState, turn: usize, restamped: Vec<(String, worktree::Stamp)>) {
+ s.turns.truncate(turn);
+ if !restamped.is_empty() {
+ let mut before = (*s.before).clone();
+ before.extend(restamped);
+ s.before = Arc::new(before);
+ }
+ }
+
+ async fn prune_turn_copies(&self, dir: PathBuf, kept: Vec>>) {
+ let _ = vcs(&self.shared, move || {
+ worktree::prune_turn_copies(&dir, kept.iter().flatten().map(|t| &**t));
+ Ok(())
+ })
+ .await;
+ }
+
/// Rollback: puts the task's changed files among `rel_paths` (all with `None`) back as
/// `view` compares them: as they were when it started, as they are in `HEAD`, or as they
/// were when its last turn started.
@@ -1972,12 +2099,12 @@ impl AgentManager {
s.before = Arc::new(before);
}
// Rolled back further than the last turn: what it changed there is gone, not the turn's to list.
- if let Some(turn) = &s.turn
+ if let Some(Some(turn)) = s.turns.last_mut()
&& let Some(changed) = &turn.changed
&& restored.iter().any(|rel| changed.contains(rel))
{
let changed = changed.iter().filter(|rel| !restored.contains(rel)).cloned().collect();
- s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(changed), ..(**turn).clone() }));
+ *turn = Arc::new(worktree::TurnStart { changed: Some(changed), ..(**turn).clone() });
}
}
task.persist();
@@ -2224,6 +2351,14 @@ impl Task {
config::add_client_options(&task.provider, &mut task.config);
let adopt = file.entries.is_empty() && file.session_id.is_some();
let conversation = Conversation::restore(file.entries, file.subagents);
+ let mut turns: Vec<_> = file.turns.into_iter().map(|t| t.map(Arc::new)).collect();
+ // Saved with the last turn's only: the turns before it have none.
+ if turns.is_empty()
+ && let Some(last) = file.turn
+ {
+ turns.resize(turn_starts(&conversation.main.entries).len().saturating_sub(1), None);
+ turns.push(Some(Arc::new(last)));
+ }
let mut wanted = file.wanted;
let pending_model = file.pending_switch.or_else(|| {
let id = file.pending_model?;
@@ -2256,7 +2391,7 @@ impl Task {
before: Arc::new(file.before),
saved: file.saved,
touched: file.touched.map(Arc::new),
- turn: file.turn.map(Arc::new),
+ turns,
pending_rollback: file.pending_rollback,
title_renamed: file.title_renamed,
busy: false,
@@ -2295,7 +2430,7 @@ impl Task {
(s.before.clone(), s.touched.clone())
}
- /// Where the copies of the files already changed as the last turn started are kept.
+ /// Where the copies of the files already changed as the turns started are kept.
fn turn_dir(&self) -> PathBuf {
self.shared.paths.store_dir.join(format!("{}.turn", self.id))
}
@@ -2303,20 +2438,38 @@ impl Task {
/// The checkout as the last turn started, with the folder of its copies.
fn last_turn(&self) -> (PathBuf, Option>, PathBuf) {
let s = self.state.lock();
- (s.task.cwd.0.clone(), s.turn.clone(), self.turn_dir())
+ (s.task.cwd.0.clone(), s.turns.last().cloned().flatten(), self.turn_dir())
}
- /// Records the checkout as a turn starts: what the turn's changes are compared with.
+ /// Records the checkout as a turn starts (its message shown): what the turn's changes are
+ /// compared with, and what rolling back to its message puts back.
async fn checkout_before_turn(self: &Arc) {
- let (cwd, previous, dir) = self.last_turn();
- let turn = match vcs(&self.shared, move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
+ let (cwd, dir, index, earlier) = {
+ let s = self.state.lock();
+ let index = turn_starts(&s.conversation.main.entries).len().saturating_sub(1);
+ let earlier: Vec<_> = s.turns.iter().take(index).cloned().collect();
+ (s.task.cwd.0.clone(), self.turn_dir(), index, earlier)
+ };
+ let kept = earlier.clone();
+ let turn = match vcs(&self.shared, move || {
+ let turn = worktree::start_turn(&cwd, &dir)?;
+ worktree::prune_turn_copies(&dir, kept.iter().flatten().map(|t| &**t).chain([&turn]));
+ Ok(turn)
+ })
+ .await
+ {
Ok(turn) => Some(Arc::new(turn)),
Err(e) => {
tracing::warn!("recording the checkout as a turn of agent task {} starts: {e}", self.id);
None
}
};
- self.state.lock().turn = turn;
+ {
+ let mut s = self.state.lock();
+ s.turns = earlier;
+ s.turns.resize(index, None);
+ s.turns.push(turn);
+ }
self.persist_soon();
}
@@ -2338,7 +2491,9 @@ impl Task {
touched.extend(in_worktree);
s.touched = Some(Arc::new(touched));
}
- s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
+ if let Some(last) = s.turns.last_mut() {
+ *last = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
+ }
}
self.persist_soon();
}
@@ -2509,7 +2664,8 @@ impl Task {
before: (*s.before).clone(),
saved: s.saved.clone(),
touched: s.touched.as_deref().cloned(),
- turn: s.turn.as_deref().cloned(),
+ turn: None,
+ turns: s.turns.iter().map(|t| t.as_deref().cloned()).collect(),
subagents: s.conversation.saved_subagents(),
pending_rollback: s.pending_rollback,
title_renamed: s.title_renamed,
@@ -3666,12 +3822,8 @@ impl Task {
/// A user message of the adopted history: live turns show the user's own, so only a replay's count.
fn adopt_user_chunk(self: &Arc, update: &Value) {
let content = update.get("content");
- let image = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image")).map(|c| AgentImage {
- mime_type: c.get("mimeType").and_then(Value::as_str).unwrap_or_default().to_owned(),
- data: c.get("data").and_then(Value::as_str).unwrap_or_default().to_owned(),
- name: None,
- });
- let text = timeline::content_text(content).unwrap_or_default();
+ let image = content.and_then(images::from_content);
+ let text = if image.is_some() { String::new() } else { timeline::content_text(content).unwrap_or_default() };
if text.is_empty() && image.is_none() {
return;
}
diff --git a/crates/ide-agent/src/native/codex/tests.rs b/crates/ide-agent/src/native/codex/tests.rs
index c2c0f1f3f9..6e8821e0dc 100644
--- a/crates/ide-agent/src/native/codex/tests.rs
+++ b/crates/ide-agent/src/native/codex/tests.rs
@@ -473,6 +473,39 @@ fn history_replays_turns() {
assert_eq!(updates[4]["status"], "completed");
}
+#[test]
+fn viewed_generated_and_attached_images_carry_their_pixels() {
+ let dir = tempfile::tempdir().unwrap();
+ let png = dir.path().join("shot.png");
+ std::fs::write(&png, b"\x89PNG\r\n").unwrap();
+ let png_path = png.to_str().unwrap();
+ let encoded = "iVBORw0K";
+ let view = json!({"id": "v", "type": "imageView", "path": png_path});
+ assert!(tool_call(&view, false, None, None).unwrap().get("content").is_none());
+ let image = &tool_call(&view, true, None, None).unwrap()["content"][0]["content"];
+ assert_eq!((image["type"].as_str(), image["data"].as_str()), (Some("image"), Some(encoded)));
+ let missing = json!({"id": "v", "type": "imageView", "path": dir.path().join("gone.png")});
+ assert!(tool_call(&missing, true, None, None).unwrap().get("content").is_none());
+ let inline = json!({"id": "g", "type": "imageGeneration", "status": "completed", "result": encoded});
+ let image = &tool_call(&inline, true, None, None).unwrap()["content"][0]["content"];
+ assert_eq!((image["mimeType"].as_str(), image["data"].as_str()), (Some("image/png"), Some(encoded)));
+ let saved =
+ json!({"id": "g", "type": "imageGeneration", "status": "completed", "fileId": "f", "savedPath": png_path});
+ assert_eq!(tool_call(&saved, true, None, None).unwrap()["content"][0]["content"]["data"], encoded);
+
+ let thread = json!({"turns": [{"items": [{"type": "userMessage", "id": "u", "content": [
+ {"type": "image", "url": "data:image/jpeg;base64,/9j/"},
+ {"type": "image", "url": "https://example.com/a.png"},
+ {"type": "localImage", "path": png_path},
+ {"type": "localImage", "path": "/gone.png"}
+ ]}]}]});
+ let contents: Vec = history(&thread, None).into_iter().map(|u| u["content"].clone()).collect();
+ assert_eq!(contents[0], json!({"type": "image", "mimeType": "image/jpeg", "data": "/9j/"}));
+ assert_eq!(contents[1]["type"], "resource_link");
+ assert_eq!(contents[2], json!({"type": "image", "mimeType": "image/png", "data": encoded}));
+ assert_eq!(contents[3], json!({"type": "text", "text": "/gone.png"}));
+}
+
#[test]
fn history_preserves_async_questions_with_stable_answer_ids() {
let updates = history(
diff --git a/crates/ide-agent/src/native/codex/translate.rs b/crates/ide-agent/src/native/codex/translate.rs
index 56b2baff22..de572d83be 100644
--- a/crates/ide-agent/src/native/codex/translate.rs
+++ b/crates/ide-agent/src/native/codex/translate.rs
@@ -348,36 +348,18 @@ pub(super) fn user_input(prompt: &Value) -> Vec {
}
"resource" => {
let r = b.get("resource")?;
- let path = uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
+ let path = crate::images::uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
let text = r.get("text").and_then(Value::as_str)?;
Some(json!({ "type": "text", "text": format!("\n{text}\n ") }))
}
- "resource_link" => Some(json!({ "type": "text", "text": uri_path(b.get("uri")?.as_str()?) })),
+ "resource_link" => {
+ Some(json!({ "type": "text", "text": crate::images::uri_path(b.get("uri")?.as_str()?) }))
+ }
_ => None,
})
.collect()
}
-/// The path of a `file://` URI (percent-decoded); other URIs as they are.
-fn uri_path(uri: &str) -> String {
- let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
- let bytes = rest.as_bytes();
- let mut out = Vec::with_capacity(bytes.len());
- let mut i = 0;
- while i < bytes.len() {
- if bytes[i] == b'%'
- && let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
- {
- out.push(b);
- i += 3;
- } else {
- out.push(bytes[i]);
- i += 1;
- }
- }
- String::from_utf8_lossy(&out).into_owned()
-}
-
/// A `session/update` notification's `update` for content.
pub(super) fn chunk(kind: &str, text: &str) -> Value {
json!({ "sessionUpdate": kind, "content": { "type": "text", "text": text } })
@@ -467,6 +449,9 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
"imageView" => {
let path = item.get("path").and_then(Value::as_str).unwrap_or_default();
call.insert("locations".into(), json!([{ "path": path }]));
+ if done && let Some(image) = crate::images::from_file(std::path::Path::new(path)) {
+ call.insert("content".into(), json!([image_content(&image)]));
+ }
(format!("View {}", display_path(path, cwd)), "read")
}
"collabAgentToolCall" => {
@@ -482,7 +467,12 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
}
"contextCompaction" => ("Compact the conversation".to_owned(), "other"),
"sleep" => ("Wait".to_owned(), "other"),
- "imageGeneration" => ("Generate an image".to_owned(), "other"),
+ "imageGeneration" => {
+ if done && let Some(image) = generated_image(item) {
+ call.insert("content".into(), json!([image_content(&image)]));
+ }
+ ("Generate an image".to_owned(), "other")
+ }
_ => return None,
};
call.insert("sessionUpdate".into(), json!(if done { "tool_call_update" } else { "tool_call" }));
@@ -493,6 +483,19 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
Some(Value::Object(call))
}
+fn image_content(image: &crate::model::AgentImage) -> Value {
+ json!({ "type": "content", "content": crate::images::content(image) })
+}
+
+/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
+fn generated_image(item: &Value) -> Option {
+ if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
+ let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
+ return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
+ }
+ crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
+}
+
/// The output of a running command, as a `tool_call_update`.
pub(super) fn command_output(id: &str, output: &str) -> Value {
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "content": [text_content(&tail(output))] })
@@ -856,9 +859,23 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec {
"user_message_chunk",
c.get("text").and_then(Value::as_str).unwrap_or_default(),
)),
- Some("image") => out.push(json!({ "sessionUpdate": "user_message_chunk",
- "content": { "type": "resource_link", "uri": c.get("url"), "name": "image" } })),
- Some("localImage" | "mention" | "skill") => {
+ Some("image") => {
+ let url = c.get("url").and_then(Value::as_str).unwrap_or_default();
+ let content = crate::images::from_uri(url).map_or_else(
+ || json!({ "type": "resource_link", "uri": url, "name": "image" }),
+ |image| crate::images::content(&image),
+ );
+ out.push(json!({ "sessionUpdate": "user_message_chunk", "content": content }));
+ }
+ Some("localImage") => {
+ let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
+ out.push(match crate::images::from_file(std::path::Path::new(path)) {
+ Some(image) => json!({ "sessionUpdate": "user_message_chunk",
+ "content": crate::images::content(&image) }),
+ None => chunk("user_message_chunk", path),
+ });
+ }
+ Some("mention" | "skill") => {
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
out.push(chunk("user_message_chunk", path));
}
diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs
index e811db3da4..3c9ec82632 100644
--- a/crates/ide-agent/src/tests.rs
+++ b/crates/ide-agent/src/tests.rs
@@ -2688,7 +2688,7 @@ async fn forks_rollbacks_and_steering() {
}
// Undoing the last turn hands its message back.
- let undone = mgr.rollback(&task.id, 1).await.unwrap().unwrap();
+ let undone = mgr.rollback(&task.id, 1, false).await.unwrap().unwrap();
assert_eq!(undone.text, "again");
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1);
assert!(agent.calls.lock().iter().any(|c| c == "_openidea/rollback 1"));
@@ -2715,7 +2715,7 @@ async fn forks_rollbacks_and_steering() {
}
handle.state.lock().conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
let rewinds = agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count();
- let first = mgr.rollback(&task.id, 0).await.unwrap().unwrap();
+ let first = mgr.rollback(&task.id, 0, false).await.unwrap().unwrap();
assert_eq!(first.text, "again");
assert!(mgr.entries(&task.id, None).unwrap().is_empty());
assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_none());
@@ -3654,7 +3654,7 @@ async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
tokio::time::sleep(Duration::from_millis(600)).await;
assert!(!live(&mgr, &task.id));
- mgr.rollback(&task.id, 1).await.unwrap();
+ mgr.rollback(&task.id, 1, false).await.unwrap();
assert!(live(&mgr, &task.id));
tokio::time::sleep(Duration::from_millis(600)).await;
assert!(!live(&mgr, &task.id), "an agent started to undo turns stops too");
@@ -4665,6 +4665,157 @@ async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() {
}
}
+#[tokio::test(flavor = "multi_thread")]
+async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() {
+ for isolation in [Isolation::Local, Isolation::Worktree] {
+ let repo = Checkout::new(Eol::Lf);
+ repo.write("a.txt", "base\n");
+ repo.write("gone.txt", "base\n");
+ repo.commit("init");
+ let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
+ let task = mgr
+ .create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), isolation, ..Default::default() })
+ .await
+ .unwrap();
+ let cwd = task.cwd.0.clone();
+ let write = |rel: &str, text: &str| std::fs::write(cwd.join(rel), text).unwrap();
+ let read = |rel: &str| std::fs::read_to_string(cwd.join(rel)).ok();
+ let case = format!("{isolation:?}");
+
+ one_turn(&mgr, &task.id, None, || write("a.txt", "base\nturn 1\n")).await;
+ // The user's own work between the turns.
+ write("mine.txt", "mine\n");
+ one_turn(&mgr, &task.id, Some("more"), || {
+ write("a.txt", "base\nturn 1\nturn 2\n");
+ write("two.txt", "two\n");
+ })
+ .await;
+ one_turn(&mgr, &task.id, Some("last"), || {
+ write("a.txt", "base\nturn 1\nturn 2\nturn 3\n");
+ std::fs::remove_file(cwd.join("gone.txt")).unwrap();
+ })
+ .await;
+ // And after the last one.
+ write("later.txt", "later\n");
+
+ // After a restart: the turns' records are kept with the task.
+ mgr.shutdown();
+ let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
+ let undone = mgr.rollback(&task.id, 1, true).await.unwrap().unwrap();
+ assert_eq!(undone.text, "more", "{case}");
+ assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1, "{case}");
+ assert_eq!(read("a.txt").as_deref(), Some("base\nturn 1\n"), "{case}");
+ assert_eq!(read("gone.txt").as_deref(), Some("base\n"), "{case}");
+ assert_eq!(read("two.txt"), None, "{case}");
+ // There before the message was sent.
+ assert_eq!(read("mine.txt").as_deref(), Some("mine\n"), "{case}");
+ let later = match isolation {
+ // In the project's own checkout, a file no turn of the task changed is the user's.
+ Isolation::Local => Some("later\n"),
+ // In its own worktree, everything changed there since is the task's.
+ Isolation::Worktree => None,
+ };
+ assert_eq!(read("later.txt").as_deref(), later, "{case}");
+ assert_eq!(mgr.task(&task.id).unwrap().state.lock().turns.len(), 1, "{case}");
+
+ // Without `files` they stay; the first message takes the task back to its start.
+ one_turn(&mgr, &task.id, Some("retry"), || write("a.txt", "again\n")).await;
+ mgr.rollback(&task.id, 1, false).await.unwrap();
+ assert_eq!(read("a.txt").as_deref(), Some("again\n"), "{case}");
+ mgr.rollback(&task.id, 0, true).await.unwrap();
+ assert_eq!(read("a.txt").as_deref(), Some("base\n"), "{case}");
+ assert!(mgr.task(&task.id).unwrap().state.lock().turns.is_empty(), "{case}");
+ let left = std::fs::read_dir(repo.dir.join("store").join(format!("{}.turn", task.id)));
+ assert!(left.map_or(true, |mut d| d.next().is_none()), "{case}: no copies left");
+ mgr.delete(&task.id, true).await.unwrap();
+ }
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn a_message_sent_before_turns_were_recorded_cannot_take_the_files_back() {
+ let repo = Checkout::new(Eol::Lf);
+ repo.write("a.txt", "base\n");
+ repo.commit("init");
+ let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
+ let task = mgr
+ .create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), ..Default::default() })
+ .await
+ .unwrap();
+ one_turn(&mgr, &task.id, None, || repo.write("a.txt", "base\nturn 1\n")).await;
+ one_turn(&mgr, &task.id, Some("more"), || repo.write("a.txt", "base\nturn 1\nturn 2\n")).await;
+ one_turn(&mgr, &task.id, Some("last"), || repo.write("a.txt", "base\nturn 1\nturn 2\nturn 3\n")).await;
+ // As a task saved with its last turn's record only.
+ mgr.task(&task.id).unwrap().state.lock().turns[1] = None;
+ assert!(mgr.rollback(&task.id, 1, true).await.is_err());
+ assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 3, "nothing changed");
+ assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\nturn 3\n");
+ mgr.rollback(&task.id, 2, true).await.unwrap();
+ assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\n");
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn rolling_back_to_first_message_without_turn_record_checks_before_changing_anything() {
+ let repo = Checkout::new(Eol::Lf);
+ repo.write("a.txt", "base\n");
+ repo.write("b.txt", "base\n");
+ repo.commit("init");
+ repo.write("a.txt", "user edit\n");
+ let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
+ let task = mgr
+ .create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), ..Default::default() })
+ .await
+ .unwrap();
+ one_turn(&mgr, &task.id, None, || {
+ repo.write("a.txt", "agent edit\n");
+ repo.write("b.txt", "agent edit\n");
+ })
+ .await;
+ {
+ let handle = mgr.task(&task.id).unwrap();
+ let mut s = handle.state.lock();
+ s.turns[0] = None;
+ s.saved = None;
+ }
+ assert!(mgr.rollback(&task.id, 0, true).await.is_err());
+ assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1, "conversation stays intact");
+ assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_some(), "session stays intact");
+ assert_eq!(repo.read("a.txt"), "agent edit\n");
+ assert_eq!(repo.read("b.txt"), "agent edit\n");
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn local_turn_rollback_keeps_user_edits_to_other_turns_files_and_reverts_committed_files() {
+ let repo = Checkout::new(Eol::Lf);
+ repo.write("turn1.txt", "base\n");
+ repo.write("turn2.txt", "base\n");
+ repo.commit("init");
+ let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
+ let task = mgr
+ .create(NewAgentTask {
+ prompt: text("Hello"),
+ provider: "claude".into(),
+ isolation: Isolation::Local,
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ one_turn(&mgr, &task.id, None, || repo.write("turn1.txt", "turn 1\n")).await;
+ one_turn(&mgr, &task.id, Some("more"), || {
+ repo.write("turn2.txt", "turn 2\n");
+ repo.write("committed.txt", "from turn 2\n");
+ repo.git(&["add", "committed.txt"]);
+ repo.git(&["commit", "-q", "-m", "turn 2 commit"]);
+ })
+ .await;
+ // User edits a file from turn 1 after turn 2 finishes.
+ repo.write("turn1.txt", "turn 1 + user edit\n");
+
+ mgr.rollback(&task.id, 1, true).await.unwrap();
+ assert_eq!(repo.read("turn1.txt"), "turn 1 + user edit\n");
+ assert_eq!(repo.read("turn2.txt"), "base\n");
+ assert!(!repo.dir.join("committed.txt").exists());
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn rolling_back_the_whole_task_leaves_the_last_turn_nothing_to_list() {
let repo = Checkout::new(Eol::Lf);
diff --git a/crates/ide-agent/src/timeline.rs b/crates/ide-agent/src/timeline.rs
index 4cf3b36f78..f5d09bc26d 100644
--- a/crates/ide-agent/src/timeline.rs
+++ b/crates/ide-agent/src/timeline.rs
@@ -8,6 +8,9 @@ use std::collections::HashMap;
/// Tool output kept per call; longer output keeps its tail.
const MAX_OUTPUT: usize = 64 * 1024;
+/// Image files a read tool names that are shown when it reports none itself.
+const MAX_READ_IMAGES: usize = 4;
+
#[derive(Default)]
pub(crate) struct Timeline {
pub entries: Vec,
@@ -171,51 +174,17 @@ impl Timeline {
if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations"));
}
- let Some(content) = update.get("content").and_then(Value::as_array) else { return };
- let mut text = String::new();
- let mut new_diffs = Vec::new();
- let mut new_images = Vec::new();
- for item in content {
- match item.get("type").and_then(Value::as_str) {
- Some("content") => {
- let content = item.get("content");
- if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
- && let (Some(data), Some(mime)) =
- (image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
- && !data.is_empty()
- && mime.starts_with("image/")
- {
- new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
- }
- if let Some(t) = content_text(content) {
- if !text.is_empty() {
- text.push('\n');
- }
- text.push_str(&t);
- }
- }
- Some("diff") => {
- let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
- let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
- let (added, removed) = line_stats(old, new);
- new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
- }
- _ => {}
- }
+ if let Some(content) = update.get("content").and_then(Value::as_array) {
+ merge_content(content, output, images, diffs);
}
- if !text.is_empty() {
- // The command a call announced (`$ cmd`) stays above the result that replaces it.
- let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
- if let Some(command) = command.filter(|c| !text.starts_with(c)) {
- text = format!("{command}\n{text}");
- }
- *output = Some(tail(text));
- }
- if !new_diffs.is_empty() {
- *diffs = new_diffs;
- }
- if !new_images.is_empty() {
- *images = new_images;
+ // Agents that only name the image a read tool opened (Cursor): show the file itself.
+ if *status == AgentToolStatus::Completed && kind == "read" && images.is_empty() {
+ images.extend(
+ locs.iter()
+ .filter(|p| p.0.is_absolute())
+ .take(MAX_READ_IMAGES)
+ .filter_map(|p| crate::images::from_file(&p.0)),
+ );
}
}
@@ -382,6 +351,54 @@ fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option
})
}
+/// Folds a tool update's content into its output, diffs and images.
+fn merge_content(
+ content: &[Value],
+ output: &mut Option,
+ images: &mut Vec,
+ diffs: &mut Vec,
+) {
+ let mut text = String::new();
+ let mut new_diffs = Vec::new();
+ let mut new_images = Vec::new();
+ for item in content {
+ match item.get("type").and_then(Value::as_str) {
+ Some("content") => {
+ let content = item.get("content");
+ if let Some(image) = content.and_then(crate::images::from_content) {
+ new_images.push(image);
+ } else if let Some(t) = content_text(content) {
+ if !text.is_empty() {
+ text.push('\n');
+ }
+ text.push_str(&t);
+ }
+ }
+ Some("diff") => {
+ let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
+ let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
+ let (added, removed) = line_stats(old, new);
+ new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
+ }
+ _ => {}
+ }
+ }
+ if !text.is_empty() {
+ // The command a call announced (`$ cmd`) stays above the result that replaces it.
+ let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
+ if let Some(command) = command.filter(|c| !text.starts_with(c)) {
+ text = format!("{command}\n{text}");
+ }
+ *output = Some(tail(text));
+ }
+ if !new_diffs.is_empty() {
+ *diffs = new_diffs;
+ }
+ if !new_images.is_empty() {
+ *images = new_images;
+ }
+}
+
/// The text of a list of content blocks, one per line.
pub(crate) fn blocks_text(content: Option<&Value>) -> String {
let blocks = content.and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
@@ -432,6 +449,7 @@ fn tail(mut text: String) -> String {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::model::AgentImage;
use serde_json::json;
#[test]
@@ -478,6 +496,47 @@ mod tests {
assert_eq!(serde_json::from_str::(&saved).unwrap(), t.entries[0]);
}
+ #[test]
+ fn tool_images_come_from_linked_files_and_resource_blobs() {
+ let dir = tempfile::tempdir().unwrap();
+ let png = dir.path().join("out.png");
+ std::fs::write(&png, b"\x89PNG\r\n").unwrap();
+ let mut t = Timeline::default();
+ t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "r", "title": "Read", "kind": "read"}));
+ t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "r", "content": [
+ {"type": "content", "content": {"type": "text", "text": "Read the image"}},
+ {"type": "content", "content": {"type": "resource_link", "uri": crate::file_uri(&png), "name": "out.png"}},
+ {"type": "content", "content": {"type": "resource", "resource": {"uri": "mem:1", "mimeType": "image/gif", "blob": "R0lG"}}}
+ ]}));
+ let AgentEntry::Tool { images, output, .. } = &t.entries[0] else { panic!() };
+ let types: Vec<&str> = images.iter().map(|i| i.mime_type.as_str()).collect();
+ assert_eq!(types, ["image/png", "image/gif"]);
+ assert_eq!(output.as_deref(), Some("Read the image"));
+ }
+
+ #[test]
+ fn a_completed_read_shows_the_image_file_it_names() {
+ let dir = tempfile::tempdir().unwrap();
+ let png = dir.path().join("icon.png");
+ std::fs::write(&png, b"\x89PNG\r\n").unwrap();
+ let text = dir.path().join("a.rs");
+ std::fs::write(&text, b"fn main() {}").unwrap();
+ let mut t = Timeline::default();
+ for (id, path) in [("img", &png), ("src", &text)] {
+ t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": id, "title": "Read", "kind": "read",
+ "locations": [{"path": path}]}));
+ }
+ let images = |t: &Timeline, i: usize| match &t.entries[i] {
+ AgentEntry::Tool { images, .. } => images.len(),
+ _ => panic!(),
+ };
+ assert_eq!(images(&t, 0), 0, "not before the read completes");
+ for id in ["img", "src"] {
+ t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed"}));
+ }
+ assert_eq!((images(&t, 0), images(&t, 1)), (1, 0));
+ }
+
#[test]
fn chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default();
diff --git a/crates/ide-agent/src/worktree.rs b/crates/ide-agent/src/worktree.rs
index 8a1ffab8b6..b0ab4e99f3 100644
--- a/crates/ide-agent/src/worktree.rs
+++ b/crates/ide-agent/src/worktree.rs
@@ -697,12 +697,24 @@ pub(crate) fn snapshot(cwd: &Path) -> IdeResult> {
if let Some(rel) = nested_rel(&base, repo, &roots, &s.path) {
out.insert(rel, stamp(&s.path));
}
+ if let Some(old) = &s.renamed_from
+ && let Some(rel) = nested_rel(&base, repo, &roots, &repo.root().join(old))
+ {
+ out.entry(rel).or_insert(None);
+ }
}
}
return Ok(out);
}
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
- Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
+ let mut out = BTreeMap::new();
+ for s in repo.status()? {
+ out.insert(s.rel_path, stamp(&s.path));
+ if let Some(old) = s.renamed_from {
+ out.entry(old).or_insert(None);
+ }
+ }
+ Ok(out)
}
/// The files whose state changed between two snapshots of a checkout: edited, new, deleted,
@@ -763,6 +775,36 @@ pub(crate) fn save_before(cwd: &Path, before: &BTreeMap, dir: &Pa
Ok(saved)
}
+fn restore_content(
+ cwd: &Path,
+ rev: Option<&str>,
+ change: &AgentChange,
+ before: &BTreeMap,
+ saved: Option<&Path>,
+) -> IdeResult>> {
+ match before.get(&change.rel_path) {
+ Some(None) => Ok(None),
+ Some(Some(_)) => {
+ let copy =
+ saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
+ IdeError::invalid(format!(
+ "{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
+ change.rel_path
+ ))
+ })?;
+ Ok(Some(std::fs::read(copy)?))
+ }
+ None => match rev {
+ Some(rev) => {
+ let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
+ let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
+ repo.file_bytes_at(&change.path.0, Some(rev))
+ }
+ None => Ok(None),
+ },
+ }
+}
+
/// Rolls `change` back: to the copy saved when the task started when the file had changes
/// then (`before`, `saved` holding the copies), otherwise to `rev` (removed when `rev` lacks
/// it, or when there is no `rev`: the repository had no commits).
@@ -773,28 +815,35 @@ pub(crate) fn restore(
before: &BTreeMap,
saved: Option<&Path>,
) -> IdeResult<()> {
- let content = match before.get(&change.rel_path) {
- Some(None) => None,
- Some(Some(_)) => {
- let copy =
- saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
- IdeError::invalid(format!(
- "{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
- change.rel_path
- ))
- })?;
- Some(std::fs::read(copy)?)
- }
- None => match rev {
- Some(rev) => {
- let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
- let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
- repo.file_bytes_at(&change.path.0, Some(rev))?
- }
- None => None,
- },
+ put(&change.path.0, restore_content(cwd, rev, change, before, saved)?)
+}
+
+/// The files the task changed since it started, with what to put back. Fails, changing
+/// nothing, when one can't be put back.
+pub(crate) fn plan_restore(
+ at: &TaskBase,
+ before: &BTreeMap,
+ saved: Option<&Path>,
+ touched: Option<&BTreeSet>,
+) -> IdeResult> {
+ let changes = made_by_task(at.changes(before, None)?, touched);
+ let rev = at.rev()?;
+ let sources = match rev.as_deref() {
+ Some(rev) => rename_sources(at.cwd(), rev)?,
+ None => Default::default(),
};
- put(&change.path.0, content)
+ let mut seen = BTreeSet::new();
+ let mut out = Vec::new();
+ for change in &changes {
+ for change in std::iter::once(change).chain(sources.get(&change.rel_path)) {
+ if !seen.insert(change.rel_path.clone()) {
+ continue;
+ }
+ let content = restore_content(at.cwd(), rev.as_deref(), change, before, saved)?;
+ out.push(PutBack { rel: change.rel_path.clone(), path: change.path.0.clone(), content });
+ }
+ }
+ Ok(out)
}
/// Writes `content` to `path`, or removes the file when there is none.
@@ -819,7 +868,7 @@ pub(crate) fn saved_copy(dir: &Path, rel: &str) -> Option> {
std::fs::read(dir.join(saved_name(rel))).ok()
}
-/// The checkout as the task's last turn started: what that turn's changes are compared with
+/// The checkout as one of the task's turns started: what that turn's changes are compared with
/// and rolled back to. Recorded like the task's own start: `HEAD`, the files already changed,
/// and copies of those.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -840,13 +889,45 @@ pub(crate) struct TurnStart {
/// The files that changed while the turn ran, recorded as it ended (`None` while it runs).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub changed: Option>,
+ /// The copies are named by file and stamp, so the turns share them; the turn recorded
+ /// before that named them by file alone.
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub stamped: bool,
+}
+
+fn is_false(b: &bool) -> bool {
+ !*b
+}
+
+/// The name of the copy of `rel` as stamped `stamp`: the same while the file is unchanged.
+fn turn_copy_name(rel: &str, stamp: &Stamp) -> String {
+ let mut hasher = blake3::Hasher::new();
+ hasher.update(rel.as_bytes());
+ hasher.update(&[0]);
+ if let Some((len, modified)) = stamp {
+ hasher.update(&[1]);
+ hasher.update(&len.to_le_bytes());
+ hasher.update(&modified.to_le_bytes());
+ }
+ let hex = hasher.finalize().to_hex();
+ format!("t{}", &hex[..16])
+}
+
+impl TurnStart {
+ /// The name of the copy saved of `rel` as the turn began.
+ fn copy_name(&self, rel: &str) -> Option {
+ if !self.stamped {
+ return Some(saved_name(rel));
+ }
+ Some(turn_copy_name(rel, self.before.get(rel)?))
+ }
}
/// Records the checkout at `cwd` as a turn starts, with copies of its changed files in `dir`.
-/// The copies `previous` saved of files unchanged since are kept rather than made again, so
+/// A copy an earlier turn saved of a file unchanged since is used rather than made again, so
/// starting a turn copies little more than what the turn before it changed.
-pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult {
- let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::default()) };
+pub(crate) fn start_turn(cwd: &Path, dir: &Path) -> IdeResult {
+ let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart { stamped: true, ..Default::default() }) };
let mut heads = BTreeMap::new();
let head = if at.nested {
for repo in &at.repos {
@@ -859,37 +940,95 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
// As the turn's end is read, so the two compare.
let before = snapshot(cwd)?;
let mut saved = BTreeSet::new();
- match previous {
- Some(previous) => {
- for rel in &previous.saved {
- let unchanged =
- before.get(rel).is_some_and(|now| now.is_some() && previous.before.get(rel) == Some(now));
- if unchanged {
- saved.insert(rel.clone());
- } else {
- let _ = std::fs::remove_file(dir.join(saved_name(rel)));
- }
- }
- }
- None => {
- let _ = std::fs::remove_dir_all(dir);
- }
- }
for (rel, stamp) in &before {
let path = at.base.join(rel);
- if stamp.is_none()
- || saved.contains(rel)
- || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
- {
+ if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
+ continue;
+ }
+ let copy = dir.join(turn_copy_name(rel, stamp));
+ if copy.is_file() {
+ saved.insert(rel.clone());
continue;
}
std::fs::create_dir_all(dir)?;
// One that can't be copied is listed but can't be rolled back, as a large one.
- if std::fs::copy(&path, dir.join(saved_name(rel))).is_ok() {
+ if std::fs::copy(&path, ©).is_ok() {
saved.insert(rel.clone());
}
}
- Ok(TurnStart { head, heads, before, saved, changed: None })
+ Ok(TurnStart { head, heads, before, saved, changed: None, stamped: true })
+}
+
+/// Removes the copies in `dir` that none of `turns` uses any more.
+pub(crate) fn prune_turn_copies<'a>(dir: &Path, turns: impl IntoIterator- ) {
+ let used: BTreeSet
=
+ turns.into_iter().flat_map(|t| t.saved.iter().filter_map(move |rel| t.copy_name(rel))).collect();
+ let Ok(read) = std::fs::read_dir(dir) else { return };
+ for entry in read.flatten() {
+ if !used.contains(&*entry.file_name().to_string_lossy()) {
+ let _ = std::fs::remove_file(entry.path());
+ }
+ }
+}
+
+/// A file to put back as it was.
+pub(crate) struct PutBack {
+ /// Relative to the checkout, as the task names it.
+ pub rel: String,
+ pub path: PathBuf,
+ /// `None`: there was no file.
+ pub content: Option>,
+}
+
+/// The files among `rels` that differ from how they were as the turn `start` began, with what
+/// to put back. Fails, changing nothing, when one can't be put back.
+pub(crate) fn rewind(cwd: &Path, start: &TurnStart, dir: &Path, rels: &BTreeSet) -> IdeResult> {
+ let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
+ let mut lower_counts: BTreeMap = BTreeMap::new();
+ for rel in rels {
+ *lower_counts.entry(rel.to_lowercase()).or_default() += 1;
+ }
+ let mut out = Vec::new();
+ for rel in rels {
+ let path = at.base.join(rel);
+ // A folder (a submodule, say) has nothing to put back.
+ if path.is_dir() {
+ continue;
+ }
+ let then = at_turn_start(&at, rel, start, dir)?;
+ // On a case-insensitive disk, `existing(&path)` can read a case-only rename's new name;
+ // keep the write so `put_back` deletes the new name and recreates the old one.
+ let case_collision = lower_counts.get(&rel.to_lowercase()).is_some_and(|&n| n > 1);
+ if !case_collision && existing(&path).is_some_and(|now| now == then) {
+ continue;
+ }
+ out.push(PutBack { rel: rel.clone(), path, content: then });
+ }
+ Ok(out)
+}
+
+/// Writes what `rewind` or `plan_restore` planned, returning the files back to their saved
+/// pre-task copy so `before` can be restamped.
+pub(crate) fn put_back(
+ mut planned: Vec,
+ before: &BTreeMap,
+ saved: Option<&Path>,
+) -> IdeResult> {
+ // Removals first so a case-only rename on a case-insensitive disk ends at its old name.
+ planned.sort_by_key(|f| f.content.is_some());
+ let mut restamped = Vec::new();
+ for file in planned {
+ let should_restamp = matches!(before.get(&file.rel), Some(Some(_)))
+ && file
+ .content
+ .as_deref()
+ .is_some_and(|bytes| saved.and_then(|d| saved_copy(d, &file.rel)).as_deref() == Some(bytes));
+ put(&file.path, file.content)?;
+ if should_restamp {
+ restamped.push((file.rel, stamp(&file.path)));
+ }
+ }
+ Ok(restamped)
}
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
@@ -919,7 +1058,12 @@ pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec IdeResult>> {
match start.before.get(rel) {
Some(None) => Ok(None),
- Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() {
+ Some(Some(_)) => match start
+ .saved
+ .contains(rel)
+ .then(|| start.copy_name(rel).and_then(|name| std::fs::read(dir.join(name)).ok()))
+ .flatten()
+ {
Some(bytes) => Ok(Some(bytes)),
None => Err(IdeError::invalid(format!(
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
@@ -1312,30 +1456,64 @@ mod tests {
git(&repo, &["commit", "-q", "-m", "init"]);
let dir = tmp.path().join("turn");
let set = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect::>();
+ let copy = |turn: &TurnStart, rel: &str| std::fs::read(dir.join(turn.copy_name(rel).unwrap())).ok();
+ let at = |turn: &TurnStart, rel: &str| {
+ at_turn_start(&TurnRepos::of(&repo).unwrap().unwrap(), rel, turn, &dir).unwrap()
+ };
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
std::fs::write(repo.join("b.txt"), "b\n").unwrap();
- let first = start_turn(&repo, &dir, None).unwrap();
+ let first = start_turn(&repo, &dir).unwrap();
assert_eq!(first.saved, set(&["a.txt", "b.txt"]));
// A copy made again would replace this mark.
- std::fs::write(dir.join(saved_name("b.txt")), "kept\n").unwrap();
+ std::fs::write(dir.join(first.copy_name("b.txt").unwrap()), "kept\n").unwrap();
std::thread::sleep(std::time::Duration::from_millis(10));
std::fs::write(repo.join("a.txt"), "turn two\n").unwrap();
- let second = start_turn(&repo, &dir, Some(&first)).unwrap();
+ let second = start_turn(&repo, &dir).unwrap();
assert_eq!(second.saved, set(&["a.txt", "b.txt"]));
- assert_eq!(saved_copy(&dir, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
- assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"kept\n"[..]));
+ assert_eq!(copy(&second, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
+ assert_eq!(copy(&second, "b.txt").as_deref(), Some(&b"kept\n"[..]));
+ // The first turn keeps its own copy of the file changed since.
+ assert_eq!(at(&first, "a.txt").as_deref(), Some(&b"turn 1\n"[..]));
- // Back as committed: nothing to keep a copy of.
+ // Back as committed: nothing to keep a copy of, and the committed text is the start.
git(&repo, &["checkout", "--", "a.txt"]);
- let third = start_turn(&repo, &dir, Some(&second)).unwrap();
+ let third = start_turn(&repo, &dir).unwrap();
assert_eq!(third.saved, set(&["b.txt"]));
- assert_eq!(saved_copy(&dir, "a.txt"), None);
- // Without a record of the last turn (a task from before), every copy is made afresh.
- let fresh = start_turn(&repo, &dir, None).unwrap();
- assert_eq!(fresh.saved, set(&["b.txt"]));
- assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"b\n"[..]));
+ assert_eq!(at(&third, "a.txt").as_deref(), Some(&b"base\n"[..]));
+
+ // Dropping the earlier turns drops the copies only they used.
+ prune_turn_copies(&dir, [&third]);
+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
+ assert_eq!(copy(&third, "b.txt").as_deref(), Some(&b"kept\n"[..]));
+ }
+
+ #[test]
+ fn put_back_removes_new_name_before_writing_old_name_for_case_only_rename() {
+ let tmp = tempfile::tempdir().unwrap();
+ let repo = tmp.path().join("repo");
+ std::fs::create_dir(&repo).unwrap();
+ git(&repo, &["init", "-q", "-b", "main"]);
+ std::fs::write(repo.join("A.txt"), "upper\n").unwrap();
+ git(&repo, &["add", "."]);
+ git(&repo, &["commit", "-q", "-m", "init"]);
+
+ let dir = tmp.path().join("turn");
+ let start = start_turn(&repo, &dir).unwrap();
+ git(&repo, &["mv", "A.txt", "a.txt"]);
+ let changed = changed_in_turn(&repo, &start).unwrap().1;
+ let planned = rewind(&repo, &start, &dir, &changed).unwrap();
+ put_back(planned, &BTreeMap::new(), None).unwrap();
+
+ assert_eq!(std::fs::read_to_string(repo.join("A.txt")).unwrap(), "upper\n");
+ let entries: Vec = std::fs::read_dir(&repo)
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .map(|e| e.file_name().to_string_lossy().into_owned())
+ .filter(|n| n != ".git")
+ .collect();
+ assert_eq!(entries, ["A.txt"]);
}
#[cfg(unix)]
@@ -1350,7 +1528,7 @@ mod tests {
git(&repo, &["commit", "-q", "-m", "init"]);
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
let dir = tmp.path().join("turn");
- let start = start_turn(&repo, &dir, None).unwrap();
+ let start = start_turn(&repo, &dir).unwrap();
std::fs::write(repo.join("a.txt"), "turn 2\n").unwrap();
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
let link = tmp.path().join("link");
diff --git a/crates/ide-android/Cargo.toml b/crates/ide-android/Cargo.toml
index 1a0b59bb20..21c049e4d7 100644
--- a/crates/ide-android/Cargo.toml
+++ b/crates/ide-android/Cargo.toml
@@ -10,3 +10,6 @@ ide-core.workspace = true
serde.workspace = true
specta.workspace = true
which = "8"
+
+[dev-dependencies]
+tempfile.workspace = true
diff --git a/crates/ide-android/src/lib.rs b/crates/ide-android/src/lib.rs
index a959c98f00..2029a74dd9 100644
--- a/crates/ide-android/src/lib.rs
+++ b/crates/ide-android/src/lib.rs
@@ -12,11 +12,12 @@ mod process;
pub use model::*;
+use ide_core::process::{own_group, prepare};
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::path::{Path, PathBuf};
-use std::process::Command;
+use std::process::{Command, Stdio};
use std::sync::OnceLock;
-use std::time::Duration;
+use std::time::{Duration, Instant};
/// `adb devices` is quick unless it starts the daemon, which can take a moment.
const DEVICES: Duration = Duration::from_secs(20);
@@ -28,6 +29,8 @@ const TAIL_LINES: u32 = 200;
/// while `IDLE` makes sure a quiet stream still shows its last line promptly.
const BATCH_IDLE: Duration = Duration::from_millis(60);
const BATCH_MAX: usize = 300;
+/// How long a started emulator gets to fail: a locked or broken AVD exits within it.
+const EMULATOR_STARTUP: Duration = Duration::from_secs(3);
fn exe(name: &str) -> String {
if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }
@@ -91,6 +94,51 @@ fn executable() -> IdeResult {
})
}
+/// The SDK's `emulator` executable, which starts AVDs.
+pub fn emulator_executable() -> Option {
+ let name = exe("emulator");
+ sdk_roots().into_iter().map(|root| root.join("emulator").join(&name)).find(|p| p.is_file())
+}
+
+/// Starts AVD `avd` in its own process group, so it
+/// outlives whoever asked: a restarted `flutter daemon`, a closed project, the IDE. Fails when
+/// the emulator exits within its first seconds, with what it printed.
+pub fn launch_emulator(avd: &str) -> IdeResult<()> {
+ let emulator = emulator_executable().ok_or_else(|| {
+ IdeError::unavailable(
+ "the Android emulator was not found: install it with the Android SDK Manager, or set ANDROID_HOME",
+ )
+ })?;
+ start_emulator(&emulator, avd)
+}
+
+fn start_emulator(emulator: &Path, avd: &str) -> IdeResult<()> {
+ let name: String = avd.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
+ let log_path = std::env::temp_dir().join(format!("openidea-emulator-{name}.log"));
+ let log = std::fs::File::create(&log_path)?;
+ let mut cmd = Command::new(emulator);
+ cmd.arg("-avd").arg(avd);
+ cmd.stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log);
+ let mut child = prepare(own_group(&mut cmd)).spawn()?;
+ let deadline = Instant::now() + EMULATOR_STARTUP;
+ while Instant::now() < deadline {
+ if let Some(status) = child.try_wait()? {
+ let output = std::fs::read_to_string(&log_path).unwrap_or_default();
+ let tail: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
+ let tail = tail[tail.len().saturating_sub(8)..].join("\n");
+ return Err(IdeError::unavailable(if tail.is_empty() {
+ format!("the emulator exited ({status})")
+ } else {
+ tail
+ }));
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+ // Reaps it whenever it ends.
+ std::thread::spawn(move || child.wait());
+ Ok(())
+}
+
/// Connected devices, online ones first; starting the adb daemon when needed.
pub fn devices() -> IdeResult> {
let adb = executable()?;
@@ -206,6 +254,30 @@ mod tests {
}
}
+ #[cfg(unix)]
+ #[test]
+ fn an_emulator_that_fails_at_once_says_why_and_one_that_runs_is_left_running() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+ let script = |name: &str, body: &str| {
+ let path = dir.path().join(name);
+ std::fs::write(&path, format!("#!/bin/sh\n{body}")).unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
+ path
+ };
+ let broken = script("broken", "echo \"PANIC: Missing emulator engine for $2\" >&2\nexit 1\n");
+ let e = start_emulator(&broken, "Pixel_9").unwrap_err();
+ assert_eq!(e.message, "PANIC: Missing emulator engine for Pixel_9");
+
+ let args = dir.path().join("args");
+ let running =
+ script("running", &format!("echo $$ > '{0}.pid'\necho \"$@\" > '{0}'\nexec sleep 30\n", args.display()));
+ start_emulator(&running, "Pixel_9").unwrap();
+ assert_eq!(std::fs::read_to_string(&args).unwrap().trim(), "-avd Pixel_9");
+ let pid = std::fs::read_to_string(dir.path().join("args.pid")).unwrap();
+ assert!(Command::new("kill").arg(pid.trim()).status().unwrap().success(), "still running");
+ }
+
#[test]
fn executable_is_absolute_when_found() {
if let Some(adb) = adb_executable() {
diff --git a/crates/ide-build/src/compile/mod.rs b/crates/ide-build/src/compile/mod.rs
index 37732b1af6..532beeff91 100644
--- a/crates/ide-build/src/compile/mod.rs
+++ b/crates/ide-build/src/compile/mod.rs
@@ -15,12 +15,12 @@ pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
- SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, module_classpaths,
- single_file_classpath, single_file_target,
+ SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
+ has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
};
pub use structure::{
- StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_outputs, structure_plan,
- structure_war_plan, structure_web_artifacts,
+ StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
+ structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
};
pub use up_to_date::{menu_up_to_date, record_menu_build};
diff --git a/crates/ide-build/src/compile/parse.rs b/crates/ide-build/src/compile/parse.rs
index d33e5d4384..99d9207321 100644
--- a/crates/ide-build/src/compile/parse.rs
+++ b/crates/ide-build/src/compile/parse.rs
@@ -200,19 +200,22 @@ fn kotlin_line(line: &str) -> Option {
kotlin_location(rest, severity)
}
-/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`.
+/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`
+/// (and localized javac prefixes such as Chinese/Japanese `错误:` / `錯誤:` / `エラー:` / `警告:`).
fn javac_header(line: &str) -> Option {
let (path, ln, col, rest) = path_line_col(line)?;
if !looks_like_source_path(path) {
return None;
}
let rest = rest.trim_start_matches(':').trim_start();
- let (severity, msg) = if let Some(m) = rest.strip_prefix("error:") {
- (Severity::Error, m)
- } else {
- let m = rest.strip_prefix("warning:")?;
- (Severity::Warning, m)
- };
+ let (severity, msg) = ["error:", "错误:", "錯誤:", "エラー:"]
+ .into_iter()
+ .find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Error, m)))
+ .or_else(|| {
+ ["warning:", "警告:"]
+ .into_iter()
+ .find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Warning, m)))
+ })?;
Some(RawMessage::new(severity, msg.trim(), ColUnit::Char).at(path, ln, col))
}
@@ -555,6 +558,31 @@ mod tests {
assert_eq!(out[1].text, "[removal] finalize() has been deprecated");
}
+ #[test]
+ fn localized_javac_errors_and_warnings() {
+ let out = parse(
+ Format::Gradle,
+ "/p/src/A.java:12: 错误: 找不到符号\n\
+ \x20 Foo foo = new Foo();\n\
+ \x20 ^\n\
+ \x20 符号: 类 Foo\n\
+ \x20 位置: 类 A\n\
+ /p/src/B.java:5: 錯誤: 需要 ';'\n\
+ \x20 int x = 1\n\
+ \x20 ^\n\
+ /p/src/C.java:8: 警告: [deprecation] old() 已过时\n\
+ \x20 old();\n\
+ \x20 ^\n",
+ );
+ assert_eq!(out.len(), 3, "{out:?}");
+ assert_eq!(pos(&out[0]), (Severity::Error, "/p/src/A.java", 12, Some(9)));
+ assert_eq!(out[0].text, "找不到符号\n符号: 类 Foo\n位置: 类 A");
+ assert_eq!(pos(&out[1]), (Severity::Error, "/p/src/B.java", 5, Some(14)));
+ assert_eq!(out[1].text, "需要 ';'");
+ assert_eq!(pos(&out[2]), (Severity::Warning, "/p/src/C.java", 8, Some(5)));
+ assert_eq!(out[2].text, "[deprecation] old() 已过时");
+ }
+
#[test]
fn gradle_kotlin() {
let out = parse(
diff --git a/crates/ide-build/src/compile/single.rs b/crates/ide-build/src/compile/single.rs
index b87f5bee40..8bd7c5f63f 100644
--- a/crates/ide-build/src/compile/single.rs
+++ b/crates/ide-build/src/compile/single.rs
@@ -1,4 +1,4 @@
-//! Single-file Java compilation with `javac` for the Compile File action (#2476).
+//! Single-file Java compilation with `javac` for the Recompile action (#2476).
//!
//! A module build (`-pl … -am`) still walks every upstream module, and packaging
//! walks the whole reactor; compiling one file only needs that file's module
@@ -6,12 +6,93 @@
use super::*;
use serde::{Deserialize, Serialize};
use std::fs;
-use std::process::Command as ProcCommand;
/// Output file of the `dependency:build-classpath` probe, relative to each module.
const CP_FILE: &str = "target/ide-compile-cp.txt";
// Older records include undeclared reactor test outputs even in runtime classpaths.
const CLASSPATH_CACHE_VERSION: u32 = 1;
+const GRADLE_COMPILE_CP_INIT_SCRIPT: &str = include_str!("../gradle-compile-cp.init.gradle");
+
+pub(super) fn is_java_file(file: &Path) -> IdeResult {
+ if file.extension().is_none_or(|ext| !ext.eq_ignore_ascii_case("java")) {
+ return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
+ }
+ if !file.is_file() {
+ return Err(IdeError::not_found("no Java source found for single-file compilation"));
+ }
+ Ok(file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())
+}
+
+pub(super) fn is_test_source(rel: &str) -> bool {
+ let parts: Vec<&str> = rel.split(['/', '\\']).collect();
+ parts.windows(2).any(|w| w == ["src", "test"])
+}
+
+pub(super) fn java_home_major(env: &BTreeMap) -> Option {
+ let home = env.get("JAVA_HOME").filter(|h| !h.trim().is_empty())?;
+ let release = fs::read_to_string(Path::new(home).join("release")).ok()?;
+ let value = release.lines().find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))?;
+ let value = value.trim().trim_matches(['"', '\'']);
+ language_release(value)
+}
+
+/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
+pub(super) fn release_args(level: Option, jdk_major: Option) -> Vec {
+ let Some(level) = level else { return Vec::new() };
+ if jdk_major.is_none_or(|m| m >= 9) {
+ vec!["--release".into(), level.to_string()]
+ } else {
+ vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
+ }
+}
+
+pub(super) fn join_classpath(entries: impl IntoIterator- ) -> String {
+ let separator = if cfg!(windows) { ";" } else { ":" };
+ let mut seen = HashSet::new();
+ let mut out = Vec::new();
+ for entry in entries {
+ if !entry.is_empty() && seen.insert(entry.clone()) {
+ out.push(entry);
+ }
+ }
+ out.join(separator)
+}
+
+#[allow(clippy::too_many_arguments)]
+pub(super) fn build_javac_step(
+ javac: &str,
+ cwd: &Path,
+ out_dir: &Path,
+ classpath: &str,
+ sources: &[PathBuf],
+ release: Vec
,
+ file: &Path,
+ env: BTreeMap,
+) -> IdeResult {
+ fs::create_dir_all(out_dir)
+ .map_err(|e| IdeError::internal(format!("cannot create {} ({e})", out_dir.display())))?;
+ // Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
+ let mut step = BuildStep::new(javac, &[], cwd, Format::Gradle);
+ step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]);
+ step.args.extend(["-d".into(), out_dir.to_string_lossy().into_owned()]);
+ if !classpath.is_empty() {
+ step.args.extend(["-cp".into(), classpath.to_owned()]);
+ }
+ // Classes of the module that were never built (or are older than their source) are read
+ // from its sources; only `file` is written, so a test compile never puts main classes
+ // into test-classes.
+ if !sources.is_empty() {
+ let separator = if cfg!(windows) { ";" } else { ":" };
+ step.args.push("-sourcepath".into());
+ step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::>().join(separator));
+ step.args.push("-implicit:none".into());
+ }
+ step.args.extend(release);
+ step.args.push(file.to_string_lossy().into_owned());
+ step.env = env;
+ step.mkdirs = vec![out_dir.to_path_buf()];
+ Ok(step)
+}
/// The resolved dependency classpath for one module and scope, tied to the same
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
@@ -41,12 +122,7 @@ pub struct SingleFileTarget {
/// Locates the linked Maven module owning a `.java` source file.
pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeResult {
- if file.extension().is_none_or(|ext| ext != "java") {
- return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
- }
- if !file.is_file() {
- return Err(IdeError::not_found("no Java source found for single-file compilation"));
- }
+ is_java_file(file)?;
let Some(m) = &model.maven else {
return Err(IdeError::not_found("no linked Maven project found for module"));
};
@@ -70,8 +146,7 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
let top_dir = subdir(root, &top.dir);
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
// Test sources see the test classpath and compile into test classes.
- let parts: Vec<&str> = rel.split('/').collect();
- let test = parts.windows(2).any(|w| w == ["src", "test"]);
+ let test = is_test_source(&rel);
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
}
@@ -112,7 +187,17 @@ pub fn find_javac(env: &BTreeMap) -> String {
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
pub fn single_file_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) -> IdeResult {
- classpath(root, model, target, "test", false)
+ single_file_classpath_cancellable(root, model, target, &CancellationToken::new())
+}
+
+fn single_file_classpath_cancellable(
+ root: &Path,
+ model: &BuildModel,
+ target: &SingleFileTarget,
+ cancel: &CancellationToken,
+) -> IdeResult {
+ let scope = if target.test { "test" } else { "compile" };
+ classpath(root, model, target, scope, false, cancel)
}
/// Runtime (or test) dependency classpath for a launch module.
@@ -172,10 +257,12 @@ pub fn module_classpaths(
}
let scope = if test { "test" } else { "runtime" };
let targets: Vec<&SingleFileTarget> = probes.iter().map(|p| &p.0).collect();
- let classpaths = match classpaths(root, model, &targets, scope, true) {
+ let classpaths = match classpaths(root, model, &targets, scope, true, cancel) {
Ok(classpaths) => classpaths,
// Another module's failure must not cost this launch its own probe.
- Err(_) if targets.len() > 1 && !cancel.is_cancelled() => classpaths(root, model, &targets[..1], scope, true)?,
+ Err(_) if targets.len() > 1 && !cancel.is_cancelled() => {
+ classpaths(root, model, &targets[..1], scope, true, cancel)?
+ }
Err(e) => return Err(e),
};
if cancel.is_cancelled() {
@@ -236,8 +323,9 @@ fn classpath(
target: &SingleFileTarget,
scope: &str,
compile_first: bool,
+ cancel: &CancellationToken,
) -> IdeResult {
- Ok(classpaths(root, model, &[target], scope, compile_first)?.pop().unwrap())
+ Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
}
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
@@ -247,6 +335,7 @@ fn classpaths(
targets: &[&SingleFileTarget],
scope: &str,
compile_first: bool,
+ cancel: &CancellationToken,
) -> IdeResult> {
let top = &targets[0].top;
let probe = CP_FILE;
@@ -274,16 +363,17 @@ fn classpaths(
}
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &top.dir);
- let mut command = ProcCommand::new(&top.command);
- command.args(&args).envs(&top.env).current_dir(&top_dir);
- let status = ide_core::process::prepare(&mut command)
- .output()
- .map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?;
- if !status.status.success() {
- let stdout = String::from_utf8_lossy(&status.stdout);
- let stderr = String::from_utf8_lossy(&status.stderr);
+ let owned_args: Vec = args.into_iter().map(str::to_owned).collect();
+ let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
+ if e.kind == ide_core::error::ErrorKind::Cancelled {
+ e
+ } else {
+ IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
+ }
+ })?;
+ if !out.success {
// Maven reports reactor/dependency failures on stdout, not only stderr.
- let tail: Vec<&str> = stdout.lines().chain(stderr.lines()).filter(|l| !l.trim().is_empty()).collect();
+ let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
let tail = tail.iter().rev().take(5).rev().cloned().collect::>().join("\n");
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
}
@@ -325,39 +415,14 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
})?;
let separator = if cfg!(windows) { ';' } else { ':' };
entries.extend(content.split([separator, '\n', '\r']).map(str::trim).filter(|e| !e.is_empty()).map(str::to_owned));
- entries.dedup();
- Ok(entries.join(&separator.to_string()))
+ Ok(join_classpath(entries))
}
/// The `javac` step compiling `file` into `target`'s output directory.
pub fn javac_step(target: &SingleFileTarget, file: &Path, classpath: &str, javac: &str) -> IdeResult {
- fs::create_dir_all(&target.out_dir)
- .map_err(|e| IdeError::internal(format!("cannot create {} ({e})", target.out_dir.display())))?;
- let mut step = BuildStep::new(javac, &[], &target.module, Format::Gradle);
- // Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
- step.args.push("-encoding".into());
- step.args.push("UTF-8".into());
- step.args.push("-d".into());
- step.args.push(target.out_dir.to_string_lossy().into_owned());
- step.args.push("-cp".into());
- step.args.push(classpath.to_owned());
- // Classes of the module that were never built (or are older than their source) are read
- // from its sources; only `file` is written, so a test compile never puts main classes
- // into test-classes.
let sources = source_roots(target);
- if !sources.is_empty() {
- let separator = if cfg!(windows) { ";" } else { ":" };
- step.args.push("-sourcepath".into());
- step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::>().join(separator));
- step.args.push("-implicit:none".into());
- }
- if let Some(version) = target.java_version {
- step.args.push("--release".into());
- step.args.push(version.to_string());
- }
- step.args.push(file.to_string_lossy().into_owned());
- step.env = target.top.env.clone();
- Ok(step)
+ let release = release_args(target.java_version, java_home_major(&target.top.env));
+ build_javac_step(javac, &target.module, &target.out_dir, classpath, &sources, release, file, target.top.env.clone())
}
/// The module's Java source folders that exist, generated ones included; test sources see
@@ -383,8 +448,18 @@ fn source_roots(target: &SingleFileTarget) -> Vec {
/// Resolves the classpath and plans the `javac` invocation for one Java source.
pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeResult {
+ compile_file_plan_cancellable(root, model, file, &CancellationToken::new())
+}
+
+/// Cancellable [`compile_file_plan`].
+pub fn compile_file_plan_cancellable(
+ root: &Path,
+ model: &BuildModel,
+ file: &Path,
+ cancel: &CancellationToken,
+) -> IdeResult {
let target = single_file_target(root, model, file)?;
- let classpath = single_file_classpath(root, model, &target)?;
+ let classpath = single_file_classpath_cancellable(root, model, &target, cancel)?;
let javac = find_javac(&target.top.env);
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
Ok(BuildPlan {
@@ -394,6 +469,140 @@ pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeRes
})
}
+fn gradle_for_file<'a>(
+ root: &Path,
+ model: &'a BuildModel,
+ file: &Path,
+) -> Option<(&'a crate::GradleModel, &'a crate::GradleProject, PathBuf)> {
+ let file = normalize(file);
+ let file_ref = &file;
+ model
+ .gradle
+ .iter()
+ .flat_map(|g| {
+ let g_dir = normalize(&subdir(root, &g.dir));
+ let g_depth = g_dir.components().count();
+ g.projects.iter().filter_map(move |p| {
+ let p_dir = normalize(&subdir(root, &p.dir));
+ file_ref.starts_with(&p_dir).then_some((g, p, p_dir, g_depth))
+ })
+ })
+ .max_by_key(|(_, _, p_dir, g_depth)| (p_dir.components().count(), *g_depth))
+ .map(|(g, p, p_dir, _)| (g, p, p_dir))
+}
+
+/// Whether `file` lies inside a linked Gradle project of `model`.
+pub fn has_gradle_file_target(root: &Path, model: &BuildModel, file: &Path) -> bool {
+ gradle_for_file(root, model, file).is_some()
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct GradleCompileCp {
+ out_dir: Option,
+ #[serde(default)]
+ classpath: Vec,
+ #[serde(default)]
+ src_dirs: Vec,
+ release: Option,
+}
+
+/// Resolves the compile classpath from Gradle and plans a single-file `javac` step.
+pub fn gradle_compile_file_plan(
+ root: &Path,
+ model: &BuildModel,
+ file: &Path,
+ cache: &Path,
+ cancel: &CancellationToken,
+) -> IdeResult {
+ let name = is_java_file(file)?;
+ let (gradle, project, module_dir) = gradle_for_file(root, model, file)
+ .ok_or_else(|| IdeError::not_found("no linked Gradle project found for file"))?;
+ let rel = rel_str(&module_dir, file);
+ let test = is_test_source(&rel);
+ let scope = if test { "test" } else { "main" };
+
+ fs::create_dir_all(cache)?;
+ let init_script = cache.join("gradle-compile-cp.init.gradle");
+ fs::write(&init_script, GRADLE_COMPILE_CP_INIT_SCRIPT)?;
+ let args = vec![
+ "--console=plain".into(),
+ "-q".into(),
+ "-Dorg.gradle.configuration-cache=false".into(),
+ "--init-script".into(),
+ init_script.to_string_lossy().into_owned(),
+ format!("-Popenidea.target={}", project.path),
+ format!("-Popenidea.scope={scope}"),
+ "help".into(),
+ ];
+ let gradle_dir = subdir(root, &gradle.dir);
+ let mut reported: Option = None;
+ let out = process::run_bounded(&gradle.command, &args, &gradle_dir, &gradle.env, cancel, |_, line| {
+ if let Some(json) = line.strip_prefix("@openidea-compile-cp\t") {
+ reported = Some(json.to_owned());
+ }
+ })
+ .map_err(|e| {
+ if e.kind == ide_core::error::ErrorKind::Cancelled {
+ e
+ } else {
+ IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
+ }
+ })?;
+ if !out.success {
+ let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
+ let tail = tail.iter().rev().take(5).rev().cloned().collect::>().join("\n");
+ return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
+ }
+ let json = reported.ok_or_else(|| {
+ IdeError::internal(format!(
+ "cannot resolve the compile classpath: Gradle did not report source set '{scope}' for {}",
+ project.path
+ ))
+ })?;
+ let cp: GradleCompileCp = serde_json::from_str(&json)
+ .map_err(|e| IdeError::internal(format!("cannot parse Gradle compile classpath: {e}")))?;
+
+ let out_dir = cp
+ .out_dir
+ .filter(|d| !d.trim().is_empty())
+ .map(PathBuf::from)
+ .unwrap_or_else(|| module_dir.join("build/classes/java").join(scope));
+ let mut cp_entries: Vec = Vec::new();
+ if out_dir.is_dir() {
+ cp_entries.push(out_dir.to_string_lossy().into_owned());
+ }
+ if test {
+ let main_out = module_dir.join("build/classes/java/main");
+ if main_out.is_dir() {
+ cp_entries.push(main_out.to_string_lossy().into_owned());
+ }
+ }
+ for sibling in &gradle.projects {
+ let sibling_dir = subdir(root, &sibling.dir);
+ if sibling_dir == module_dir {
+ continue;
+ }
+ let classes = sibling_dir.join("build/classes/java/main");
+ if classes.is_dir() {
+ cp_entries.push(classes.to_string_lossy().into_owned());
+ }
+ }
+ cp_entries.extend(cp.classpath);
+ let classpath = join_classpath(cp_entries);
+
+ let mut sources: Vec = cp.src_dirs.into_iter().map(PathBuf::from).filter(|p| p.is_dir()).collect();
+ if sources.is_empty() {
+ let fallback: &[&str] = if test { &["src/test/java", "src/main/java"] } else { &["src/main/java"] };
+ sources.extend(fallback.iter().map(|s| module_dir.join(s)).filter(|p| p.is_dir()));
+ }
+ let javac = find_javac(&gradle.env);
+ let release = release_args(cp.release.or(gradle.java_version), java_home_major(&gradle.env));
+ let step =
+ build_javac_step(&javac, &module_dir, &out_dir, &classpath, &sources, release, file, gradle.env.clone())?;
+ Ok(BuildPlan { system: BuildSystem::Gradle, title: format!("Compile {name}"), steps: vec![step] })
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -439,7 +648,8 @@ mod tests {
#[test]
fn target_finds_the_owning_module_and_the_test_scope() {
let dir = tempfile::tempdir().unwrap();
- let root = dir.path();
+ let root_buf = dunce::canonicalize(dir.path()).unwrap();
+ let root = root_buf.as_path();
let model = fixture(root);
let main = single_file_target(root, &model, &root.join("app/src/main/java/demo/Main.java")).unwrap();
assert_eq!(main.module, root.join("app"));
@@ -453,7 +663,8 @@ mod tests {
#[test]
fn target_rejects_non_java_missing_and_unlinked_files() {
let dir = tempfile::tempdir().unwrap();
- let root = dir.path();
+ let root_buf = dunce::canonicalize(dir.path()).unwrap();
+ let root = root_buf.as_path();
let model = fixture(root);
write(root, "app/pom.xml", " ");
assert!(single_file_target(root, &model, &root.join("app/pom.xml")).is_err());
@@ -465,7 +676,8 @@ mod tests {
#[test]
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
let dir = tempfile::tempdir().unwrap();
- let root = dir.path();
+ let root_buf = dunce::canonicalize(dir.path()).unwrap();
+ let root = root_buf.as_path();
let model = fixture(root);
let file = root.join("app/src/test/java/demo/MainTest.java");
let target = single_file_target(root, &model, &file).unwrap();
@@ -501,7 +713,8 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
- let root = dir.path();
+ let root_buf = dunce::canonicalize(dir.path()).unwrap();
+ let root = root_buf.as_path();
fixture(root);
let script = root.join("mvnw");
fs::write(
@@ -532,6 +745,7 @@ mod tests {
assert!(cp.split(separator).count() >= 3, "{cp}");
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(!args.lines().any(|a| a == "compile" || a == "package"), "{args}");
+ assert!(args.lines().any(|a| a == "-Dmdep.includeScope=compile"), "{args}");
fs::create_dir_all(root.join("app/target/test-classes")).unwrap();
let target = single_file_target(root, &model, &root.join("app/src/test/java/demo/MainTest.java")).unwrap();
let cp = single_file_classpath(root, &model, &target).unwrap();
@@ -539,6 +753,8 @@ mod tests {
assert_eq!(paths[0], root.join("app/target/test-classes"));
assert!(paths.contains(&root.join("app/target/classes")), "{cp}");
assert!(!paths.contains(&root.join("lib/target/test-classes")), "{cp}");
+ let args = fs::read_to_string(root.join("args.txt")).unwrap();
+ assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
}
/// Launches request Maven's matching scope without adding reactor test outputs.
@@ -548,7 +764,8 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
- let root = dir.path();
+ let root_buf = dunce::canonicalize(dir.path()).unwrap();
+ let root = root_buf.as_path();
fixture(root);
let script = root.join("mvnw");
fs::write(
@@ -605,7 +822,8 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
- let root = dir.path();
+ let root_buf = dunce::canonicalize(dir.path()).unwrap();
+ let root = root_buf.as_path();
fixture(root);
write(root, "lib/src/main/java/demo/Lib.java", "class Lib {}");
let script = root.join("mvnw");
@@ -646,7 +864,8 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
- let root = dir.path();
+ let root_buf = dunce::canonicalize(dir.path()).unwrap();
+ let root = root_buf.as_path();
fixture(root);
let script = root.join("mvnw");
// `dependency:build-classpath` reports reactor outputs as absolute paths. Keep
@@ -712,4 +931,79 @@ mod tests {
calls.push('x');
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
}
+
+ #[test]
+ fn javac_step_omits_empty_classpath_and_uses_source_target_on_jdk_8() {
+ let dir = tempfile::tempdir().unwrap();
+ let root_buf = dunce::canonicalize(dir.path()).unwrap();
+ let root = root_buf.as_path();
+ let mut model = fixture(root);
+ let file = root.join("app/src/main/java/demo/Main.java");
+ let jdk8 = root.join("jdk8");
+ fs::create_dir_all(jdk8.join("bin")).unwrap();
+ fs::write(jdk8.join("release"), "JAVA_VERSION=\"1.8.0_372\"\n").unwrap();
+ let project = model.maven.as_mut().unwrap().projects.iter_mut().find(|p| p.dir == "app").unwrap();
+ project.java_version = Some(8);
+ let mut target = single_file_target(root, &model, &file).unwrap();
+ target.top.env.insert("JAVA_HOME".into(), jdk8.to_string_lossy().into_owned());
+ let step = javac_step(&target, &file, "", "javac").unwrap();
+ assert!(!step.args.iter().any(|a| a == "-cp"), "{:?}", step.args);
+ assert!(step.args.iter().any(|a| a == "-g"), "{:?}", step.args);
+ assert!(step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]), "{:?}", step.args);
+ assert!(!step.args.iter().any(|a| a == "--release"), "{:?}", step.args);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn gradle_single_file_compiles_with_source_set_classpath_and_siblings() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = tempfile::tempdir().unwrap();
+ let root_buf = dunce::canonicalize(dir.path()).unwrap();
+ let root = root_buf.as_path();
+ write(root, "settings.gradle", "include ':lib', ':app'");
+ write(root, "lib/build.gradle", "plugins { id 'java' }");
+ write(root, "app/build.gradle", "plugins { id 'java' }");
+ write(root, "app/src/main/java/demo/App.java", "package demo; class App {}");
+ write(root, "app/src/test/java/demo/AppTest.java", "package demo; class AppTest {}");
+ fs::create_dir_all(root.join("lib/build/classes/java/main")).unwrap();
+ fs::create_dir_all(root.join("app/build/classes/java/main")).unwrap();
+ let wrapper = root.join("gradlew");
+ fs::write(
+ &wrapper,
+ "#!/bin/sh\nprintf '%s\\n' \"$@\" > gradle_args.txt\nscope='main'\nfor a in \"$@\"; do\ncase \"$a\" in -Popenidea.scope=*) scope=\"${a#-Popenidea.scope=}\" ;; esac\ndone\nprintf '@openidea-compile-cp\\t{\"outDir\":\"%s/app/build/classes/java/%s\",\"classpath\":[\"%s/deps/guava.jar\"],\"srcDirs\":[\"%s/app/src/%s/java\"],\"release\":17}\\n' \"$PWD\" \"$scope\" \"$PWD\" \"$PWD\" \"$scope\"\n",
+ )
+ .unwrap();
+ fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap();
+
+ let model = crate::load(root, &root.join("cache"), None);
+ let cache = root.join("cache");
+ let cancel = CancellationToken::new();
+
+ let main_file = root.join("app/src/main/java/demo/App.java");
+ let main_plan = gradle_compile_file_plan(root, &model, &main_file, &cache, &cancel).unwrap();
+ assert_eq!(main_plan.system, BuildSystem::Gradle);
+ assert_eq!(main_plan.title, "Compile App.java");
+ let step = &main_plan.steps[0];
+ let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
+ assert!(args.lines().any(|a| a == "-Popenidea.target=:app"), "{args}");
+ assert!(args.lines().any(|a| a == "-Popenidea.scope=main"), "{args}");
+ let cp = &step.args[step.args.iter().position(|a| a == "-cp").unwrap() + 1];
+ let paths: Vec<_> = std::env::split_paths(cp).collect();
+ assert!(paths.contains(&root.join("app/build/classes/java/main")), "{cp}");
+ assert!(paths.contains(&root.join("lib/build/classes/java/main")), "{cp}");
+ assert!(paths.contains(&root.join("deps/guava.jar")), "{cp}");
+ assert!(step.args.windows(2).any(|w| w == ["--release", "17"]), "{:?}", step.args);
+ assert!(step.args.iter().any(|a| a == "-implicit:none"), "{:?}", step.args);
+
+ let test_file = root.join("app/src/test/java/demo/AppTest.java");
+ let test_plan = gradle_compile_file_plan(root, &model, &test_file, &cache, &cancel).unwrap();
+ assert_eq!(test_plan.title, "Compile AppTest.java");
+ let test_step = &test_plan.steps[0];
+ let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
+ assert!(args.lines().any(|a| a == "-Popenidea.scope=test"), "{args}");
+ assert!(
+ test_step.args.windows(2).any(|w| w == ["-d", &root.join("app/build/classes/java/test").to_string_lossy()])
+ );
+ }
}
diff --git a/crates/ide-build/src/compile/structure.rs b/crates/ide-build/src/compile/structure.rs
index 1c90cd0898..20df075d46 100644
--- a/crates/ide-build/src/compile/structure.rs
+++ b/crates/ide-build/src/compile/structure.rs
@@ -162,16 +162,6 @@ fn classpath(entries: &[String]) -> String {
entries.join(if cfg!(windows) { ";" } else { ":" })
}
-/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
-fn release_args(level: Option, jdk: Option<&StructureJdk>) -> Vec {
- let Some(level) = level else { return Vec::new() };
- if jdk.is_none_or(|j| j.major >= 9) {
- vec!["--release".into(), level.to_string()]
- } else {
- vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
- }
-}
-
/// `"17"`, `"1.8"`, `"JDK_17"` → the release number.
pub fn language_release(level: &str) -> Option {
let digits = level.trim().trim_start_matches("JDK_").trim_start_matches("jdk").replace('_', ".");
@@ -179,6 +169,25 @@ pub fn language_release(level: &str) -> Option {
digits.split(['.', ' ']).next()?.parse().ok().filter(|n| *n > 0)
}
+fn structure_compiler(
+ root: &Path,
+ ps: &ProjectStructureSettings,
+ jdk: Option<&StructureJdk>,
+ language_level: &str,
+) -> (Option, BTreeMap, String) {
+ let module = root_module(root, ps);
+ let level = module
+ .map(|m| m.language_level.as_str())
+ .filter(|l| !l.trim().is_empty())
+ .or(Some(language_level))
+ .and_then(language_release);
+ let env: BTreeMap = jdk
+ .map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
+ .unwrap_or_default();
+ let javac = find_javac(&env);
+ (level, env, javac)
+}
+
/// The Build / Rebuild plan of a project without a build tool, or `None` when it has no
/// Java sources under its source roots. `language_level`: the project's, unless the module
/// overrides it. Writes the javac argument files below `cache`.
@@ -203,16 +212,7 @@ pub fn structure_plan(
return Ok(None);
}
let (main_out, test_out) = structure_outputs(root, ps);
- let module = root_module(root, ps);
- let level = module
- .map(|m| m.language_level.as_str())
- .filter(|l| !l.trim().is_empty())
- .or(Some(language_level))
- .and_then(language_release);
- let env: BTreeMap = jdk
- .map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
- .unwrap_or_default();
- let javac = find_javac(&env);
+ let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
let args_dir = cache.join("javac");
fs::create_dir_all(&args_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", args_dir.display())))?;
@@ -241,7 +241,7 @@ pub fn structure_plan(
if !cp.is_empty() {
step.args.extend(["-cp".into(), classpath(cp)]);
}
- step.args.extend(release_args(level, jdk));
+ step.args.extend(single::release_args(level, jdk.map(|j| j.major)));
step.args.push(format!("@{}", args_file.to_string_lossy()));
step.env = env.clone();
step.mkdirs = vec![out.to_path_buf()];
@@ -281,6 +281,47 @@ pub fn structure_plan(
Ok(Some(BuildPlan { system: BuildSystem::Javac, title: module_name(root), steps }))
}
+/// Single-file `javac` plan for a Java project without a build tool (Project Structure).
+pub fn structure_compile_file_plan(
+ root: &Path,
+ ps: &ProjectStructureSettings,
+ roots: &StructureRoots,
+ jdk: Option<&StructureJdk>,
+ language_level: &str,
+ file: &Path,
+) -> IdeResult {
+ let name = single::is_java_file(file)?;
+ let rel = rel_str(root, file);
+ let test = if roots.tests.is_empty() {
+ single::is_test_source(&rel)
+ } else {
+ let file_norm = normalize(file);
+ roots.tests.iter().any(|t| file_norm.starts_with(normalize(t)))
+ };
+ let (main_out, test_out) = structure_outputs(root, ps);
+ let out_dir = if test { &test_out } else { &main_out };
+ let mut cp: Vec = Vec::new();
+ if test && test_out.is_dir() {
+ cp.push(test_out.to_string_lossy().into_owned());
+ }
+ if main_out.is_dir() {
+ cp.push(main_out.to_string_lossy().into_owned());
+ }
+ cp.extend(library_entries(root, ps, test));
+ let cp = single::join_classpath(cp);
+
+ let mut src_roots: Vec = Vec::new();
+ if test {
+ src_roots.extend(roots.tests.iter().filter(|p| p.is_dir()).cloned());
+ }
+ src_roots.extend(roots.sources.iter().filter(|p| p.is_dir()).cloned());
+
+ let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
+ let release = single::release_args(level, jdk.map(|j| j.major));
+ let step = single::build_javac_step(&javac, root, out_dir, &cp, &src_roots, release, file, env)?;
+ Ok(BuildPlan { system: BuildSystem::Javac, title: format!("Compile {name}"), steps: vec![step] })
+}
+
/// Where an artifact goes: its output folder, else `out/artifacts/`.
pub fn artifact_output(root: &Path, artifact: &ArtifactConfig) -> PathBuf {
resolve_dir(root, &artifact.output_directory)
@@ -1008,4 +1049,99 @@ mod tests {
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("c.jar").is_file());
}
+
+ #[test]
+ fn plans_single_file_javac_for_main_test_and_jdk8() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("shop");
+ write(&root.join("src/com/a/Main.java"), "package com.a; class Main {}");
+ write(&root.join("test/com/a/MainTest.java"), "package com.a; class MainTest {}");
+ write(&root.join("out/production/shop/com/a/Helper.class"), "");
+ let ps = ProjectStructureSettings {
+ libraries: vec![
+ ProjectLibrary { name: "core".into(), classes: vec!["lib/core.jar".into()], ..Default::default() },
+ ProjectLibrary {
+ name: "junit".into(),
+ classes: vec!["lib/junit.jar".into()],
+ scope: DependencyScope::Test,
+ ..Default::default()
+ },
+ ],
+ ..Default::default()
+ };
+ let roots =
+ StructureRoots { sources: vec![root.join("src")], tests: vec![root.join("test")], ..Default::default() };
+
+ let jdk21 = StructureJdk { home: PathBuf::from("/jdk21"), major: 21 };
+ let main_plan =
+ structure_compile_file_plan(&root, &ps, &roots, Some(&jdk21), "17", &root.join("src/com/a/Main.java"))
+ .unwrap();
+ assert_eq!(main_plan.system, BuildSystem::Javac);
+ assert_eq!(main_plan.title, "Compile Main.java");
+ let main_step = &main_plan.steps[0];
+ let cp = &main_step.args[main_step.args.iter().position(|a| a == "-cp").unwrap() + 1];
+ assert!(cp.contains("core.jar") && !cp.contains("junit.jar"), "{cp}");
+ assert!(main_step.args.windows(2).any(|w| w == ["--release", "17"]));
+ assert!(main_step.args.iter().any(|a| a == "-implicit:none"));
+
+ let jdk8 = StructureJdk { home: PathBuf::from("/jdk8"), major: 8 };
+ let test_plan =
+ structure_compile_file_plan(&root, &ps, &roots, Some(&jdk8), "8", &root.join("test/com/a/MainTest.java"))
+ .unwrap();
+ let test_step = &test_plan.steps[0];
+ let test_cp = &test_step.args[test_step.args.iter().position(|a| a == "-cp").unwrap() + 1];
+ assert!(test_cp.contains("out/production/shop") || test_cp.contains("out\\production\\shop"), "{test_cp}");
+ assert!(test_cp.contains("junit.jar"), "{test_cp}");
+ assert!(test_step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]));
+ assert!(test_step.args.windows(2).any(|w| w[0] == "-d" && Path::new(&w[1]).ends_with("out/test/shop")));
+ }
+
+ #[test]
+ fn compiles_only_the_target_java_file_and_reports_errors() {
+ let exe = if cfg!(windows) { "javac.exe" } else { "javac" };
+ if !std::process::Command::new(exe).arg("-version").output().is_ok_and(|o| o.status.success()) {
+ return;
+ }
+ let tmp = tempfile::tempdir().unwrap();
+ let root = dunce::canonicalize(tmp.path()).unwrap().join("demo");
+ let good = root.join("src/p/Good.java");
+ let broken_sibling = root.join("src/p/BrokenSibling.java");
+ let bad_target = root.join("src/p/BadTarget.java");
+ write(&good, "package p;\npublic class Good { public static int ok() { return 1; } }\n");
+ write(&broken_sibling, "package p;\npublic class BrokenSibling { MissingType field; }\n");
+ write(&bad_target, "package p;\npublic class BadTarget {\n UnknownSymbol field;\n}\n");
+
+ let ps = ProjectStructureSettings::default();
+ let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
+ let cancel = CancellationToken::new();
+
+ // 1. Valid file compiles cleanly without touching or failing on BrokenSibling.java.
+ let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &good).unwrap();
+ let events = std::sync::Mutex::new(Vec::new());
+ let result = run(&root, &plan, &cancel, &|e| events.lock().unwrap().push(e)).unwrap();
+ assert!(result.success, "expected single-file compile to succeed: {:?}", result.messages);
+ assert_eq!(result.errors, 0);
+ assert!(root.join("out/production/demo/p/Good.class").is_file());
+ assert!(!root.join("out/production/demo/p/BrokenSibling.class").exists());
+
+ // 2. Broken target fails, streams raw compiler output, and produces structured diagnostics.
+ let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &bad_target).unwrap();
+ let bad_events = std::sync::Mutex::new(Vec::new());
+ let bad_result = run(&root, &plan, &cancel, &|e| bad_events.lock().unwrap().push(e)).unwrap();
+ assert!(!bad_result.success);
+ assert!(bad_result.errors >= 1, "{bad_result:?}");
+ assert!(
+ bad_events.lock().unwrap().iter().any(|e| matches!(e, BuildEvent::Output { .. })),
+ "expected streamed output"
+ );
+ assert!(
+ bad_result.messages.iter().any(|m| {
+ m.severity == Severity::Error
+ && m.path.as_ref().is_some_and(|p| >::as_ref(p) == bad_target)
+ && m.range.is_some_and(|r| r.start.line == 2)
+ }),
+ "messages={:?}",
+ bad_result.messages
+ );
+ }
}
diff --git a/crates/ide-build/src/gradle-compile-cp.init.gradle b/crates/ide-build/src/gradle-compile-cp.init.gradle
new file mode 100644
index 0000000000..c26b37a5d5
--- /dev/null
+++ b/crates/ide-build/src/gradle-compile-cp.init.gradle
@@ -0,0 +1,58 @@
+// OpenIDEA single-file javac classpath probe for Gradle projects.
+// Prints the target source set's output directory, compile classpath, source dirs and release version.
+import groovy.json.JsonOutput
+
+def identity = { Project p -> try { p.identityPath.toString() } catch (ignored) { p.path } }
+
+gradle.projectsEvaluated { g ->
+ def wantedTarget = g.rootProject.findProperty('openidea.target')?.toString() ?: ':'
+ def scope = g.rootProject.findProperty('openidea.scope')?.toString() ?: 'main'
+ def project = g.rootProject.allprojects.find { identity(it) == wantedTarget }
+ if (project == null && g.parent == null) {
+ project = g.rootProject.allprojects.find { it.path == wantedTarget }
+ }
+ if (project == null) return
+
+ def sets = project.extensions.findByName('sourceSets') ?: project.findProperty('sourceSets')
+ def ss = sets?.findByName(scope)
+ if (ss == null) return
+
+ def outDir = null
+ try { outDir = ss.java.destinationDirectory.get().asFile.canonicalPath } catch (ignored) {}
+ if (outDir == null) {
+ try { outDir = ss.output.classesDirs.files.iterator().next().canonicalPath } catch (ignored) {}
+ }
+
+ def cp = []
+ if (scope == 'test') {
+ def mainSet = sets.findByName('main')
+ try { mainSet?.output?.classesDirs?.files?.each { cp << it.canonicalPath } } catch (ignored) {}
+ }
+ try { ss.compileClasspath.files.each { cp << it.canonicalPath } } catch (ignored) {}
+ cp = cp.unique()
+
+ def srcDirs = []
+ try { ss.java.srcDirs.each { srcDirs << it.canonicalPath } } catch (ignored) {}
+ if (scope == 'test') {
+ def mainSet = sets.findByName('main')
+ try { mainSet?.java?.srcDirs?.each { srcDirs << it.canonicalPath } } catch (ignored) {}
+ }
+ srcDirs = srcDirs.unique()
+
+ def release = null
+ try {
+ def compileTask = project.tasks.findByName(ss.compileJavaTaskName)
+ release = compileTask?.options?.release?.getOrNull()
+ } catch (ignored) {}
+ if (release == null) {
+ try {
+ def java = project.extensions.findByName('java')
+ def lv = null
+ try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
+ def target = java != null ? java.targetCompatibility : project.findProperty('targetCompatibility')
+ release = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
+ } catch (ignored) {}
+ }
+
+ println '@openidea-compile-cp\t' + JsonOutput.toJson([outDir: outDir, classpath: cp, srcDirs: srcDirs, release: release])
+}
diff --git a/crates/ide-build/src/lib.rs b/crates/ide-build/src/lib.rs
index 6d86c4242b..94e8d7b5bf 100644
--- a/crates/ide-build/src/lib.rs
+++ b/crates/ide-build/src/lib.rs
@@ -16,6 +16,7 @@ mod process;
#[cfg(test)]
mod process_numbers;
pub mod sbt;
+pub mod surefire;
mod sync;
pub mod web;
mod xml;
diff --git a/crates/ide-build/src/surefire.rs b/crates/ide-build/src/surefire.rs
new file mode 100644
index 0000000000..6ff50410f5
--- /dev/null
+++ b/crates/ide-build/src/surefire.rs
@@ -0,0 +1,216 @@
+//! A Maven module's Surefire configuration, for test runs OpenIDEA starts itself instead of
+//! Surefire (IDEA's `MavenJUnitPatcher`): what the forked test JVM would get from the POM.
+//!
+//! Read from the effective POM the last sync cached (Maven merged parents, profiles and
+//! `pluginManagement` there), else from the module's own `pom.xml` and its ``.
+
+use crate::maven::{MavenModel, interpolate};
+use crate::xml::{self, Element};
+use std::collections::{BTreeMap, HashMap};
+use std::path::Path;
+
+const SUREFIRE: &str = "maven-surefire-plugin";
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct SurefireConfig {
+ /// ``, split into JVM options.
+ pub arg_line: Vec,
+ /// `` and the older ``.
+ pub system_properties: BTreeMap,
+ /// ``.
+ pub environment: BTreeMap,
+ pub working_directory: Option,
+ /// ``.
+ pub additional_classpath: Vec,
+ /// ``: `groupId:artifactId`.
+ pub classpath_excludes: Vec,
+}
+
+/// The Surefire configuration of the Maven module at `module` (absolute), if it is one.
+pub fn surefire_config(root: &Path, cache_dir: &Path, model: &MavenModel, module: &Path) -> Option {
+ let same = |a: &Path, b: &Path| dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok();
+ let project = model.projects.iter().find(|p| same(&root.join(&p.dir), module))?;
+ let pom = root.join(&project.pom);
+ let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
+ // A cache written before the POM last changed would apply an old configuration.
+ let effective = std::fs::read_dir(cache_dir).ok()?.flatten().map(|e| e.path()).find_map(|path| {
+ let name = path.file_name()?.to_str()?;
+ if !(name.starts_with("effective-pom-") && name.ends_with(".xml")) || modified(&path) < modified(&pom) {
+ return None;
+ }
+ let root = xml::parse(&xml::read_text(&path)?)?;
+ let projects: Vec = if root.name == "projects" {
+ root.children.into_iter().filter(|p| p.name == "project").collect()
+ } else {
+ vec![root]
+ };
+ projects.into_iter().find(|p| {
+ let group = p.text_of("groupId").or_else(|| p.at("parent/groupId").map(|g| g.text.trim().to_owned()));
+ group.as_deref() == Some(project.group_id.as_str())
+ && p.text_of("artifactId").as_deref() == Some(&project.artifact_id)
+ })
+ });
+ let (element, own) = match effective {
+ Some(e) => (e, false),
+ // ponytail: without a sync, inherited configuration and parent properties are missing; Reload adds them.
+ None => (xml::parse(&xml::read_text(&pom)?)?, true),
+ };
+ let mut props: HashMap = element
+ .child("properties")
+ .map(|p| p.children.iter().map(|c| (c.name.clone(), c.text.trim().to_owned())).collect())
+ .unwrap_or_default();
+ let dir = module.to_string_lossy().into_owned();
+ for (key, value) in [
+ ("basedir", dir.clone()),
+ ("project.basedir", dir.clone()),
+ ("project.build.directory", format!("{dir}/target")),
+ ("project.groupId", project.group_id.clone()),
+ ("project.artifactId", project.artifact_id.clone()),
+ ("project.version", project.version.clone()),
+ ] {
+ props.entry(key.into()).or_insert(value);
+ }
+ Some(read(&element, &props, own))
+}
+
+/// `` Surefire's configuration, then its `default-test` execution's.
+fn read(project: &Element, props: &HashMap, own: bool) -> SurefireConfig {
+ let is_surefire = |p: &&Element| p.text_of("artifactId").as_deref() == Some(SUREFIRE);
+ let mut plugins: Vec<&Element> = project.list("build/plugins", "plugin").into_iter().filter(is_surefire).collect();
+ if own && plugins.is_empty() {
+ plugins = project.list("build/pluginManagement/plugins", "plugin").into_iter().filter(is_surefire).collect();
+ }
+ let mut configurations: Vec<&Element> = Vec::new();
+ for plugin in plugins {
+ configurations.extend(plugin.child("configuration"));
+ let default_test = plugin
+ .list("executions", "execution")
+ .into_iter()
+ .find(|e| e.text_of("id").as_deref() == Some("default-test"));
+ configurations.extend(default_test.and_then(|e| e.child("configuration")));
+ }
+ let value = |text: &str| resolve(text.trim(), props);
+ let mut config = SurefireConfig::default();
+ for c in configurations {
+ if let Some(arg_line) = c.child("argLine") {
+ config.arg_line = split_arg_line(&value(&arg_line.text));
+ }
+ for p in c.child("systemPropertyVariables").map_or(&[][..], |p| &p.children) {
+ config.system_properties.insert(p.name.clone(), value(&p.text));
+ }
+ // ``: ` ` (deprecated, still honoured).
+ for p in c.list("systemProperties", "property") {
+ if let Some(name) = p.text_of("name") {
+ config.system_properties.insert(name, value(&p.text_of("value").unwrap_or_default()));
+ }
+ }
+ for e in c.child("environmentVariables").map_or(&[][..], |e| &e.children) {
+ config.environment.insert(e.name.clone(), value(&e.text));
+ }
+ if let Some(dir) = c.text_of("workingDirectory").map(|d| value(&d)).filter(|d| !d.is_empty()) {
+ config.working_directory = Some(dir);
+ }
+ let texts = |list: &str, item: &str| -> Vec {
+ c.list(list, item).into_iter().map(|e| value(&e.text)).filter(|t| !t.is_empty()).collect()
+ };
+ config.additional_classpath.extend(texts("additionalClasspathElements", "additionalClasspathElement"));
+ config.classpath_excludes.extend(texts("classpathDependencyExcludes", "classpathDependencyExclude"));
+ }
+ config
+}
+
+/// `${…}` from the POM's properties, then Surefire's late replacement `@{…}` (a property a plugin
+/// sets during the build, such as JaCoCo's `argLine`, is unknown here and left out, as in IDEA).
+fn resolve(text: &str, props: &HashMap) -> String {
+ let mut out = interpolate(text, props);
+ for open in ["@{", "${"] {
+ while let Some(start) = out.find(open) {
+ let Some(len) = out[start..].find('}') else { break };
+ let key = &out[start + 2..start + len];
+ let replacement = if open == "@{" { props.get(key).cloned().unwrap_or_default() } else { String::new() };
+ out.replace_range(start..=start + len, &replacement);
+ }
+ }
+ out.trim().to_owned()
+}
+
+/// Splits `argLine` as Surefire does (plexus `CommandLineUtils`): whitespace, `"…"` and `'…'`, no escapes.
+fn split_arg_line(line: &str) -> Vec {
+ let mut out = Vec::new();
+ let mut current: Option = None;
+ let mut quote: Option = None;
+ for c in line.chars() {
+ match quote {
+ Some(q) if c == q => quote = None,
+ Some(_) => current.get_or_insert_default().push(c),
+ None if c == '"' || c == '\'' => {
+ quote = Some(c);
+ current.get_or_insert_default();
+ }
+ None if c.is_whitespace() => out.extend(current.take()),
+ None => current.get_or_insert_default().push(c),
+ }
+ }
+ out.extend(current);
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const POM: &str = r#"
+ com.example orders 1
+ true /m2/mockito.jar
+
+ maven-surefire-plugin
+
+ @{argLine} @{jacoco} -javaagent:${mockito} --add-opens "java.base/java.lang=ALL-UNNAMED" -Dx=${undefined}
+ ${openideaFail} ${project.build.directory}
+ old style
+ UTC
+ ${basedir}/extra
+ org.slf4j:slf4j-simple
+
+ default-test ${basedir}/work
+
+ "#;
+
+ fn model(dir: &Path) -> MavenModel {
+ crate::maven::load(dir)
+ }
+
+ #[test]
+ fn reads_the_module_pom_and_the_effective_pom_the_sync_cached() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path();
+ std::fs::write(root.join("pom.xml"), POM).unwrap();
+ let cache = root.join("cache");
+ std::fs::create_dir_all(&cache).unwrap();
+ let config = surefire_config(root, &cache, &model(root), root).unwrap();
+ let d = root.to_string_lossy();
+ assert_eq!(
+ config.arg_line,
+ ["-javaagent:/m2/mockito.jar", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "-Dx="]
+ );
+ assert_eq!(config.system_properties["openidea.fail"], "true");
+ assert_eq!(config.system_properties["dir"], format!("{d}/target"));
+ assert_eq!(config.system_properties["old"], "style");
+ assert_eq!(config.environment["TZ"], "UTC");
+ assert_eq!(config.working_directory, Some(format!("{d}/work")));
+ assert_eq!(config.additional_classpath, [format!("{d}/extra")]);
+ assert_eq!(config.classpath_excludes, ["org.slf4j:slf4j-simple"]);
+
+ // A sync's effective POM wins: it has what the module inherits.
+ let effective = POM.replace("", "-Xmx1g ").replace("UTC ", "Asia/Tokyo ");
+ std::fs::write(cache.join("effective-pom-0.xml"), format!("{effective} ")).unwrap();
+ let config = surefire_config(root, &cache, &model(root), root).unwrap();
+ assert_eq!(config.arg_line[0], "-Xmx1g");
+ assert_eq!(config.environment["TZ"], "Asia/Tokyo");
+ }
+
+ #[test]
+ fn splits_arg_line_like_surefire() {
+ assert_eq!(split_arg_line(r#" -a "b c" 'd "e"' C:\x\y "" "#), ["-a", "b c", r#"d "e""#, r"C:\x\y", ""]);
+ }
+}
diff --git a/crates/ide-clipboard/src/image.rs b/crates/ide-clipboard/src/image.rs
new file mode 100644
index 0000000000..4f1fd28227
--- /dev/null
+++ b/crates/ide-clipboard/src/image.rs
@@ -0,0 +1,85 @@
+use std::io::{Cursor, Error, ErrorKind, Result};
+
+/// A top-down BITMAPV5HEADER and BGRA pixels. The alpha mask lets native paste targets
+/// retain transparency; the PNG flavor is also written for browsers and image editors.
+pub(crate) fn png_to_dib(png: &[u8]) -> Result> {
+ let invalid = |error| Error::new(ErrorKind::InvalidData, error);
+ let mut decoder = png::Decoder::new(Cursor::new(png));
+ decoder.set_transformations(png::Transformations::normalize_to_color8());
+ let mut reader = decoder.read_info().map_err(invalid)?;
+ let rgba_size = (reader.info().width as usize)
+ .checked_mul(reader.info().height as usize)
+ .and_then(|pixels| pixels.checked_mul(4))
+ .filter(|size| *size <= 64 * 1024 * 1024)
+ .ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
+ let size = reader
+ .output_buffer_size()
+ .filter(|size| *size <= 64 * 1024 * 1024)
+ .ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
+ let mut pixels = vec![0; size];
+ let info = reader.next_frame(&mut pixels).map_err(invalid)?;
+ let mut dib = vec![0; 124];
+ dib[0..4].copy_from_slice(&124u32.to_le_bytes());
+ dib[4..8].copy_from_slice(&info.width.to_le_bytes());
+ dib[8..12].copy_from_slice(&(-(info.height as i32)).to_le_bytes());
+ dib[12..14].copy_from_slice(&1u16.to_le_bytes());
+ dib[14..16].copy_from_slice(&32u16.to_le_bytes());
+ dib[16..20].copy_from_slice(&3u32.to_le_bytes()); // BI_BITFIELDS
+ dib[20..24].copy_from_slice(&(rgba_size as u32).to_le_bytes());
+ for (at, value) in [(40, 0x00ff0000u32), (44, 0x0000ff00), (48, 0x000000ff), (52, 0xff000000), (56, 0x73524742)] {
+ dib[at..at + 4].copy_from_slice(&value.to_le_bytes());
+ }
+ dib[108..112].copy_from_slice(&4u32.to_le_bytes()); // LCS_GM_IMAGES
+ for pixel in pixels[..info.buffer_size()].chunks_exact(info.color_type.samples()) {
+ let rgba = match info.color_type {
+ png::ColorType::Rgba => [pixel[0], pixel[1], pixel[2], pixel[3]],
+ png::ColorType::Rgb => [pixel[0], pixel[1], pixel[2], 255],
+ png::ColorType::Grayscale => [pixel[0], pixel[0], pixel[0], 255],
+ png::ColorType::GrayscaleAlpha => [pixel[0], pixel[0], pixel[0], pixel[1]],
+ png::ColorType::Indexed => unreachable!("palette expansion requested"),
+ };
+ dib.extend_from_slice(&[rgba[2], rgba[1], rgba[0], rgba[3]]);
+ }
+ Ok(dib)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn encode(color: png::ColorType, pixels: &[u8]) -> Vec {
+ let mut png = Vec::new();
+ {
+ let mut encoder = png::Encoder::new(&mut png, 1, 2);
+ encoder.set_color(color);
+ encoder.set_depth(png::BitDepth::Eight);
+ encoder.write_header().unwrap().write_image_data(pixels).unwrap();
+ }
+ png
+ }
+
+ #[test]
+ fn keeps_rgba_colors_alpha_and_top_down_row_order() {
+ let png = encode(png::ColorType::Rgba, &[255, 0, 0, 128, 0, 255, 0, 255]);
+ let dib = png_to_dib(&png).unwrap();
+ assert_eq!(i32::from_le_bytes(dib[8..12].try_into().unwrap()), -2);
+ assert_eq!(&dib[124..], &[0, 0, 255, 128, 0, 255, 0, 255]);
+ let round_trip = crate::dib_to_png(&dib).unwrap();
+ let mut reader = png::Decoder::new(Cursor::new(round_trip)).read_info().unwrap();
+ let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
+ reader.next_frame(&mut pixels).unwrap();
+ assert_eq!(pixels, [255, 0, 0, 128, 0, 255, 0, 255]);
+ }
+
+ #[test]
+ fn supports_rgb_and_grayscale_without_assuming_an_alpha_channel() {
+ for (color, pixels, expected) in [
+ (png::ColorType::Rgb, vec![255, 0, 0, 0, 255, 0], vec![0, 0, 255, 255, 0, 255, 0, 255]),
+ (png::ColorType::Grayscale, vec![20, 200], vec![20, 20, 20, 255, 200, 200, 200, 255]),
+ (png::ColorType::GrayscaleAlpha, vec![20, 10, 200, 250], vec![20, 20, 20, 10, 200, 200, 200, 250]),
+ ] {
+ assert_eq!(&png_to_dib(&encode(color, &pixels)).unwrap()[124..], expected);
+ }
+ assert!(png_to_dib(b"not a PNG").is_err());
+ }
+}
diff --git a/crates/ide-clipboard/src/lib.rs b/crates/ide-clipboard/src/lib.rs
index 24a5a582f2..0f44b24cba 100644
--- a/crates/ide-clipboard/src/lib.rs
+++ b/crates/ide-clipboard/src/lib.rs
@@ -25,6 +25,29 @@
use std::path::PathBuf;
+#[cfg(any(windows, test))]
+mod image;
+
+/// Writes a PNG as a native image, independently of WebView clipboard permissions.
+/// Call on the main thread on macOS and Linux; `owner` is a window handle on Windows.
+pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
+ if png.get(..8) != Some(b"\x89PNG\r\n\x1a\n") || png.get(12..16) != Some(b"IHDR") || png.len() < 24 {
+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
+ }
+ let width = u32::from_be_bytes(png[16..20].try_into().unwrap()) as usize;
+ let height = u32::from_be_bytes(png[20..24].try_into().unwrap()) as usize;
+ if width == 0
+ || height == 0
+ || !width
+ .checked_mul(height)
+ .and_then(|pixels| pixels.checked_mul(4))
+ .is_some_and(|size| size <= 64 * 1024 * 1024)
+ {
+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Clipboard image is too large"));
+ }
+ imp::set_png(png, owner)
+}
+
/// Replaces every clipboard flavor with plain text. `owner` is the calling window
/// handle on Windows, ignored elsewhere. Call on the main thread on macOS and Linux.
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
@@ -240,6 +263,7 @@ mod imp {
/// `CF_DIB`: Windows synthesizes it from `CF_BITMAP` and `CF_DIBV5`, so every
/// bitmap on the clipboard reads as one.
const CF_DIB: u32 = 8;
+ const CF_DIBV5: u32 = 17;
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
/// keeps transparency, so it is read first.
@@ -422,6 +446,48 @@ mod imp {
}
}
+ pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
+ let dib = super::image::png_to_dib(png)?;
+ let format = png_format();
+ if format == 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ let formats = [(format, png), (CF_DIBV5, dib.as_slice())];
+ // SAFETY: allocations remain ours until SetClipboardData accepts them. Prepare both
+ // before replacing the clipboard; free only allocations the OS did not take.
+ unsafe {
+ let mut blocks: Vec<_> = formats.iter().map(|(_, bytes)| global_bytes(bytes)).collect();
+ if blocks.iter().any(|memory| memory.is_null()) || !open_for(owner as Handle) {
+ let error = std::io::Error::last_os_error();
+ for memory in blocks {
+ if !memory.is_null() {
+ GlobalFree(memory);
+ }
+ }
+ return Err(error);
+ }
+ let mut result = Ok(());
+ if EmptyClipboard() == 0 {
+ result = Err(std::io::Error::last_os_error());
+ } else {
+ for ((format, _), memory) in formats.iter().zip(&mut blocks) {
+ if SetClipboardData(*format, *memory).is_null() {
+ result = Err(std::io::Error::last_os_error());
+ break;
+ }
+ *memory = ptr::null_mut();
+ }
+ }
+ CloseClipboard();
+ for memory in blocks {
+ if !memory.is_null() {
+ GlobalFree(memory);
+ }
+ }
+ result
+ }
+ }
+
pub fn set_files(paths: &[PathBuf]) -> bool {
let bytes = encode(paths);
if bytes.len() <= HEADER {
@@ -489,7 +555,7 @@ mod imp {
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG,
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
};
- use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
+ use objc2_foundation::{NSArray, NSData, NSDictionary, NSNumber, NSString, NSURL};
use std::path::PathBuf;
use super::names_text;
@@ -587,6 +653,23 @@ mod imp {
})
}
+ pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
+ debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
+ autoreleasepool(|_| {
+ let data = NSData::with_bytes(png);
+ if NSBitmapImageRep::imageRepWithData(&data).is_none() {
+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
+ }
+ let board = NSPasteboard::generalPasteboard();
+ board.clearContents();
+ if board.setData_forType(Some(&data), unsafe { NSPasteboardTypePNG }) {
+ Ok(())
+ } else {
+ Err(std::io::Error::other("Cannot write clipboard image"))
+ }
+ })
+ }
+
pub fn set_files(paths: &[PathBuf]) -> bool {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
@@ -617,6 +700,21 @@ mod imp {
mod imp {
use std::path::PathBuf;
+ pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
+ #[cfg(target_os = "linux")]
+ {
+ let image = gtk::gdk_pixbuf::Pixbuf::from_read(std::io::Cursor::new(png.to_vec()))
+ .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()))?;
+ gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).set_image(&image);
+ Ok(())
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ let _ = png;
+ Err(std::io::Error::other("Clipboard images are unavailable on this platform"))
+ }
+ }
+
pub fn set_text(text: &str, _owner: usize) -> std::io::Result<()> {
#[cfg(target_os = "linux")]
{
@@ -658,6 +756,15 @@ mod imp {
mod tests {
use super::*;
+ #[test]
+ fn invalid_or_oversized_images_are_rejected_before_accessing_the_clipboard() {
+ assert!(set_png(b"not a PNG", 0).is_err());
+ let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
+ header.extend_from_slice(&100_000u32.to_be_bytes());
+ header.extend_from_slice(&100_000u32.to_be_bytes());
+ assert!(set_png(&header, 0).is_err());
+ }
+
fn paths(list: &[&str]) -> Vec {
list.iter().map(PathBuf::from).collect()
}
diff --git a/crates/ide-core/src/editor_settings.rs b/crates/ide-core/src/editor_settings.rs
index e5d883877d..62e156dcba 100644
--- a/crates/ide-core/src/editor_settings.rs
+++ b/crates/ide-core/src/editor_settings.rs
@@ -336,6 +336,7 @@ pub struct CodeEditingSettings {
/// Next / previous error goes to errors only (skips warnings).
pub next_error_errors_only: bool,
pub sticky_lines_max: u32,
+ pub sticky_lines_disabled_languages: Vec,
}
impl Default for CodeEditingSettings {
@@ -348,6 +349,7 @@ impl Default for CodeEditingSettings {
quick_doc_delay: 500,
next_error_errors_only: true,
sticky_lines_max: 5,
+ sticky_lines_disabled_languages: Vec::new(),
}
}
}
@@ -360,6 +362,8 @@ pub struct InlayHintsSettings {
pub parameters: bool,
/// Hints of other kinds (chaining, closing labels…).
pub other: bool,
+ /// The Dart server's closing labels (`// Column` after a widget's closing bracket).
+ pub closing_labels: bool,
pub disabled_languages: Vec,
/// Code vision as a whole (usages, author and language-server lenses); the switches below apply while it is on.
pub code_vision: bool,
@@ -392,6 +396,7 @@ impl Default for InlayHintsSettings {
types: true,
parameters: true,
other: true,
+ closing_labels: true,
disabled_languages: Vec::new(),
code_vision: true,
code_vision_usages: true,
@@ -473,6 +478,12 @@ pub struct LanguageCodeStyle {
/// PHP: align `=` of consecutive assignment statements after formatting.
#[serde(skip_serializing_if = "Option::is_none")]
pub align_consecutive_assignments: Option,
+ /// SQL › Case › Keywords: `upper` | `lower` | `keep` (other languages ignore it).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub keyword_case: Option,
+ /// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub identifier_case: Option,
}
/// Editor › Code Style (General tab + per-language overrides).
@@ -585,3 +596,20 @@ mod folding_tests {
}
}
}
+
+#[cfg(test)]
+mod sticky_lines_tests {
+ use super::CodeEditingSettings;
+
+ #[test]
+ fn sticky_lines_language_exclusions_round_trip_and_default_to_empty() {
+ let old: CodeEditingSettings = serde_json::from_value(serde_json::json!({"stickyLinesMax": 3})).unwrap();
+ assert_eq!(old.sticky_lines_max, 3);
+ assert!(old.sticky_lines_disabled_languages.is_empty());
+ let json = serde_json::json!(["markdown", "rust"]);
+ let saved: CodeEditingSettings =
+ serde_json::from_value(serde_json::json!({"stickyLinesDisabledLanguages": json})).unwrap();
+ assert_eq!(saved.sticky_lines_disabled_languages, ["markdown", "rust"]);
+ assert_eq!(serde_json::to_value(saved).unwrap()["stickyLinesDisabledLanguages"], json);
+ }
+}
diff --git a/crates/ide-core/src/event.rs b/crates/ide-core/src/event.rs
index 979faabe20..0715db9cf5 100644
--- a/crates/ide-core/src/event.rs
+++ b/crates/ide-core/src/event.rs
@@ -264,6 +264,20 @@ pub struct FlutterDevice {
pub emulator: bool,
/// The adb state keeping it from being used (`unauthorized`, `offline`, …).
pub unavailable: Option,
+ /// The [`FlutterEmulator`] it runs on: an AVD name, or `apple_ios_simulator`.
+ #[serde(default)]
+ #[specta(optional)]
+ pub emulator_id: Option,
+}
+
+/// An Android emulator (AVD) or the iOS Simulator that `flutter emulators --launch` can start.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct FlutterEmulator {
+ pub id: String,
+ pub name: String,
+ /// `android` or `ios`.
+ pub platform_type: Option,
}
/// See [`FlutterDeviceList`].
@@ -289,6 +303,10 @@ pub enum FlutterDaemonStatus {
pub struct FlutterDeviceList {
pub status: FlutterDaemonStatus,
pub devices: Vec,
+ /// The emulators that no listed device runs on.
+ #[serde(default)]
+ #[specta(optional)]
+ pub emulators: Vec,
}
/// See [`IdeEvent::Direnv`].
diff --git a/crates/ide-core/src/process.rs b/crates/ide-core/src/process.rs
index 76dea73c4c..29bf8b60f6 100644
--- a/crates/ide-core/src/process.rs
+++ b/crates/ide-core/src/process.rs
@@ -402,12 +402,14 @@ mod windows_job {
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
use windows_sys::Win32::Foundation::{ERROR_MORE_DATA, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::JobObjects::{
- AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
+ AssignProcessToJobObject, CreateJobObjectW, IsProcessInJob, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
JOBOBJECT_BASIC_LIMIT_INFORMATION, JOBOBJECT_BASIC_PROCESS_ID_LIST, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JobObjectBasicProcessIdList, JobObjectExtendedLimitInformation, QueryInformationJobObject,
SetInformationJobObject, TerminateJobObject,
};
- use windows_sys::Win32::System::Threading::{IO_COUNTERS, OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};
+ use windows_sys::Win32::System::Threading::{
+ IO_COUNTERS, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_QUOTA, PROCESS_TERMINATE,
+ };
/// A job object holding one launch's processes. The handle is kept open for the
/// launch's lifetime: `KILL_ON_JOB_CLOSE` ends anything still in the job when the
@@ -510,6 +512,21 @@ mod windows_job {
ok != 0
}
+ /// Whether the running process belongs to this specific launch's job.
+ pub fn contains_pid(&self, pid: u32) -> bool {
+ // SAFETY: a non-null result is a process handle owned by this call.
+ let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
+ if handle.is_null() {
+ return false;
+ }
+ // SAFETY: the process handle was just opened above and the job handle is owned here.
+ let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
+ let mut contained = 0;
+ // SAFETY: both handles remain valid and `contained` is a writable BOOL.
+ (unsafe { IsProcessInJob(handle.as_raw_handle(), self.0.as_raw_handle(), &mut contained) }) != 0
+ && contained != 0
+ }
+
/// Terminates every process in the job. `false` when the call failed (the job
/// handle is invalid): callers then fall back to `taskkill /T /F`. Termination is
/// asynchronous; poll [`Job::is_running`] (bounded by [`TREE_EXIT_WAIT`]) until
diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs
index 78b61da575..86703c0cf8 100644
--- a/crates/ide-core/src/settings.rs
+++ b/crates/ide-core/src/settings.rs
@@ -941,6 +941,8 @@ pub struct FileIconThemeOptions {
#[serde(default, rename_all = "camelCase")]
pub struct MainToolbarSettings {
pub left: Vec,
+ /// Centred in the toolbar (between the other two groups when they leave too little room).
+ pub center: Vec,
pub right: Vec,
/// Widgets the user removed.
pub hidden: Vec,
@@ -1655,6 +1657,20 @@ pub struct MavenSettings {
/// Always update snapshots (`-U`): Maven checks remote repositories for newer SNAPSHOT
/// dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`).
pub update_snapshots: bool,
+ /// Who runs the JUnit 5 tests of the gutter's Run / Debug.
+ pub run_tests_using: MavenRunTestsUsing,
+}
+
+/// Build Tools › Maven › Run tests using. IDEA runs a Maven project's tests itself unless its build
+/// and run actions are delegated to Maven.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub enum MavenRunTestsUsing {
+ /// OpenIDEA's JUnit Platform runner on the language server's test classpath (`java/junit-runner`).
+ #[default]
+ Ide,
+ /// Surefire (`mvn test -Dtest=…`).
+ Maven,
}
impl MavenSettings {
@@ -2316,6 +2332,7 @@ mod maven_linkage_tests {
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
assert!(old.runner_jre.is_empty());
assert!(!old.delegate_build);
+ assert_eq!(old.run_tests_using, MavenRunTestsUsing::Ide);
assert!(MavenSettings::default().runner_jre.is_empty());
let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), delegate_build: true, ..old };
let encoded = serde_json::to_string(&settings).unwrap();
diff --git a/crates/ide-core/src/workflow_settings.rs b/crates/ide-core/src/workflow_settings.rs
index a7ec7814cd..c4c50b5e4a 100644
--- a/crates/ide-core/src/workflow_settings.rs
+++ b/crates/ide-core/src/workflow_settings.rs
@@ -460,6 +460,16 @@ impl Default for ConsoleSettings {
}
}
+/// Whether compiled classes are reloaded into running Java debug sessions after compilation.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub enum HotSwapPolicy {
+ #[default]
+ Ask,
+ Always,
+ Never,
+}
+
/// Build, Execution, Deployment › Debugger (+ Data Views, Stepping, Python Debugger).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -487,6 +497,8 @@ pub struct DebuggerSettings {
pub debug_server_page: bool,
/// Flutter: saving a Dart file of a running debug session hot reloads the app.
pub flutter_hot_reload_on_save: bool,
+ /// Java: whether to reload changed classes into running debug sessions after compilation.
+ pub hot_swap_after_compile: HotSwapPolicy,
pub python: PythonDebuggerSettings,
}
@@ -508,6 +520,7 @@ impl Default for DebuggerSettings {
skip_library_code: true,
debug_server_page: false,
flutter_hot_reload_on_save: true,
+ hot_swap_after_compile: HotSwapPolicy::Ask,
python: PythonDebuggerSettings::default(),
}
}
@@ -718,4 +731,19 @@ mod tests {
let off: GitSettings = serde_json::from_str(r#"{"syncBranchOperations":false}"#).unwrap();
assert!(!off.sync_branch_operations);
}
+
+ #[test]
+ fn debugger_hotswap_after_compile_defaults_to_ask_and_roundtrips() {
+ let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
+ assert_eq!(missing.hot_swap_after_compile, HotSwapPolicy::Ask);
+ for (raw, expected) in
+ [("ask", HotSwapPolicy::Ask), ("always", HotSwapPolicy::Always), ("never", HotSwapPolicy::Never)]
+ {
+ let parsed: DebuggerSettings =
+ serde_json::from_str(&format!(r#"{{"hotSwapAfterCompile":"{raw}"}}"#)).unwrap();
+ assert_eq!(parsed.hot_swap_after_compile, expected);
+ let serialized = serde_json::to_value(&parsed).unwrap();
+ assert_eq!(serialized["hotSwapAfterCompile"], raw);
+ }
+ }
}
diff --git a/crates/ide-dap/src/jvm_memory/mod.rs b/crates/ide-dap/src/jvm_memory/mod.rs
index ce710d6f97..e2e519c094 100644
--- a/crates/ide-dap/src/jvm_memory/mod.rs
+++ b/crates/ide-dap/src/jvm_memory/mod.rs
@@ -1,5 +1,6 @@
//! Class-table snapshots of a debugged JVM, read over the HotSpot attach listener or, where
-//! that is unavailable, counted by the debugger; and the JVM's objects through the debugger.
+//! that is unavailable, counted by the debugger; the JVM's objects through the debugger; and
+//! its thread dumps.
mod fallback;
mod heap;
@@ -10,6 +11,7 @@ mod snapshot;
pub(crate) mod test_support;
#[cfg(test)]
mod tests;
+mod threads;
use crate::session::Session;
use crate::session::Suspension;
@@ -28,6 +30,8 @@ pub(crate) use inspect::{fields, instances, referrers, set_inspector, vm_target,
pub(crate) use scan::watch_for_attached_jvm;
pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port};
use snapshot::{AttachProbe, JdkProbe, take_snapshot};
+pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, run_jvm_thread_dump};
+pub(crate) use threads::{debugged_run_thread_dump, session_thread_dump};
pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER, crate::kotlin_lsp::ADAPTER];
pub const HISTOGRAM_TIMEOUT: Duration = Duration::from_secs(10);
@@ -190,6 +194,25 @@ fn histogram_pid(session: &Session) -> Result, JvmMemoryUnavailable>
Ok(None)
}
+/// Whether `session` is a JVM session attached to `run` that may hold `pid`: its JVM is `pid` or
+/// not located yet.
+pub(crate) fn attached_to_run(session: &Session, run: ide_core::RunId, pid: u32) -> bool {
+ let located = session.jvm_pid.load(Ordering::Acquire);
+ session.run == Some(run)
+ && JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str())
+ && !session.terminated.load(Ordering::Acquire)
+ && (located <= 0 || located == i64::from(pid))
+}
+
+/// Whether `session` debugs the JVM `pid`: the program it launched or the JVM its attach found.
+pub(crate) fn debugs_jvm(session: &Session, pid: u32) -> bool {
+ let jvm = if session.request == "launch" { launch_pid(session) } else { session.jvm_pid.load(Ordering::Acquire) };
+ JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str())
+ && !session.terminated.load(Ordering::Acquire)
+ && jvm > 0
+ && jvm == i64::from(pid)
+}
+
/// The JVM a launch session started: the one the IDE started for an app-launched (Kotlin)
/// session, else the program the adapter reported; 0 when neither is known.
pub(crate) fn launch_pid(session: &Session) -> i64 {
@@ -206,6 +229,8 @@ pub(crate) enum JvmTarget<'a> {
/// The JVM of an attach session. While `pid` is 0 it is looked up by `jdwp_port`, which is
/// `None` for a remote JVM.
Attached { pid: &'a AtomicI64, jdwp_port: Option },
+ /// A JVM the session debugs, found from outside it (in a run's process tree).
+ Known(i32),
/// Known without asking any JVM: no histogram can be taken, for this reason.
Unavailable(JvmMemoryUnavailable),
}
@@ -261,6 +286,7 @@ async fn histogram(
fn lookup(target: JvmTarget<'_>) -> Result {
match target {
JvmTarget::Launched(pid) => Ok(Lookup::Tree(pid)),
+ JvmTarget::Known(pid) => Ok(Lookup::Known(pid)),
JvmTarget::Attached { pid, jdwp_port } => match i32::try_from(pid.load(Ordering::Acquire)) {
Ok(p) if p > 0 => Ok(Lookup::Known(p)),
_ => jdwp_port.map(Lookup::Scan).ok_or(JvmMemoryUnavailable::AttachedJvmNotFound),
diff --git a/crates/ide-dap/src/jvm_memory/snapshot.rs b/crates/ide-dap/src/jvm_memory/snapshot.rs
index ddaddd02ea..ce674aca48 100644
--- a/crates/ide-dap/src/jvm_memory/snapshot.rs
+++ b/crates/ide-dap/src/jvm_memory/snapshot.rs
@@ -15,7 +15,8 @@ use std::time::Duration;
const VERSION_TIMEOUT: Duration = Duration::from_secs(2);
const FLAGS_TIMEOUT: Duration = Duration::from_secs(2);
-/// The attach calls a snapshot or a heap dump makes, so tests can stand in for a JVM.
+/// The attach calls a snapshot, a heap dump or a thread dump makes, so tests can stand in for a
+/// JVM.
pub(crate) trait AttachProbe: Send + Sync {
fn has_listener(&self, pid: u32) -> bool;
/// Asks only the JVMs whose pid `may_query` accepts.
@@ -27,6 +28,11 @@ pub(crate) trait AttachProbe: Send + Sync {
fn heap_dump(&self, pid: u32, path: &Path, timeout: Duration) -> Result;
/// `None` where the free space is not known.
fn free_bytes(&self, dir: &Path) -> Option;
+ fn thread_print(&self, pid: u32) -> Result;
+ /// Opens `pid`'s attach listener unless it runs; refuses a process not confirmed HotSpot.
+ fn ensure_listener(&self, pid: u32) -> Result<(), AttachError>;
+ /// Confirmed HotSpot and not one of Gradle's own JVMs; asks the JVM nothing.
+ fn is_application_jvm(&self, pid: u32) -> bool;
}
pub(super) struct JdkProbe {
@@ -73,6 +79,18 @@ impl AttachProbe for JdkProbe {
fn free_bytes(&self, dir: &Path) -> Option {
ide_heap::free_bytes(dir)
}
+
+ fn thread_print(&self, pid: u32) -> Result {
+ ide_jvm_attach::thread_print(pid, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
+ }
+
+ fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> {
+ ide_jvm_attach::ensure_listener(pid, ide_jvm_attach::LISTENER_START_TIMEOUT)
+ }
+
+ fn is_application_jvm(&self, pid: u32) -> bool {
+ ide_jvm_attach::is_application_jvm(pid)
+ }
}
fn alive(pid: u32) -> bool {
diff --git a/crates/ide-dap/src/jvm_memory/tests.rs b/crates/ide-dap/src/jvm_memory/tests.rs
index 003574ebe8..545573437b 100644
--- a/crates/ide-dap/src/jvm_memory/tests.rs
+++ b/crates/ide-dap/src/jvm_memory/tests.rs
@@ -3,6 +3,7 @@ use super::heap::*;
use super::scan::*;
use super::snapshot::*;
use super::test_support::{BareSession, FakeInspector, bare_session, bare_session_of};
+use super::threads::*;
use super::*;
use ide_core::CancellationToken;
use ide_jvm_attach::{AttachError, HeapDumpReply, HistogramRow, JavaVersion};
@@ -39,6 +40,13 @@ struct FakeProbe {
free: Option,
/// Answering this command stops the program: runs the hook.
stops_on: Option<(&'static str, StopHook)>,
+ thread_dumps: parking_lot::Mutex>>,
+ /// Replies to `ensure_listener`, in order; `Ok` once empty.
+ listener_starts: parking_lot::Mutex>>,
+ /// Pids `is_application_jvm` confirms.
+ application_jvms: Vec,
+ /// Pids `ensure_listener` was asked for.
+ ensured: parking_lot::Mutex>,
}
type StopHook = Box;
@@ -97,6 +105,10 @@ impl FakeProbe {
dump_bytes: 64,
free: None,
stops_on: None,
+ thread_dumps: parking_lot::Mutex::new(VecDeque::new()),
+ listener_starts: parking_lot::Mutex::new(VecDeque::new()),
+ application_jvms: Vec::new(),
+ ensured: parking_lot::Mutex::new(Vec::new()),
}
}
@@ -167,6 +179,20 @@ impl AttachProbe for FakeProbe {
fn free_bytes(&self, _dir: &Path) -> Option {
self.free
}
+ fn thread_print(&self, _pid: u32) -> Result {
+ self.enter("thread_print");
+ std::thread::sleep(self.delay);
+ self.leave();
+ self.thread_dumps.lock().pop_front().expect("unexpected thread dump request")
+ }
+ fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> {
+ self.record("ensure_listener");
+ self.ensured.lock().push(pid);
+ self.listener_starts.lock().pop_front().unwrap_or(Ok(()))
+ }
+ fn is_application_jvm(&self, pid: u32) -> bool {
+ self.application_jvms.contains(&pid)
+ }
}
const FLAGS: &str = "-XX:+UseCompressedOops -XX:+StartAttachListener";
@@ -1160,6 +1186,341 @@ async fn jdk11_is_refused_while_the_link_is_suspended_before_dap_stops() {
assert!(!dir.exists());
}
+const THREADS: &str = "Full thread dump OpenJDK 64-Bit Server VM (21.0.5+11-LTS mixed mode, sharing):\n\n\"main\" #1 [259] prio=5 os_prio=31 cpu=31.20ms elapsed=1.70s tid=0x1 nid=259 runnable [0x2]\n java.lang.Thread.State: RUNNABLE\n";
+
+fn dumping_threads(listener: u32, dumps: Vec>) -> FakeProbe {
+ let fake = FakeProbe::new(listener, Vec::new());
+ *fake.thread_dumps.lock() = dumps.into();
+ fake
+}
+
+fn threads_unavailable(r: JvmThreadsResult) -> JvmThreadsUnavailable {
+ match r {
+ JvmThreadsResult::Unavailable { reason } => reason,
+ other => panic!("{other:?}"),
+ }
+}
+
+fn threads_jvm(reason: JvmMemoryUnavailable) -> JvmThreadsUnavailable {
+ JvmThreadsUnavailable::Jvm { reason }
+}
+
+#[test]
+fn threads_while_running_start_the_listener() {
+ let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
+ let r = dump_threads(&fake, 12, false);
+ let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
+ assert_eq!((dump.text.as_str(), dump.pid, dump.java_version.as_str()), (THREADS, 12, "21.0.5"));
+ assert!(!dump.taken_while_suspended);
+ assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
+}
+
+#[test]
+fn threads_while_suspended_without_listener_do_not_attach() {
+ let fake = dumping_threads(99, Vec::new());
+ assert_eq!(
+ threads_unavailable(dump_threads(&fake, 12, true)),
+ threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)
+ );
+ assert!(fake.commands.lock().is_empty());
+}
+
+#[test]
+fn threads_while_suspended_on_11_are_refused() {
+ let mut fake = dumping_threads(12, Vec::new());
+ fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
+ assert_eq!(
+ threads_unavailable(dump_threads(&fake, 12, true)),
+ threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })
+ );
+ fake.version = None;
+ assert_eq!(
+ threads_unavailable(dump_threads(&fake, 12, true)),
+ threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 })
+ );
+ assert!(fake.commands.lock().is_empty());
+}
+
+#[test]
+fn threads_while_suspended_on_17_use_the_running_listener() {
+ let mut fake = dumping_threads(12, vec![Ok(THREADS.into())]);
+ fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
+ let r = dump_threads(&fake, 12, true);
+ let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
+ assert!(dump.taken_while_suspended);
+ assert_eq!(dump.java_version, "17.0.13");
+ assert_eq!(*fake.commands.lock(), ["thread_print"]);
+}
+
+#[test]
+fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
+ // A shell (10) started a Gradle client (11) that started the program's JVM (12).
+ let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
+ fake.application_jvms = vec![12];
+ let r = dump_tree(&fake, &[10, 11, 12], false);
+ let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
+ assert_eq!(dump.pid, 12);
+ assert_eq!(*fake.ensured.lock(), [12]);
+
+ // No JVM at all: the reported pid is asked, which tells an exited program from a non-JVM.
+ let fake = dumping_threads(99, Vec::new());
+ *fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm)].into();
+ assert_eq!(
+ threads_unavailable(dump_tree(&fake, &[10, 11], false)),
+ threads_jvm(JvmMemoryUnavailable::NoJvmProcess)
+ );
+ assert_eq!(*fake.ensured.lock(), [10]);
+}
+
+#[cfg(unix)]
+#[tokio::test]
+async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reported_pid() {
+ struct Child(std::process::Child);
+ impl Drop for Child {
+ fn drop(&mut self) {
+ let _ = self.0.kill();
+ let _ = self.0.wait();
+ }
+ }
+ let child = Child(std::process::Command::new("sleep").arg("30").spawn().unwrap());
+ let jvm = child.0.id();
+ let state = tokio::sync::Mutex::new(JvmMemoryState::default());
+ let mut fake = dumping_threads(0, vec![Ok(THREADS.into())]);
+ fake.application_jvms = vec![jvm];
+ let fake = Arc::new(fake);
+ let probe: Arc = fake.clone();
+ let target = JvmTarget::Launched(std::process::id() as i32);
+ let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
+ let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
+ assert_eq!(dump.pid, jvm);
+ assert_eq!(*fake.ensured.lock(), [jvm]);
+}
+
+#[tokio::test]
+async fn a_session_debugs_the_jvm_it_launched_or_found() {
+ let attach = bare_session("attach");
+ attach.session.jvm_pid.store(4242, Ordering::Release);
+ assert!(debugs_jvm(&attach.session, 4242));
+ assert!(!debugs_jvm(&attach.session, 4243));
+ let launch = bare_session("launch");
+ launch.session.debuggee_pid.store(77, Ordering::Release);
+ assert!(debugs_jvm(&launch.session, 77));
+ let python = bare_session_of("debugpy", "attach");
+ python.session.jvm_pid.store(4242, Ordering::Release);
+ assert!(!debugs_jvm(&python.session, 4242));
+ attach.session.terminated.store(true, Ordering::Release);
+ assert!(!debugs_jvm(&attach.session, 4242));
+ // An attach whose JVM is not found yet debugs no pid.
+ assert!(!debugs_jvm(&bare_session("attach").session, 0));
+}
+
+#[tokio::test]
+async fn a_session_attached_to_a_run_may_hold_its_jvm_before_it_is_located() {
+ let run = ide_core::RunId(7);
+ let mut bare = bare_session("attach");
+ Arc::get_mut(&mut bare.session).unwrap().run = Some(run);
+ // Gradle bootRun Debug opens no attach listener, so the attach-time scan finds no pid.
+ assert!(attached_to_run(&bare.session, run, 555));
+ assert!(!attached_to_run(&bare.session, ide_core::RunId(8), 555));
+ bare.session.jvm_pid.store(4242, Ordering::Release);
+ assert!(attached_to_run(&bare.session, run, 4242));
+ assert!(!attached_to_run(&bare.session, run, 555), "another JVM of the same run");
+ bare.session.terminated.store(true, Ordering::Release);
+ assert!(!attached_to_run(&bare.session, run, 4242));
+
+ let mut python = bare_session_of("debugpy", "attach");
+ Arc::get_mut(&mut python.session).unwrap().run = Some(run);
+ assert!(!attached_to_run(&python.session, run, 555));
+ assert!(!attached_to_run(&bare_session("attach").session, run, 555), "not linked to a run");
+}
+
+#[tokio::test]
+async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
+ // Stopped at a breakpoint, no listener: refused with the resume reason, no listener start.
+ let bare = stopped_attach(0);
+ let fake = Arc::new(dumping_threads(99, Vec::new()));
+ let probe: Arc = fake.clone();
+ let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
+ assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
+ assert!(fake.commands.lock().is_empty());
+
+ // Running: the run's JVM is dumped under the session's turn.
+ let bare = bare_session("attach");
+ let fake = Arc::new(dumping_threads(99, vec![Ok(THREADS.into())]));
+ let probe: Arc = fake.clone();
+ let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
+ let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
+ assert_eq!((dump.pid, dump.taken_while_suspended), (555, false));
+ assert_eq!(*fake.ensured.lock(), [555]);
+}
+
+/// A run's JVM held at a breakpoint by a debugger attached to it (Debug of `spring-boot:run`).
+fn stopped_attach(pid: u32) -> BareSession {
+ let bare = bare_session("attach");
+ bare.session.jvm_pid.store(i64::from(pid), Ordering::Release);
+ bare.session.suspended.stopped(None, true);
+ bare
+}
+
+#[tokio::test]
+async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() {
+ let bare = stopped_attach(4242);
+ let mut fake = dumping_threads(4242, Vec::new());
+ fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
+ let fake = Arc::new(fake);
+ let probe: Arc = fake.clone();
+ let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
+ assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 }));
+ assert!(fake.commands.lock().is_empty());
+
+ // No listener: none is started, the JVM's Signal Dispatcher being stopped.
+ let fake = Arc::new(dumping_threads(99, Vec::new()));
+ let probe: Arc = fake.clone();
+ let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
+ assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
+ assert!(fake.commands.lock().is_empty());
+
+ let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
+ fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
+ let probe: Arc = Arc::new(fake);
+ let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
+ let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
+ assert!(dump.taken_while_suspended);
+ assert_eq!(dump.pid, 4242);
+}
+
+#[tokio::test]
+async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
+ let bare = bare_session("attach");
+ bare.session.jvm_pid.store(4242, Ordering::Release);
+ let fake = Arc::new(dumping_threads(99, Vec::new()));
+ let probe: Arc = fake.clone();
+
+ let histogram = bare.session.jvm_memory.lock().await;
+ let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242));
+ assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
+ // The program hits a breakpoint while the dump waits behind the session's histogram.
+ bare.session.suspended.stopped(None, true);
+ drop(histogram);
+ assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
+ assert!(fake.commands.lock().is_empty());
+}
+
+#[test]
+fn threads_of_an_exited_program() {
+ let mut fake = dumping_threads(99, Vec::new());
+ fake.alive = false;
+ *fake.listener_starts.lock() = vec![Err(AttachError::NoListener)].into();
+ assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
+ assert_eq!(threads_unavailable(dump_threads(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
+}
+
+#[test]
+fn thread_dump_errors_map_to_reasons() {
+ let fake = dumping_threads(12, vec![Err(AttachError::Timeout)]);
+ assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
+
+ let fake = dumping_threads(99, Vec::new());
+ *fake.listener_starts.lock() = vec![Err(AttachError::ListenerDidNotStart)].into();
+ assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
+ assert_eq!(*fake.commands.lock(), ["ensure_listener"]);
+
+ let mut fake = dumping_threads(99, Vec::new());
+ *fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm), Err(AttachError::NotAJvm)].into();
+ assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
+ fake.alive = false;
+ assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
+
+ let fake = dumping_threads(12, vec![Err(AttachError::Command { code: 1, message: "no".into() })]);
+ let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_threads(&fake, 12, false)) else {
+ panic!("not a failure")
+ };
+ assert!(message.contains("no"), "{message}");
+}
+
+#[test]
+fn thread_results_serialize_with_camel_case_tags() {
+ let r = JvmThreadsResult::Unavailable { reason: threads_jvm(JvmMemoryUnavailable::ListenerNotRunning) };
+ assert_eq!(
+ serde_json::to_value(r).unwrap(),
+ serde_json::json!({"status": "unavailable", "reason": {"kind": "jvm", "reason": {"kind": "listenerNotRunning"}}})
+ );
+ let r = JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::ListenerDidNotStart };
+ assert_eq!(
+ serde_json::to_value(r).unwrap(),
+ serde_json::json!({"status": "unavailable", "reason": {"kind": "listenerDidNotStart"}})
+ );
+ let dump = JvmThreadDump {
+ text: "t".into(),
+ pid: 7,
+ java_version: String::new(),
+ taken_while_suspended: true,
+ elapsed_ms: 3,
+ };
+ assert_eq!(
+ serde_json::to_value(JvmThreadsResult::Ready { dump }).unwrap(),
+ serde_json::json!({
+ "status": "ready",
+ "dump": {"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3}
+ })
+ );
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread")]
+async fn threads_take_the_memory_lock() {
+ let pid = std::process::id();
+ let state = tokio::sync::Mutex::new(JvmMemoryState::default());
+ let mut fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
+ *fake.histograms.lock() = vec![Ok(HISTOGRAM.into())].into();
+ fake.delay = Duration::from_millis(100);
+ let fake = Arc::new(fake);
+ let probe: Arc = fake.clone();
+ let running = Suspension::default();
+ let (classes, threads) = tokio::join!(
+ snapshot(&state, &running, |_| probe.clone(), JvmTarget::Launched(pid as i32), None),
+ thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32))
+ );
+ assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. }));
+ let threads = threads.unwrap();
+ assert!(matches!(threads, JvmThreadsResult::Ready { .. }), "{threads:?}");
+ assert_eq!(fake.max_in_flight.load(Ordering::SeqCst), 1);
+ assert_eq!(*fake.commands.lock(), ["histogram", "ensure_listener", "thread_print"]);
+}
+
+#[cfg(unix)]
+#[tokio::test]
+async fn queued_thread_dump_reads_suspension_under_the_lock() {
+ let pid = std::process::id();
+ let state = tokio::sync::Mutex::new(JvmMemoryState::default());
+ let suspended = Suspension::default();
+ let fake = Arc::new(dumping_threads(0, Vec::new()));
+ let probe: Arc = fake.clone();
+
+ let running = state.lock().await;
+ let mut queued = Box::pin(thread_dump(&state, || suspended.get(), |_| probe, JvmTarget::Launched(pid as i32)));
+ assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
+ // The program hits a breakpoint while the dump waits behind a class-table request.
+ suspended.stopped(None, true);
+ drop(running);
+ assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
+ assert!(fake.commands.lock().is_empty());
+}
+
+#[tokio::test]
+async fn attached_thread_dump_keeps_the_scanned_jvm() {
+ let state = tokio::sync::Mutex::new(JvmMemoryState::default());
+ let jvm_pid = AtomicI64::new(0);
+ let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
+ fake.jdwp = Some((5005, 4242));
+ let probe: Arc = Arc::new(fake);
+ let target = JvmTarget::Attached { pid: &jvm_pid, jdwp_port: Some(5005) };
+ let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
+ let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
+ assert_eq!(dump.pid, 4242);
+ assert_eq!(jvm_pid.load(Ordering::SeqCst), 4242);
+}
+
#[tokio::test]
async fn capability_matches_memory() {
for adapter in JVM_MEMORY_ADAPTERS.iter().copied().chain(["debugpy"]) {
diff --git a/crates/ide-dap/src/jvm_memory/threads.rs b/crates/ide-dap/src/jvm_memory/threads.rs
new file mode 100644
index 0000000000..7a94f36e46
--- /dev/null
+++ b/crates/ide-dap/src/jvm_memory/threads.rs
@@ -0,0 +1,181 @@
+//! A thread dump (`Thread.print -l`) of a debugged or running JVM.
+
+use super::heap::capture_suspended;
+use super::snapshot::{AttachProbe, JdkProbe, attach_failure, gone, pick_jvm_pid};
+use super::{
+ JvmMemoryState, JvmMemoryUnavailable, JvmTarget, histogram_pid, keep_found, lookup, resolve_jvm,
+ safe_while_suspended, session_target, until_located,
+};
+use crate::session::Session;
+use ide_core::{IdeError, IdeResult};
+use ide_jvm_attach::AttachError;
+use serde::{Deserialize, Serialize};
+use specta::Type;
+use std::sync::Arc;
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct JvmThreadDump {
+ pub text: String,
+ pub pid: u32,
+ /// Empty when unknown.
+ pub java_version: String,
+ pub taken_while_suspended: bool,
+ /// Wall time of the `Thread.print` request.
+ pub elapsed_ms: u32,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
+#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
+pub enum JvmThreadsUnavailable {
+ /// The reason a class table could not be read applies to the dump too.
+ Jvm {
+ reason: JvmMemoryUnavailable,
+ },
+ /// The JVM ignored the request to open its attach listener (`-XX:+DisableAttachMechanism`).
+ ListenerDidNotStart,
+ /// A run on a remote host, whose JVM this machine cannot attach to.
+ RemoteRun,
+ Failed {
+ message: String,
+ },
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
+#[serde(tag = "status", rename_all = "camelCase", rename_all_fields = "camelCase")]
+pub enum JvmThreadsResult {
+ Ready { dump: JvmThreadDump },
+ Unavailable { reason: JvmThreadsUnavailable },
+}
+
+/// A thread dump of `pid`, a JVM no debugger holds. Blocking for up to the listener start and
+/// dump timeouts, so callers run it in `spawn_blocking`.
+pub fn run_jvm_thread_dump(pid: u32) -> JvmThreadsResult {
+ dump_threads(&JdkProbe { suspended: false }, pid, false)
+}
+
+pub(crate) async fn session_thread_dump(session: Arc) -> IdeResult {
+ until_located(&session).await;
+ let launched = histogram_pid(&session);
+ // Detached, so a caller that gives up cannot release the lock while the JVM is still
+ // answering and let a class-table request run next to it.
+ tokio::spawn(async move {
+ let target = session_target(&session, launched);
+ let probe = |suspended| -> Arc { Arc::new(JdkProbe { suspended }) };
+ thread_dump(&session.jvm_memory, || capture_suspended(&session), probe, target).await
+ })
+ .await
+ .map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
+}
+
+/// A thread dump of `pid`, a run's JVM that `session` debugs, taken as the session's own dump
+/// is: a JVM the debugger holds suspended is never asked to open a listener.
+pub(crate) async fn debugged_run_thread_dump(session: Arc, pid: u32) -> IdeResult {
+ // Detached for the same reason as `session_thread_dump`.
+ tokio::spawn(async move {
+ let probe = |suspended| -> Arc { Arc::new(JdkProbe { suspended }) };
+ known_pid_dump(&session, probe, pid).await
+ })
+ .await
+ .map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
+}
+
+pub(super) async fn known_pid_dump(
+ session: &Session,
+ probe: impl FnOnce(bool) -> Arc,
+ pid: u32,
+) -> IdeResult {
+ let target =
+ i32::try_from(pid).map_or(JvmTarget::Unavailable(JvmMemoryUnavailable::NoJvmProcess), JvmTarget::Known);
+ thread_dump(&session.jvm_memory, || capture_suspended(session), probe, target).await
+}
+
+/// Takes the class-table lock, so a dump never runs beside a histogram or heap dump of the same
+/// session; `suspended` and then `probe` are read once it is held.
+pub(super) async fn thread_dump(
+ state: &tokio::sync::Mutex,
+ suspended: impl FnOnce() -> bool,
+ probe: impl FnOnce(bool) -> Arc,
+ target: JvmTarget<'_>,
+) -> IdeResult {
+ let _turn = state.lock().await;
+ let suspended = suspended();
+ let lookup = match lookup(target) {
+ Ok(lookup) => lookup,
+ Err(reason) => return Ok(jvm(reason)),
+ };
+ let probe = probe(suspended);
+ let (found, outcome) = tokio::task::spawn_blocking(move || match resolve_jvm(lookup, &*probe, suspended) {
+ Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended)),
+ Err(reason) => (None, jvm(reason)),
+ })
+ .await
+ .map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?;
+ keep_found(target, found);
+ Ok(outcome)
+}
+
+/// `tree` starts with the session's reported pid, followed by its descendants: the JVM is the
+/// first with a listener, else the first application JVM (the reported pid may be a shell or a
+/// Gradle client), else the reported pid.
+pub(super) fn dump_tree(probe: &dyn AttachProbe, tree: &[i32], suspended: bool) -> JvmThreadsResult {
+ let jvm_pid = pick_jvm_pid(tree, |p| probe.has_listener(p))
+ .or_else(|| pick_jvm_pid(tree, |p| probe.is_application_jvm(p)))
+ .or_else(|| tree.first().and_then(|&p| u32::try_from(p).ok()).filter(|&p| p > 0));
+ match jvm_pid {
+ Some(pid) => dump_threads(probe, pid, suspended),
+ None => jvm(JvmMemoryUnavailable::NoJvmProcess),
+ }
+}
+
+/// Blocking. A JVM a debugger holds suspended cannot open a listener (its Signal Dispatcher is
+/// stopped), and one below 17 hangs even with one, so it is asked only when both are ruled out.
+pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
+ if suspended {
+ if !probe.has_listener(pid) {
+ return jvm(gone(probe, pid));
+ }
+ } else if let Err(e) = probe.ensure_listener(pid) {
+ return failure(probe, pid, e);
+ }
+ let version = probe.version(pid);
+ if suspended && !safe_while_suspended(version.as_ref()) {
+ return jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: version.map_or(0, |v| v.major) });
+ }
+
+ let started = std::time::Instant::now();
+ let text = match probe.thread_print(pid) {
+ Ok(text) => text,
+ Err(e) => return failure(probe, pid, e),
+ };
+ let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
+ JvmThreadsResult::Ready {
+ dump: JvmThreadDump {
+ text,
+ pid,
+ java_version: version.map(|v| v.text).unwrap_or_default(),
+ taken_while_suspended: suspended,
+ elapsed_ms,
+ },
+ }
+}
+
+fn failure(probe: &dyn AttachProbe, pid: u32, error: AttachError) -> JvmThreadsResult {
+ let reason = match error {
+ AttachError::ListenerDidNotStart => JvmThreadsUnavailable::ListenerDidNotStart,
+ // A program that exited leaves no perf-data file, so it fails the HotSpot check too.
+ AttachError::NotAJvm if probe.alive(pid) => {
+ JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::NoJvmProcess }
+ }
+ AttachError::NotAJvm => JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ProgramExited },
+ e => match attach_failure(probe, pid, e, "thread dump") {
+ Ok(reason) => JvmThreadsUnavailable::Jvm { reason },
+ Err(e) => JvmThreadsUnavailable::Failed { message: e.message },
+ },
+ };
+ JvmThreadsResult::Unavailable { reason }
+}
+
+fn jvm(reason: JvmMemoryUnavailable) -> JvmThreadsResult {
+ JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::Jvm { reason } }
+}
diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs
index 13ccd5e712..4f84a8dee7 100644
--- a/crates/ide-dap/src/lib.rs
+++ b/crates/ide-dap/src/lib.rs
@@ -27,7 +27,7 @@ use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
use connection::{Connection, DapError};
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
use futures::future::join_all;
-use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink};
+use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink};
use ide_language::LanguageRegistry;
pub use js_cdp::JsResponseRule;
pub use js_debug::JsResponseBody;
@@ -460,6 +460,15 @@ fn child_name(configuration: &Value, parent: &str) -> String {
}
}
+/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
+/// adapter.
+pub const RUN_LINK: &str = "__openideaRun";
+
+fn take_run_link(arguments: &mut Value) -> Option {
+ let run = arguments.as_object_mut()?.remove(RUN_LINK)?;
+ serde_json::from_value(run).ok()
+}
+
/// Builds the `launch`/`attach` arguments: our fields first, then `extra_json` merged on top.
pub fn launch_arguments(config: &LaunchConfig) -> IdeResult {
// VS Code puts `type`, `request` and `name` in the arguments; js-debug picks launch
@@ -1047,7 +1056,7 @@ impl DebugManager {
adapter_name: String,
parent: Option,
request: String,
- arguments: Value,
+ mut arguments: Value,
spec: AdapterSpec,
reuse_port: Option,
exception_classes: Option>,
@@ -1067,6 +1076,7 @@ impl DebugManager {
.flatten();
let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child);
session.exception_classes = exception_classes;
+ session.run = take_run_link(&mut arguments);
let session = Arc::new(session);
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
let _ = session.launch_type.set(launch_type.to_owned());
@@ -1967,6 +1977,34 @@ impl DebugManager {
jvm_memory::session_heap_dump(session, dir, cancel).await
}
+ /// `Thread.print -l` of the session's JVM, taking the session's class-table turn. A JVM the
+ /// debugger holds suspended is asked only when it is 17 or later and its listener already
+ /// runs: otherwise the request would hang until the program resumes.
+ pub async fn jvm_thread_dump(&self, s: DebugSessionId) -> IdeResult {
+ let session = self.session(s)?;
+ jvm_memory::session_thread_dump(session).await
+ }
+
+ /// `Thread.print -l` of `pid`, the JVM of `run`, when a live session debugs it (a build
+ /// tool's run started for Debug, Attach to Process): taken as [`Self::jvm_thread_dump`] takes
+ /// it, under that session's turn and suspension. `None` when no session debugs `pid`.
+ pub async fn debugged_jvm_thread_dump(&self, run: RunId, pid: u32) -> Option> {
+ let session = self.jvm_session_of(run, pid)?;
+ Some(jvm_memory::debugged_run_thread_dump(session, pid).await)
+ }
+
+ /// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan
+ /// found no listener) still holds `pid`.
+ fn jvm_session_of(&self, run: RunId, pid: u32) -> Option> {
+ let sessions = self.live_sessions();
+ let linked = || sessions.iter().filter(|s| jvm_memory::attached_to_run(s, run, pid));
+ linked()
+ .find(|s| jvm_memory::debugs_jvm(s, pid))
+ .or_else(|| linked().next())
+ .or_else(|| sessions.iter().find(|s| jvm_memory::debugs_jvm(s, pid)))
+ .cloned()
+ }
+
/// Gives the session the backend for [`Self::jvm_memory_instances`] and the debugger's class
/// counts; the UI is told to reload the session's capabilities.
pub fn set_jvm_inspector(
diff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rs
index d7aa4f656c..bcac6752e8 100644
--- a/crates/ide-dap/src/session.rs
+++ b/crates/ide-dap/src/session.rs
@@ -8,7 +8,7 @@ use crate::{Breakpoint, BreakpointState, DataBreakpoint, DebugManager, FunctionB
use ide_core::event::DebugEvent;
#[cfg(unix)]
use ide_core::process::process_tree;
-use ide_core::{DebugSessionId, IdeEvent, TaskId};
+use ide_core::{DebugSessionId, IdeEvent, RunId, TaskId};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::{BTreeSet, HashMap};
@@ -117,6 +117,9 @@ pub(crate) struct Session {
pub jvm_located: watch::Sender,
pub kotlin_mirror: Mutex>,
pub jvm_memory: tokio::sync::Mutex,
+ /// The run whose JVM this session attached to (Debug of a build tool's run, Attach to
+ /// Process on a run): that run's thread dumps go through this session.
+ pub run: Option,
pub stream_tracer: parking_lot::Mutex>>,
/// Given at start: the class breakpoints must be armed before `configurationDone`.
pub(crate) exception_classes: Option>,
@@ -333,6 +336,7 @@ impl Session {
jvm_located: watch::channel(false).0,
kotlin_mirror: Mutex::new(None),
jvm_memory: tokio::sync::Mutex::default(),
+ run: None,
stream_tracer: parking_lot::Mutex::new(None),
exception_classes: None,
exception_turn: tokio::sync::Mutex::default(),
diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs
index c9d1ba57e9..4628a54428 100644
--- a/crates/ide-dap/src/tests.rs
+++ b/crates/ide-dap/src/tests.rs
@@ -3074,6 +3074,55 @@ async fn local_attach_finds_its_jvm_before_the_debugger_connects() {
assert_eq!(session.jvm_pid.load(Ordering::Acquire), 4242);
}
+/// Gradle bootRun Debug: the JVM has no attach listener, so the session never learns its pid. The
+/// run's dump still goes through the session and, the program being stopped, signals nothing.
+#[cfg(unix)]
+#[tokio::test]
+async fn a_run_dump_goes_through_the_session_attached_to_the_run() {
+ let h = harness(Script::default());
+ let project = tempfile::tempdir().unwrap();
+ let mut cfg = remote_attach("java-debug", project.path());
+ let mut extra: Value = serde_json::from_str(cfg.extra_json.as_deref().unwrap()).unwrap();
+ extra[RUN_LINK] = json!(7);
+ cfg.extra_json = Some(extra.to_string());
+ let id = h.start(cfg).await.unwrap();
+ h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
+ assert!(h.request("attach")["arguments"].get(RUN_LINK).is_none(), "IDE-side only");
+ let session = h.manager.session(id).unwrap();
+ assert_eq!((session.run, session.jvm_pid.load(Ordering::Acquire)), (Some(RunId(7)), 0));
+
+ // `sleep` stands in for the JVM: a SIGQUIT would end it.
+ let mut jvm = std::process::Command::new("sleep").arg("30").spawn().unwrap();
+ let pid = jvm.id();
+ assert_eq!(h.manager.jvm_session_of(RunId(7), pid).map(|s| s.id), Some(id));
+ assert!(h.manager.jvm_session_of(RunId(8), pid).is_none());
+ let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid).await.unwrap().unwrap();
+ let alive = jvm.try_wait().unwrap().is_none();
+ let _ = jvm.kill();
+ let _ = jvm.wait();
+ assert_eq!(
+ dump,
+ JvmThreadsResult::Unavailable {
+ reason: JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ListenerNotRunning }
+ }
+ );
+ assert!(alive, "the stopped JVM was signalled");
+}
+
+/// A run's Dump Threads reaches the session attached to the run's JVM, not the plain run path.
+#[cfg(unix)]
+#[tokio::test]
+async fn a_run_jvm_is_found_by_the_session_attached_to_it() {
+ let h = harness(Script::default());
+ h.manager.set_jvm_finder(Arc::new(|port, _| (port == 5005).then_some(4242)));
+ let mut cfg = java_config("attach");
+ cfg.extra_json = Some(json!({"hostName": "127.0.0.1", "port": 5005}).to_string());
+ let id = h.start(cfg).await.unwrap();
+ assert_eq!(h.manager.jvm_session_of(RunId(1), 4242).map(|s| s.id), Some(id));
+ assert!(h.manager.jvm_session_of(RunId(1), 4243).is_none());
+ assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243).await.is_none());
+}
+
#[cfg(unix)]
#[tokio::test]
async fn local_attach_remembers_its_jdwp_port() {
diff --git a/crates/ide-db/Cargo.toml b/crates/ide-db/Cargo.toml
index 0843c83685..c3f0756943 100644
--- a/crates/ide-db/Cargo.toml
+++ b/crates/ide-db/Cargo.toml
@@ -17,7 +17,7 @@ specta.workspace = true
toml.workspace = true
toml_edit.workspace = true
blake3.workspace = true
-tokio.workspace = true
+tokio = { workspace = true, features = ["net"] }
tracing.workspace = true
parking_lot.workspace = true
notify.workspace = true
@@ -38,6 +38,19 @@ rsa = { version = "0.10.0-rc.18", features = ["sha2", "pkcs5"] }
zeroize = "1"
open = "5"
+[target.'cfg(unix)'.dependencies]
+libc = "0.2"
+
+[target.'cfg(windows)'.dependencies]
+windows-sys = { version = "0.61", features = [
+ "Win32_Foundation",
+ "Win32_NetworkManagement_IpHelper",
+ "Win32_Networking_WinSock",
+ "Win32_System_Diagnostics_ToolHelp",
+ "Win32_System_Threading",
+ "Win32_System_JobObjects",
+] }
+
[dev-dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "net"] }
ide-ssh = { workspace = true, features = ["testing"] }
diff --git a/crates/ide-db/src/conn.rs b/crates/ide-db/src/conn.rs
index 0845d400f4..a39e382888 100644
--- a/crates/ide-db/src/conn.rs
+++ b/crates/ide-db/src/conn.rs
@@ -12,7 +12,7 @@ use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use sqlx::{
- Column, ColumnIndex, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
+ Column, ColumnIndex, ConnectOptions, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
mysql::{MySqlConnectOptions, MySqlConnection, MySqlSslMode},
pool::PoolConnection,
postgres::{PgConnectOptions, PgConnection, PgSslMode},
@@ -135,7 +135,7 @@ impl Context {
}
macro_rules! sqlx_pool {
- ($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr) => {
+ ($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr $(, $after_init:ident)?) => {
pub struct $manager {
options: $options,
init: Arc>,
@@ -170,7 +170,7 @@ macro_rules! sqlx_pool {
async fn connect(&self) -> Result {
tokio::time::timeout(self.timeout, async {
- let mut conn = <$connection>::connect_with(&self.options).await?;
+ let mut conn = self.options.connect().await?;
let context_sql = |value: Option| {
value.map(|v| {
if $driver == DbDriver::Postgres {
@@ -183,6 +183,9 @@ macro_rules! sqlx_pool {
for sql in self.init.iter() {
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut conn).await?;
}
+ $(if !self.init.is_empty() {
+ self.options.$after_init(&mut conn).await?;
+ })?
let row = sqlx::raw_sql(sqlx::AssertSqlSafe($query.to_owned())).fetch_one(&mut conn).await?;
let context = Context::new(context_sql(row.try_get(0)?));
Ok($handle {
@@ -209,7 +212,88 @@ macro_rules! sqlx_pool {
};
}
-sqlx_pool!(PgManager, PgHandle, PgConnectOptions, PgConnection, DbDriver::Postgres, "SHOW search_path");
+#[derive(Clone)]
+struct PostgresOptions {
+ connection: PgConnectOptions,
+ read_only: bool,
+}
+
+const PG_READ_ONLY_HINT: &str = "Read-only requires the pooler to track default_transaction_read_only for each client. \
+ For PgBouncer, check track_extra_parameters.";
+
+impl PostgresOptions {
+ async fn connect(&self) -> Result {
+ let mut conn = self.connection.connect().await?;
+ // A pooler can silently discard startup options. Check before giving the startup script a connection.
+ self.verify_read_only(&mut conn).await?;
+ Ok(conn)
+ }
+
+ async fn verify_read_only(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
+ if self.read_only && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
+ return Err(sqlx::Error::Configuration(
+ format!(
+ "PostgreSQL did not enable the requested default_transaction_read_only setting. \
+ Check the Advanced properties and startup script. {PG_READ_ONLY_HINT}"
+ )
+ .into(),
+ ));
+ }
+ Ok(())
+ }
+
+ async fn verify_startup_script(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
+ self.verify_read_only(conn).await?;
+ if self.read_only && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
+ return Err(sqlx::Error::Configuration(
+ "The startup script left a writable transaction open on a read-only PostgreSQL source.".into(),
+ ));
+ }
+ Ok(())
+ }
+}
+
+async fn pg_setting_on(conn: &mut PgConnection, show: &'static str) -> Result {
+ let row = sqlx::raw_sql(show).fetch_one(conn).await?;
+ Ok(row.try_get::<&str, _>(0)? == "on")
+}
+
+fn postgres_read_only_hint(read_only: bool, code: Option<&str>, message: &str) -> Option<&'static str> {
+ match (read_only, code, message) {
+ (
+ true,
+ Some("08P01"),
+ "unsupported startup parameter in options: default_transaction_read_only"
+ | "unsupported startup parameter: default_transaction_read_only",
+ ) => Some(PG_READ_ONLY_HINT),
+ (true, Some("08P01"), "unsupported startup parameter: options") => Some(
+ "This endpoint rejects PostgreSQL startup options. Use an endpoint that supports and tracks \
+ default_transaction_read_only for each client.",
+ ),
+ _ => None,
+ }
+}
+
+fn postgres_connect_error(error: sqlx::Error, read_only: bool) -> IdeError {
+ let hint =
+ error.as_database_error().and_then(|db| postgres_read_only_hint(read_only, db.code().as_deref(), db.message()));
+ let mut error = db_err(error);
+ if let Some(hint) = hint {
+ error.message.push_str(". ");
+ error.message.push_str(hint);
+ }
+ error
+}
+
+sqlx_pool!(
+ PgManager,
+ PgHandle,
+ PostgresOptions,
+ PgConnection,
+ DbDriver::Postgres,
+ "SHOW search_path",
+ verify_startup_script
+);
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, DbDriver::Mysql, "SELECT DATABASE()");
pub struct ServerPool {
@@ -980,17 +1064,18 @@ impl Pool {
if let Some(n) = setup.statement_cache {
opts = opts.statement_cache_capacity(n);
}
- let mut manager = PgManager { options: opts, init: init.clone(), timeout };
+ let options = PostgresOptions { connection: opts, read_only: source.read_only };
+ let mut manager = PgManager { options, init: init.clone(), timeout };
// Open once directly so authentication failures retain their database error.
let first = match manager.connect().await {
Err(e) if source.ssl == DbSslMode::Prefer && tls_failed(&e) => {
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
- manager.options = manager.options.clone().ssl_mode(PgSslMode::Disable);
+ manager.options.connection = manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
manager.connect().await
}
first => first,
}
- .map_err(db_err)?;
+ .map_err(|e| postgres_connect_error(e, source.read_only))?;
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
let _ = pool.add(first);
Ok(Pool::Postgres(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
@@ -1632,6 +1717,22 @@ mod tests {
}
}
+ #[test]
+ fn postgres_read_only_guidance_identifies_what_the_pooler_rejected() {
+ let rejected = "unsupported startup parameter in options: default_transaction_read_only";
+ assert_eq!(postgres_read_only_hint(true, Some("08P01"), rejected), Some(PG_READ_ONLY_HINT));
+ let direct = "unsupported startup parameter: default_transaction_read_only";
+ assert_eq!(postgres_read_only_hint(true, Some("08P01"), direct), Some(PG_READ_ONLY_HINT));
+ let options = postgres_read_only_hint(true, Some("08P01"), "unsupported startup parameter: options").unwrap();
+ assert!(options.contains("rejects PostgreSQL startup options"));
+ assert_eq!(postgres_read_only_hint(false, Some("08P01"), rejected), None);
+ assert_eq!(postgres_read_only_hint(true, Some("28P01"), rejected), None);
+ assert_eq!(
+ postgres_read_only_hint(true, Some("08P01"), "unsupported startup parameter: extra_float_digits"),
+ None
+ );
+ }
+
#[test]
fn prefer_retries_without_tls_only_after_a_failed_handshake() {
use std::io;
diff --git a/crates/ide-db/src/external_tunnel.rs b/crates/ide-db/src/external_tunnel.rs
new file mode 100644
index 0000000000..8cb59b8d24
--- /dev/null
+++ b/crates/ide-db/src/external_tunnel.rs
@@ -0,0 +1,436 @@
+//! An approved foreground helper behind a loopback relay owned by the IDE.
+
+use crate::DbExternalTunnel;
+use ide_core::{IdeError, IdeResult, error::ErrorKind, process};
+use parking_lot::Mutex;
+use std::io;
+use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
+use std::path::Path;
+use std::process::{Child, Command, Stdio};
+use std::sync::{Arc, Weak};
+use std::time::Duration;
+use tokio::net::{TcpListener, TcpSocket, TcpStream};
+use tokio::sync::Semaphore;
+use tokio::task::{JoinHandle, JoinSet};
+
+#[cfg(target_os = "linux")]
+#[path = "external_tunnel/linux.rs"]
+mod platform;
+#[cfg(target_os = "macos")]
+#[path = "external_tunnel/macos.rs"]
+mod platform;
+#[cfg(windows)]
+#[path = "external_tunnel/windows.rs"]
+mod platform;
+
+#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
+mod platform {
+ use super::*;
+
+ pub(super) async fn owns_socket(_: &Arc, _: SocketAddr, _: Option) -> io::Result {
+ Err(io::Error::new(io::ErrorKind::Unsupported, "socket ownership cannot be verified on this OS"))
+ }
+}
+
+const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
+const CONNECTION_TIMEOUT: Duration = Duration::from_secs(3);
+const POLL_INTERVAL: Duration = Duration::from_millis(100);
+const MAX_CONNECTIONS: usize = 128;
+static VERIFICATION_SLOTS: Semaphore = Semaphore::const_new(8);
+static HELPERS: Mutex = Mutex::new(ActiveHelpers { stopping: false, children: Vec::new() });
+
+struct ActiveHelpers {
+ stopping: bool,
+ children: Vec>,
+}
+
+/// Stop the IDE's external TCP tunnel processes before desktop exit or restart.
+pub fn stop_external_tunnels_on_exit() {
+ let children = {
+ let mut active = HELPERS.lock();
+ active.stopping = true;
+ std::mem::take(&mut active.children)
+ };
+ for helper in children.into_iter().filter_map(|child| child.upgrade()) {
+ helper.stop();
+ }
+}
+
+pub(super) struct ExternalTunnel {
+ port: u16,
+ // Keep the address reserved even after the helper exits, until the last route reference drops.
+ _listener: Arc,
+ helper: Weak,
+ task: JoinHandle<()>,
+}
+
+impl ExternalTunnel {
+ pub(super) fn validate(config: &DbExternalTunnel, target: (&str, u16)) -> IdeResult<()> {
+ helper_target(config, target).map(|_| ())
+ }
+
+ pub(super) async fn open(config: &DbExternalTunnel, target: (&str, u16)) -> IdeResult {
+ if !cfg!(any(target_os = "linux", target_os = "macos", windows)) {
+ return Err(IdeError::unavailable("External TCP tunnel socket ownership cannot be verified on this OS"));
+ }
+ let listener = Arc::new(loopback_socket()?.listen(128)?);
+ let port = listener.local_addr()?.port();
+ let reservation = loopback_socket()?;
+ let endpoint = reservation.local_addr()?;
+ let arguments = helper_arguments(config, target, endpoint.port())?;
+ drop(reservation);
+ let helper = launch_helper(Path::new(&config.executable), &arguments)?;
+
+ let ready = tokio::time::timeout(STARTUP_TIMEOUT, async {
+ loop {
+ if !helper.is_alive() {
+ return Err(IdeError::new(
+ ErrorKind::Io,
+ "The external TCP tunnel helper exited before opening its loopback listener. \
+ Check the helper command in a terminal.",
+ ));
+ }
+ if verify_socket(&helper, endpoint, None).await.map_err(|error| {
+ IdeError::new(ErrorKind::Io, format!("Could not verify the external TCP tunnel listener: {error}"))
+ })? {
+ return Ok(());
+ }
+ tokio::time::sleep(POLL_INTERVAL).await;
+ }
+ })
+ .await;
+ ready.map_err(|_| {
+ IdeError::new(
+ ErrorKind::Io,
+ format!(
+ "The external TCP tunnel helper did not open an owned listener at {endpoint} before the startup timeout. \
+ Check that the command binds to 127.0.0.1 and uses {{localPort}}."
+ ),
+ )
+ })??;
+
+ let watched_helper = Arc::downgrade(&helper);
+ let task = tokio::spawn(relay(Arc::clone(&listener), endpoint, helper));
+ Ok(Self { port, _listener: listener, helper: watched_helper, task })
+ }
+
+ pub(super) fn port(&self) -> u16 {
+ self.port
+ }
+
+ pub(super) fn is_closed(&self) -> bool {
+ self.task.is_finished() || self.helper.upgrade().is_none_or(|helper| !helper.is_alive())
+ }
+}
+
+impl Drop for ExternalTunnel {
+ fn drop(&mut self) {
+ self.task.abort();
+ }
+}
+
+fn loopback_socket() -> io::Result {
+ let socket = TcpSocket::new_v4()?;
+ #[cfg(windows)]
+ platform::make_exclusive(&socket)?;
+ socket.bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0).into())?;
+ Ok(socket)
+}
+
+fn helper_target<'a>(config: &DbExternalTunnel, (host, port): (&'a str, u16)) -> IdeResult<(&'a str, u16)> {
+ let executable = Path::new(&config.executable);
+ if !executable.is_absolute() || executable.file_name().is_none() || config.executable.contains('\0') {
+ return Err(IdeError::invalid("Choose an absolute path to the external TCP tunnel executable"));
+ }
+ #[cfg(windows)]
+ if !executable.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("exe")) {
+ return Err(IdeError::invalid("Choose an .exe file for the external TCP tunnel"));
+ }
+ let host = host.trim();
+ let host = host
+ .strip_prefix('[')
+ .and_then(|host| host.strip_suffix(']'))
+ .filter(|host| host.parse::().is_ok())
+ .unwrap_or(host);
+ let dns = host.strip_suffix('.').unwrap_or(host);
+ if host.parse::().is_err()
+ && (dns.len() > 253
+ || !dns.split('.').all(|label| {
+ let bytes = label.as_bytes();
+ bytes.len() <= 63
+ && bytes.first().is_some_and(u8::is_ascii_alphanumeric)
+ && bytes.last().is_some_and(u8::is_ascii_alphanumeric)
+ && bytes.iter().all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-')
+ }))
+ {
+ return Err(IdeError::invalid("Enter a DNS name or IP address for the external TCP tunnel"));
+ }
+ if port == 0 {
+ return Err(IdeError::invalid("Enter a valid destination port for the external TCP tunnel"));
+ }
+ if !config.arguments.iter().any(|arg| arg.contains("{localPort}")) {
+ return Err(IdeError::invalid("Include {localPort} in the external TCP tunnel arguments"));
+ }
+ if config.arguments.iter().any(|arg| arg.contains('\0')) {
+ return Err(IdeError::invalid("External TCP tunnel arguments cannot contain NUL characters"));
+ }
+ Ok((host, port))
+}
+
+fn helper_arguments(config: &DbExternalTunnel, target: (&str, u16), local_port: u16) -> IdeResult> {
+ let (host, port) = helper_target(config, target)?;
+ let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
+ let (local_port, port) = (local_port.to_string(), port.to_string());
+ let placeholders =
+ [("{host}:{port}", target.as_str()), ("{localPort}", &local_port), ("{host}", host), ("{port}", &port)];
+ Ok(config
+ .arguments
+ .iter()
+ .map(|arg| {
+ let mut remaining = arg.as_str();
+ let mut expanded = String::with_capacity(arg.len());
+ while let Some(start) = remaining.find('{') {
+ expanded.push_str(&remaining[..start]);
+ remaining = &remaining[start..];
+ if let Some((value, tail)) = placeholders
+ .into_iter()
+ .find_map(|(key, value)| remaining.strip_prefix(key).map(|tail| (value, tail)))
+ {
+ expanded.push_str(value);
+ remaining = tail;
+ } else {
+ expanded.push('{');
+ remaining = &remaining[1..];
+ }
+ }
+ expanded.push_str(remaining);
+ expanded
+ })
+ .collect())
+}
+
+fn launch_helper(executable: &Path, arguments: &[String]) -> IdeResult> {
+ let mut active = HELPERS.lock();
+ if active.stopping {
+ return Err(IdeError::cancelled());
+ }
+ let helper = Arc::new(Helper::spawn(executable, arguments).map_err(|error| {
+ IdeError::new(ErrorKind::Io, format!("Could not start the external TCP tunnel helper: {error}"))
+ })?);
+ active.children.retain(|child| child.strong_count() > 0);
+ active.children.push(Arc::downgrade(&helper));
+ Ok(helper)
+}
+
+struct Helper {
+ child: Option,
+ #[cfg(windows)]
+ job: process::Job,
+}
+
+impl Helper {
+ fn spawn(executable: &Path, arguments: &[String]) -> io::Result {
+ let mut command = Command::new(executable);
+ command
+ .args(arguments)
+ .current_dir(executable.parent().expect("validated absolute executable path"))
+ .env_clear()
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null());
+ // Keep user config discovery available without inheriting database or project variables.
+ for key in [
+ "PATH",
+ "HOME",
+ "XDG_CONFIG_HOME",
+ "XDG_CACHE_HOME",
+ "XDG_DATA_HOME",
+ "XDG_RUNTIME_DIR",
+ "USERPROFILE",
+ "APPDATA",
+ "LOCALAPPDATA",
+ "SYSTEMROOT",
+ "WINDIR",
+ "TMPDIR",
+ "TEMP",
+ "TMP",
+ "SSH_AUTH_SOCK",
+ "NO_PROXY",
+ "no_proxy",
+ ] {
+ if let Some(value) = process::host_var_os(key) {
+ command.env(key, value);
+ }
+ }
+ for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"] {
+ if let Some(value) = process::host_var_os(key)
+ && value.to_str().is_some_and(credential_free_proxy)
+ {
+ command.env(key, value);
+ }
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ // Membership of this group is an authorization check. A separate session limits
+ // membership to this child and its descendants; the leader also owns the group.
+ // SAFETY: setsid is async-signal-safe and does not access Rust state after fork.
+ unsafe {
+ command.pre_exec(|| if libc::setsid() == -1 { Err(io::Error::last_os_error()) } else { Ok(()) });
+ }
+ }
+ #[cfg(windows)]
+ {
+ platform::spawn_suspended(command)
+ }
+ #[cfg(not(windows))]
+ {
+ Ok(Self { child: Some(command.spawn()?) })
+ }
+ }
+
+ fn child(&self) -> &Child {
+ self.child.as_ref().expect("the live helper owns its child handle")
+ }
+
+ #[cfg(unix)]
+ fn pid(&self) -> u32 {
+ self.child().id()
+ }
+
+ fn is_alive(&self) -> bool {
+ #[cfg(unix)]
+ {
+ loop {
+ let mut info = std::mem::MaybeUninit::::zeroed();
+ // Keep the group leader unreaped so its id cannot be reused before group cleanup.
+ // SAFETY: valid output buffer and the id of the child owned by `self`.
+ let result = unsafe {
+ libc::waitid(
+ libc::P_PID,
+ self.pid(),
+ info.as_mut_ptr(),
+ libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
+ )
+ };
+ if result == 0 {
+ // SAFETY: the buffer was zeroed and waitid returned successfully.
+ return unsafe { info.assume_init().si_pid() == 0 };
+ }
+ if io::Error::last_os_error().kind() != io::ErrorKind::Interrupted {
+ return false;
+ }
+ }
+ }
+ #[cfg(windows)]
+ {
+ use std::os::windows::io::AsRawHandle;
+ use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
+ use windows_sys::Win32::System::Threading::WaitForSingleObject;
+ // SAFETY: the owned child handle stays open through this non-blocking check.
+ unsafe { WaitForSingleObject(self.child().as_raw_handle(), 0) == WAIT_TIMEOUT }
+ }
+ #[cfg(not(any(unix, windows)))]
+ {
+ false
+ }
+ }
+
+ fn stop(&self) {
+ #[cfg(windows)]
+ let _ = self.job.terminate();
+ #[cfg(unix)]
+ process::kill_tree_of(self.pid());
+ }
+}
+
+fn credential_free_proxy(value: &str) -> bool {
+ let url = if value.contains("://") {
+ reqwest::Url::parse(value)
+ } else {
+ reqwest::Url::parse(&format!("http://{value}"))
+ };
+ url.is_ok_and(|url| {
+ matches!(url.scheme(), "http" | "https" | "socks4" | "socks4a" | "socks5" | "socks5h")
+ && url.host().is_some()
+ && url.username().is_empty()
+ && url.password().is_none()
+ && matches!(url.path(), "" | "/")
+ && url.query().is_none()
+ && url.fragment().is_none()
+ })
+}
+
+impl Drop for Helper {
+ fn drop(&mut self) {
+ self.stop();
+ #[cfg(unix)]
+ if let Some(mut child) = self.child.take() {
+ // A helper blocked in the kernel must not hold up the async caller during cleanup.
+ if !matches!(child.try_wait(), Ok(Some(_))) {
+ let _ = std::thread::Builder::new().spawn(move || child.wait());
+ }
+ }
+ }
+}
+
+async fn relay(listener: Arc, endpoint: SocketAddr, helper: Arc) {
+ let mut connections = JoinSet::new();
+ let mut liveness = tokio::time::interval(Duration::from_secs(1));
+ liveness.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ loop {
+ tokio::select! {
+ _ = liveness.tick() => {
+ if !helper.is_alive() { break; }
+ }
+ accepted = listener.accept(), if connections.len() < MAX_CONNECTIONS => {
+ let Ok((mut client, _)) = accepted else {
+ // Transient errors such as descriptor exhaustion affect new sockets only.
+ tokio::time::sleep(POLL_INTERVAL).await;
+ continue;
+ };
+ let helper = Arc::clone(&helper);
+ connections.spawn(async move {
+ if let Ok(Ok(mut upstream)) = tokio::time::timeout(CONNECTION_TIMEOUT, connect_verified(&helper, endpoint)).await {
+ let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await;
+ true
+ } else {
+ false
+ }
+ });
+ }
+ finished = connections.join_next(), if !connections.is_empty() => {
+ if matches!(finished, Some(Ok(false)))
+ // A slow ownership probe must not interrupt already verified connections.
+ && matches!(tokio::time::timeout(CONNECTION_TIMEOUT, verify_socket(&helper, endpoint, None)).await, Ok(Ok(false)))
+ {
+ break;
+ }
+ }
+ }
+ }
+}
+
+async fn connect_verified(helper: &Arc, endpoint: SocketAddr) -> io::Result {
+ let upstream = TcpStream::connect(endpoint).await?;
+ let peer = upstream.local_addr()?;
+ // TCP connect can complete before the helper accepts. Check the server's half of this
+ // exact connection, keeping all client bytes in the IDE until that socket has an owner.
+ loop {
+ if !helper.is_alive() {
+ return Err(io::Error::new(io::ErrorKind::BrokenPipe, "external TCP tunnel helper exited"));
+ }
+ if verify_socket(helper, endpoint, Some(peer)).await? && helper.is_alive() {
+ return Ok(upstream);
+ }
+ tokio::time::sleep(POLL_INTERVAL).await;
+ }
+}
+
+async fn verify_socket(helper: &Arc, local: SocketAddr, peer: Option) -> io::Result {
+ let _slot = VERIFICATION_SLOTS.acquire().await.map_err(io::Error::other)?;
+ platform::owns_socket(helper, local, peer).await
+}
+
+#[cfg(all(test, any(target_os = "linux", target_os = "macos", windows)))]
+mod tests;
diff --git a/crates/ide-db/src/external_tunnel/linux.rs b/crates/ide-db/src/external_tunnel/linux.rs
new file mode 100644
index 0000000000..25a40bcd74
--- /dev/null
+++ b/crates/ide-db/src/external_tunnel/linux.rs
@@ -0,0 +1,92 @@
+use super::{Helper, io};
+use std::fs::{self, File};
+use std::io::{BufRead, BufReader, Read};
+use std::net::{SocketAddr, SocketAddrV4};
+use std::sync::Arc;
+
+pub(super) async fn owns_socket(helper: &Arc, local: SocketAddr, peer: Option) -> io::Result {
+ let helper = Arc::clone(helper);
+ tokio::task::spawn_blocking(move || {
+ let (SocketAddr::V4(local), peer) = (local, peer) else { return Ok(false) };
+ let peer = match peer {
+ Some(SocketAddr::V4(peer)) => Some(peer),
+ None => None,
+ _ => return Ok(false),
+ };
+ let state = if peer.is_some() { "01" } else { "0A" };
+ for (table, ipv6) in [("/proc/net/tcp", false), ("/proc/net/tcp6", true)] {
+ let file = match File::open(table) {
+ Ok(file) => file,
+ Err(error) if ipv6 && error.kind() == io::ErrorKind::NotFound => continue,
+ Err(error) => return Err(error),
+ };
+ let local = address(local, ipv6);
+ let peer = peer.map(|peer| address(peer, ipv6));
+ // Kernel rows are small, but bound the time spent scanning a busy host's table.
+ for line in BufReader::new(file.take(8 * 1024 * 1024)).lines().skip(1) {
+ let line = line?;
+ let mut fields = line.split_ascii_whitespace().skip(1);
+ let (Some(left), Some(right), Some(current_state)) = (fields.next(), fields.next(), fields.next())
+ else {
+ continue;
+ };
+ if left != local || current_state != state || peer.as_deref().is_some_and(|peer| peer != right) {
+ continue;
+ }
+ let Some(inode) = fields.nth(5).and_then(|inode| inode.parse::().ok()).filter(|inode| *inode != 0)
+ else {
+ continue;
+ };
+ if group_holds_socket(helper.pid(), inode)? {
+ return Ok(true);
+ }
+ }
+ }
+ Ok(false)
+ })
+ .await
+ .map_err(io::Error::other)?
+}
+
+fn address(address: SocketAddrV4, ipv6: bool) -> String {
+ let ip = address.ip();
+ let port = address.port();
+ if !ipv6 {
+ return format!("{:08X}:{port:04X}", u32::from_ne_bytes(ip.octets()));
+ }
+ let octets = ip.to_ipv6_mapped().octets();
+ let [a, b, c, d] = octets.as_chunks::<4>().0 else { unreachable!() };
+ format!(
+ "{:08X}{:08X}{:08X}{:08X}:{port:04X}",
+ u32::from_ne_bytes(*a),
+ u32::from_ne_bytes(*b),
+ u32::from_ne_bytes(*c),
+ u32::from_ne_bytes(*d)
+ )
+}
+
+fn group_holds_socket(group: u32, inode: u64) -> io::Result {
+ let group = i32::try_from(group).map_err(io::Error::other)?;
+ let target = format!("socket:[{inode}]");
+ for process in fs::read_dir("/proc")? {
+ let Ok(process) = process else { continue };
+ let name = process.file_name();
+ let Some(pid) = name.to_str().and_then(|name| name.parse::().ok()).filter(|pid| *pid > 0) else {
+ continue;
+ };
+ // SAFETY: this only queries the process group of the enumerated pid.
+ if unsafe { libc::getpgid(pid) } != group {
+ continue;
+ }
+ let Ok(descriptors) = fs::read_dir(process.path().join("fd")) else { continue };
+ for descriptor in descriptors.flatten() {
+ if fs::read_link(descriptor.path()).is_ok_and(|link| link.as_os_str() == target.as_str()) {
+ // SAFETY: check membership again after examining the fd directory.
+ if unsafe { libc::getpgid(pid) } == group {
+ return Ok(true);
+ }
+ }
+ }
+ }
+ Ok(false)
+}
diff --git a/crates/ide-db/src/external_tunnel/macos.rs b/crates/ide-db/src/external_tunnel/macos.rs
new file mode 100644
index 0000000000..48a3dcd291
--- /dev/null
+++ b/crates/ide-db/src/external_tunnel/macos.rs
@@ -0,0 +1,61 @@
+use super::{Helper, io};
+use std::net::{IpAddr, SocketAddr};
+use std::process::Stdio;
+use std::sync::Arc;
+use tokio::io::AsyncReadExt;
+
+const MAX_OUTPUT: u64 = 64 * 1024;
+
+pub(super) async fn owns_socket(helper: &Arc, local: SocketAddr, peer: Option) -> io::Result {
+ let group = helper.pid().to_string();
+ let sockets = format!("-iTCP:{}", local.port());
+ let state = if peer.is_some() { "-sTCP:ESTABLISHED" } else { "-sTCP:LISTEN" };
+ let mut probe = tokio::process::Command::new("/usr/sbin/lsof")
+ .args(["-nP", "-a", "-g", &group, &sockets, state, "-Fgn"])
+ .env_clear()
+ .stdin(Stdio::null())
+ .stderr(Stdio::null())
+ .stdout(Stdio::piped())
+ .kill_on_drop(true)
+ .spawn()?;
+ let mut output = Vec::new();
+ probe.stdout.take().expect("stdout is piped").take(MAX_OUTPUT + 1).read_to_end(&mut output).await?;
+ if output.len() as u64 > MAX_OUTPUT {
+ return Err(io::Error::other("loopback socket ownership output exceeded its limit"));
+ }
+ let status = probe.wait().await?;
+ if !status.success() {
+ // lsof uses exit 1 for a successful scan with no matching descriptors.
+ return if status.code() == Some(1) && output.is_empty() {
+ Ok(false)
+ } else {
+ Err(io::Error::other("loopback socket ownership query failed"))
+ };
+ }
+ let mut owned = false;
+ for line in String::from_utf8_lossy(&output).lines() {
+ match line.as_bytes().first() {
+ Some(b'p') => owned = false,
+ Some(b'g') => owned = line[1..] == group,
+ Some(b'n') if owned => {
+ let (left, right) =
+ line[1..].split_once("->").map_or((&line[1..], None), |(left, right)| (left, Some(right)));
+ if address(left) == Some(local) && right.and_then(address) == peer && right.is_some() == peer.is_some()
+ {
+ return Ok(true);
+ }
+ }
+ _ => {}
+ }
+ }
+ Ok(false)
+}
+
+fn address(value: &str) -> Option {
+ let address = value.parse::().ok()?;
+ let ip = match address.ip() {
+ IpAddr::V6(ip) => ip.to_ipv4_mapped().map_or(IpAddr::V6(ip), IpAddr::V4),
+ ip => ip,
+ };
+ Some(SocketAddr::new(ip, address.port()))
+}
diff --git a/crates/ide-db/src/external_tunnel/tests.rs b/crates/ide-db/src/external_tunnel/tests.rs
new file mode 100644
index 0000000000..101ffbbca5
--- /dev/null
+++ b/crates/ide-db/src/external_tunnel/tests.rs
@@ -0,0 +1,188 @@
+use super::*;
+use std::io::{Read, Write};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+const EXAMPLE: &[u8; 4] = b"test";
+const FIXTURE: &str = "external_tunnel::tests::fixture_entry";
+
+fn config(mode: &str) -> crate::DbExternalTunnel {
+ crate::DbExternalTunnel {
+ executable: std::env::current_exe().unwrap().to_str().unwrap().to_owned(),
+ arguments: vec!["--exact".into(), FIXTURE.into(), "--skip".into(), format!("wire-{mode}-{{localPort}}")],
+ }
+}
+
+const TARGET: (&str, u16) = ("db.example", 5432);
+
+// The test binary doubles as a foreground helper without an external interpreter.
+#[test]
+fn fixture_entry() {
+ let Some(fixture) = std::env::args().find(|arg| arg.starts_with("wire-")) else { return };
+ #[cfg(unix)]
+ // SAFETY: these calls only inspect the current process's session and group.
+ assert_eq!(unsafe { libc::getsid(0) }, unsafe { libc::getpgrp() });
+ let (mode, port) = fixture.strip_prefix("wire-").unwrap().split_once('-').unwrap();
+ let endpoint = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port.parse().unwrap());
+ match mode {
+ "exit" => (),
+ "idle" => std::thread::sleep(Duration::from_secs(60)),
+ "waiting" => {
+ let observer = std::env::args()
+ .find_map(|arg| arg.strip_prefix("observer-port-").and_then(|port| port.parse::().ok()))
+ .unwrap();
+ let _observer = std::net::TcpStream::connect((Ipv4Addr::LOCALHOST, observer)).unwrap();
+ std::thread::sleep(Duration::from_secs(60));
+ }
+ "tree" => {
+ let mut child = Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", FIXTURE, "--skip", &format!("wire-echo-{port}")])
+ .spawn()
+ .unwrap();
+ assert!(child.wait().unwrap().success());
+ }
+ "echo" | "once" => {
+ let socket = std::net::TcpListener::bind(endpoint).unwrap();
+ std::thread::sleep(Duration::from_millis(150));
+ for stream in socket.incoming() {
+ let mut stream = stream.unwrap();
+ let mut bytes = [0; EXAMPLE.len()];
+ if stream.read_exact(&mut bytes).is_ok() {
+ stream.write_all(&bytes).unwrap();
+ stream.write_all(&endpoint.port().to_be_bytes()).unwrap();
+ if mode == "once" {
+ let _ = stream.read(&mut [0]);
+ break;
+ }
+ }
+ }
+ }
+ _ => unreachable!(),
+ }
+}
+
+#[tokio::test]
+async fn forwards_multiple_connections_to_the_helpers_child_and_cleans_up() {
+ let tunnel = ExternalTunnel::open(&config("tree"), TARGET).await.unwrap();
+ let mut helper_port = 0;
+ for _ in 0..2 {
+ let result = tokio::time::timeout(Duration::from_secs(5), async {
+ let mut db = TcpStream::connect((Ipv4Addr::LOCALHOST, tunnel.port())).await.unwrap();
+ db.write_all(EXAMPLE).await.unwrap();
+ let mut bytes = [0; EXAMPLE.len()];
+ db.read_exact(&mut bytes).await.unwrap();
+ assert_eq!(&bytes, EXAMPLE);
+ db.read_u16().await.unwrap()
+ });
+ helper_port = result.await.unwrap();
+ }
+ assert_ne!(helper_port, tunnel.port());
+ assert!(!tunnel.is_closed());
+ drop(tunnel);
+ tokio::time::timeout(Duration::from_secs(5), async {
+ loop {
+ if TcpStream::connect((Ipv4Addr::LOCALHOST, helper_port)).await.is_err() {
+ break;
+ }
+ tokio::time::sleep(POLL_INTERVAL).await;
+ }
+ })
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn reports_a_helper_that_exits_without_listening() {
+ let result = ExternalTunnel::open(&config("exit"), TARGET).await;
+ assert!(result.err().unwrap().message.contains("exited"));
+}
+
+#[tokio::test]
+async fn dropping_startup_stops_the_helper_before_it_listens() {
+ let observer = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
+ let mut settings = config("waiting");
+ settings.arguments.extend(["--skip".into(), format!("observer-port-{}", observer.local_addr().unwrap().port())]);
+ let startup = tokio::spawn(async move { ExternalTunnel::open(&settings, TARGET).await });
+
+ let (mut helper_socket, _) =
+ tokio::time::timeout(Duration::from_secs(10), observer.accept()).await.unwrap().unwrap();
+ assert!(!startup.is_finished());
+ startup.abort();
+ assert!(startup.await.err().unwrap().is_cancelled());
+ let error = tokio::time::timeout(Duration::from_secs(5), helper_socket.read_u8()).await.unwrap().unwrap_err();
+ // Terminating the helper can reset its observer socket on Windows.
+ assert!(matches!(error.kind(), io::ErrorKind::UnexpectedEof | io::ErrorKind::ConnectionReset), "{error}");
+}
+
+#[tokio::test]
+async fn refuses_an_unrelated_established_loopback_socket() {
+ let unrelated = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
+ let endpoint = unrelated.local_addr().unwrap();
+ let settings = config("idle");
+ let arguments = helper_arguments(&settings, TARGET, endpoint.port()).unwrap();
+ let helper = Arc::new(Helper::spawn(Path::new(&settings.executable), &arguments).unwrap());
+ assert!(helper.is_alive());
+ assert!(!verify_socket(&helper, endpoint, None).await.unwrap());
+
+ let listener = loopback_socket().unwrap().listen(128).unwrap();
+ let relay_endpoint = listener.local_addr().unwrap();
+ let task = tokio::spawn(relay(Arc::new(listener), endpoint, helper));
+ tokio::time::timeout(Duration::from_secs(10), async {
+ let mut db = TcpStream::connect(relay_endpoint).await.unwrap();
+ db.write_all(EXAMPLE).await.unwrap();
+ let (mut accepted, _) = unrelated.accept().await.unwrap();
+ assert_eq!(accepted.read_u8().await.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
+ task.await.unwrap();
+ })
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn a_dead_helper_keeps_its_relay_port_reserved_until_the_route_drops() {
+ let tunnel = ExternalTunnel::open(&config("once"), TARGET).await.unwrap();
+ let endpoint = SocketAddrV4::new(Ipv4Addr::LOCALHOST, tunnel.port());
+ tokio::time::timeout(Duration::from_secs(5), async {
+ let mut db = TcpStream::connect(endpoint).await.unwrap();
+ db.write_all(EXAMPLE).await.unwrap();
+ let mut bytes = [0; EXAMPLE.len()];
+ db.read_exact(&mut bytes).await.unwrap();
+ assert_eq!(&bytes, EXAMPLE);
+ db.read_u16().await.unwrap();
+ drop(db);
+ while !tunnel.is_closed() {
+ tokio::time::sleep(POLL_INTERVAL).await;
+ }
+ })
+ .await
+ .unwrap();
+ assert!(std::net::TcpListener::bind(endpoint).is_err());
+}
+
+#[test]
+fn only_credential_free_proxy_addresses_reach_the_helper() {
+ assert!(credential_free_proxy("proxy.example:3128"));
+ assert!(credential_free_proxy("socks5h://proxy.example:1080"));
+ assert!(!credential_free_proxy("https://user:password@proxy.example:3128"));
+ assert!(!credential_free_proxy("https://proxy.example:3128/?secret=value"));
+}
+
+#[test]
+fn expands_only_literal_arguments_and_validates_the_target() {
+ let settings = crate::DbExternalTunnel {
+ executable: config("echo").executable,
+ arguments: vec!["--port={localPort}".into(), "{host}:{port}".into(), "a b \"quotes\"".into()],
+ };
+ let arguments = helper_arguments(&settings, TARGET, 12345).unwrap();
+ assert_eq!(arguments, ["--port=12345", "db.example:5432", "a b \"quotes\""]);
+ assert!(helper_arguments(&settings, ("--some-option", 5432), 12345).is_err());
+}
+
+#[test]
+fn brackets_an_ipv6_host_port_pair_but_preserves_the_raw_host_argument() {
+ let settings = crate::DbExternalTunnel {
+ executable: config("echo").executable,
+ arguments: vec!["{localPort}".into(), "{host}:{port}".into(), "{host}".into(), "[{host}]:{port}".into()],
+ };
+ let arguments = helper_arguments(&settings, ("[2001:db8::a]", 6432), 12345).unwrap();
+ assert_eq!(arguments, ["12345", "[2001:db8::a]:6432", "2001:db8::a", "[2001:db8::a]:6432"]);
+}
diff --git a/crates/ide-db/src/external_tunnel/windows.rs b/crates/ide-db/src/external_tunnel/windows.rs
new file mode 100644
index 0000000000..6ccab334de
--- /dev/null
+++ b/crates/ide-db/src/external_tunnel/windows.rs
@@ -0,0 +1,161 @@
+use super::{Helper, io, process};
+use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4};
+use std::os::windows::io::{AsRawHandle, AsRawSocket, FromRawHandle, OwnedHandle};
+use std::os::windows::process::CommandExt;
+use std::process::Command;
+use std::sync::Arc;
+use tokio::net::TcpSocket;
+use windows_sys::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, INVALID_HANDLE_VALUE, NO_ERROR};
+use windows_sys::Win32::NetworkManagement::IpHelper::{
+ GetExtendedTcpTable, MIB_TCP_STATE_ESTAB, MIB_TCP_STATE_LISTEN, MIB_TCP6ROW_OWNER_PID, MIB_TCPROW_OWNER_PID,
+ TCP_TABLE_OWNER_PID_ALL,
+};
+use windows_sys::Win32::Networking::WinSock::{
+ AF_INET, AF_INET6, SO_EXCLUSIVEADDRUSE, SOCKET_ERROR, SOL_SOCKET, WSAGetLastError, setsockopt,
+};
+use windows_sys::Win32::System::Diagnostics::ToolHelp::{
+ CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
+};
+use windows_sys::Win32::System::Threading::{CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME};
+
+pub(super) fn make_exclusive(socket: &TcpSocket) -> io::Result<()> {
+ let enabled = 1i32;
+ // SAFETY: the socket is open and the option value remains valid for this call.
+ let result = unsafe {
+ setsockopt(
+ socket.as_raw_socket() as usize,
+ SOL_SOCKET,
+ SO_EXCLUSIVEADDRUSE,
+ (&raw const enabled).cast(),
+ size_of::() as i32,
+ )
+ };
+ if result == SOCKET_ERROR {
+ // SAFETY: reads the last Winsock error on the calling thread.
+ return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }));
+ }
+ Ok(())
+}
+
+pub(super) fn spawn_suspended(mut command: Command) -> io::Result {
+ let mut child = command.creation_flags(CREATE_SUSPENDED | process::CREATE_NO_WINDOW).spawn()?;
+ let Some(job) = process::Job::for_child(&child) else {
+ // The child has never executed, so there are no descendants to terminate.
+ let _ = child.kill();
+ return Err(io::Error::other("could not contain the external tunnel helper in a Windows job"));
+ };
+ let helper = Helper { child: Some(child), job };
+ resume_initial_thread(helper.child().id())?;
+ Ok(helper)
+}
+
+fn resume_initial_thread(pid: u32) -> io::Result<()> {
+ // SAFETY: the snapshot handle is owned here, and each enumeration call writes a sized entry.
+ unsafe {
+ let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
+ if snapshot == INVALID_HANDLE_VALUE {
+ return Err(io::Error::last_os_error());
+ }
+ let snapshot = OwnedHandle::from_raw_handle(snapshot);
+ let mut entry = THREADENTRY32 { dwSize: size_of::