mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-25 02:44:03 -10:00
Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4ca3d7857 | ||
|
|
5f17748295 | ||
|
|
2d94628d1d | ||
|
|
26aabf5229 | ||
|
|
87ce01d251 | ||
|
|
3dd918c5b2 | ||
|
|
9a74fe4418 | ||
|
|
a70a0ae6f1 | ||
|
|
9be4803462 | ||
|
|
8122127dde | ||
|
|
cdcce048fe | ||
|
|
1cea43694e | ||
|
|
260ac4efbf | ||
|
|
9805fb42b8 | ||
|
|
4a18d4d205 | ||
|
|
9ecef0ef0f | ||
|
|
aec80ced53 | ||
|
|
e5a4a6940a | ||
|
|
196af0ac37 | ||
|
|
1e4388490c | ||
|
|
ad8958901b | ||
|
|
25b49b1473 | ||
|
|
1a689ff5da | ||
|
|
2544db3025 | ||
|
|
6355534ed5 | ||
|
|
7bc26b9387 | ||
|
|
d7b9401a07 | ||
|
|
465e4f80bc | ||
|
|
1743aec533 | ||
|
|
52e2215dcf | ||
|
|
57bccc916c | ||
|
|
46a712524d | ||
|
|
0f5607d76c | ||
|
|
8c23c589ca | ||
|
|
ae7a8e74c8 | ||
|
|
a7b67347c2 | ||
|
|
707b6fe169 | ||
|
|
b9a0c66ca6 | ||
|
|
26f83240a7 | ||
|
|
c6bb0b84ce | ||
|
|
09d1f4a673 | ||
|
|
3b875620d2 | ||
|
|
843f2024c5 | ||
|
|
4ed7bf14d6 | ||
|
|
4bc46baddb |
No files matched your search
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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": "<button class=\"ds-btn ds-btn-primary\">OK</button>",
|
||||
"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": "<button class=\"ds-btn ds-btn-secondary\">Cancel</button>",
|
||||
"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": "<button class=\"ds-btn-ghost\">Show all</button>",
|
||||
"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": "<div class=\"ds-iconbar\"><button class=\"ds-icon-btn\" aria-label=\"Refresh\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M13 8a5 5 0 1 1-1.46-3.54M13 3v2.5h-2.5\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></button><button class=\"ds-icon-btn\" aria-label=\"Show options\" aria-pressed=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M2.5 4.5h11M2.5 8h11M2.5 11.5h11\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\"/></svg></button></div>",
|
||||
"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": "<input class=\"ds-input\" placeholder=\"Project name\" />",
|
||||
"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": "<button class=\"ds-chip\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\"><circle cx=\"5\" cy=\"4\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"5\" cy=\"12\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"11\" cy=\"6\" r=\"1.5\" stroke=\"currentColor\"/><path d=\"M5 5.5v5M11 7.5c0 2-2 2.5-6 3\" stroke=\"currentColor\"/></svg><span>main</span></button>",
|
||||
"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": "<div class=\"ds-tree\" tabindex=\"0\"><div class=\"ds-row\">src</div><div class=\"ds-row ds-row-sel\">main.tsx</div><div class=\"ds-row\">workbench</div></div>",
|
||||
"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": "<div class=\"ds-frame\"><div class=\"ds-island ds-side\"><div class=\"ds-head\">Project</div></div><div class=\"ds-island ds-main\"><code>fn main() {}</code></div></div>",
|
||||
"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": "<div class=\"ds-tooltip\">Run 'main' <span class=\"ds-kbd\">⌃R</span></div>",
|
||||
"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."
|
||||
]
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -158,7 +158,17 @@
|
||||
"src/features/run/**/*.ts",
|
||||
"src/features/run/**/*.tsx",
|
||||
"src/features/database/**/*.ts",
|
||||
"src/features/database/**/*.tsx"
|
||||
"src/features/database/**/*.tsx",
|
||||
"src/features/analysis/**/*.ts",
|
||||
"src/features/analysis/**/*.tsx",
|
||||
"src/features/project-tree/**/*.ts",
|
||||
"src/features/project-tree/**/*.tsx",
|
||||
"src/features/http-client/**/*.ts",
|
||||
"src/features/http-client/**/*.tsx",
|
||||
"src/platform/**/*.ts",
|
||||
"src/platform/**/*.tsx",
|
||||
"src/features/debugger/**/*.ts",
|
||||
"src/features/debugger/**/*.tsx"
|
||||
],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error"
|
||||
|
||||
Generated
+1
@@ -4189,6 +4189,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"which",
|
||||
]
|
||||
|
||||
|
||||
@@ -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.
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
# Product
|
||||
|
||||
<!-- impeccable:product-schema 1 -->
|
||||
|
||||
## 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 `<button>` and `<input>` 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.
|
||||
@@ -196,11 +196,11 @@ fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Vec<AgentConfig
|
||||
.filter(|o| config::is_per_model_option(o))
|
||||
.cloned()
|
||||
.map(|mut o| {
|
||||
if config::is_context_option(&o.id) {
|
||||
if config::is_context_option(&o.id) || config::is_fast_option(&o.id) {
|
||||
if o.category.is_none() {
|
||||
o.category = Some("model_config".into());
|
||||
}
|
||||
} else if o.category.as_deref() != Some("thought_level") {
|
||||
} else if o.category.is_none() {
|
||||
o.category = Some("thought_level".into());
|
||||
}
|
||||
o
|
||||
|
||||
@@ -168,11 +168,12 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
|
||||
assert_eq!(calls.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/new"]);
|
||||
assert_eq!(calls[1].1["mcpServers"], json!([]));
|
||||
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
|
||||
let fast = cursor.config.iter().find(|o| o.id == "fast").expect("fast option");
|
||||
// Per-model options (`effort`, `fast`, `context`) belong to the session's model, not provider-wide config.
|
||||
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
|
||||
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
|
||||
let fast = cursor.thought_levels["m1"].iter().find(|o| o.id == "fast").expect("fast option");
|
||||
assert_eq!(fast.category.as_deref(), Some("model_config"));
|
||||
assert_eq!(fast.current.as_deref(), Some("false"));
|
||||
// The effort option belongs to the session's model; m2 may offer other levels.
|
||||
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
|
||||
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ use tokio::time::Instant;
|
||||
|
||||
const FRESH_FOR: Duration = Duration::from_secs(15 * 60);
|
||||
const COOLDOWN: Duration = Duration::from_secs(30);
|
||||
/// Persisted catalog layout version; bump when option classification changes so stale per-model entries re-discover.
|
||||
const CATALOG_SCHEMA: u8 = 2;
|
||||
|
||||
type Store = Arc<Mutex<HashMap<String, Known>>>;
|
||||
type Key = (PathBuf, PathBuf, String);
|
||||
@@ -80,6 +82,8 @@ impl CatalogData {
|
||||
pub(crate) struct SavedCatalog {
|
||||
/// An opaque cryptographic digest, never raw launch arguments or credentials.
|
||||
fingerprint: String,
|
||||
#[serde(default)]
|
||||
schema: u8,
|
||||
#[serde(flatten)]
|
||||
catalog: CatalogData,
|
||||
}
|
||||
@@ -111,7 +115,7 @@ impl LaunchContext {
|
||||
hash.update(&(value.len() as u64).to_le_bytes());
|
||||
hash.update(value);
|
||||
}
|
||||
field(&mut hash, b"openidea-model-catalog-v1");
|
||||
field(&mut hash, b"openidea-model-catalog-v2");
|
||||
field(
|
||||
&mut hash,
|
||||
match self.spec.driver {
|
||||
@@ -200,7 +204,14 @@ impl AgentCatalogs {
|
||||
cache
|
||||
.get(provider)
|
||||
.and_then(|known| known.catalogs.get(&shared.root_key()))
|
||||
.map(|saved| saved.catalog.clone())
|
||||
.map(|saved| {
|
||||
let mut catalog = saved.catalog.clone();
|
||||
if saved.schema < CATALOG_SCHEMA {
|
||||
catalog.refreshed_at_ms = None;
|
||||
catalog.thought_levels.clear();
|
||||
}
|
||||
catalog
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -228,7 +239,8 @@ impl AgentCatalogs {
|
||||
}
|
||||
drop(state);
|
||||
let cache = shared.known.lock();
|
||||
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
|
||||
let saved = cache.get(provider)?.catalogs.get(&shared.root_key())?;
|
||||
(saved.schema >= CATALOG_SCHEMA).then(|| saved.catalog.thought_levels.get(model).cloned()).flatten()
|
||||
}
|
||||
|
||||
pub(super) async fn load_levels(
|
||||
@@ -281,7 +293,7 @@ impl AgentCatalogs {
|
||||
AgentModelCatalog {
|
||||
provider: provider.to_owned(),
|
||||
config: shared.config_for_new_task(catalog.config, provider),
|
||||
thought_levels: catalog.thought_levels,
|
||||
thought_levels: shared.thought_levels_for_new_task(catalog.thought_levels, provider),
|
||||
refreshing: entry.flight.is_some(),
|
||||
refreshed_at_ms: catalog.refreshed_at_ms,
|
||||
retry_at_ms: model_failure
|
||||
@@ -318,7 +330,9 @@ impl AgentCatalogs {
|
||||
let generation = state.generation;
|
||||
let saved =
|
||||
shared.known.lock().get(&spec.id).and_then(|known| known.catalogs.get(&shared.root_key())).cloned();
|
||||
let matching = saved.as_ref().is_some_and(|saved| saved.fingerprint == context.fingerprint());
|
||||
let matching = saved
|
||||
.as_ref()
|
||||
.is_some_and(|saved| saved.schema >= CATALOG_SCHEMA && saved.fingerprint == context.fingerprint());
|
||||
let age = saved
|
||||
.as_ref()
|
||||
.filter(|_| matching)
|
||||
@@ -489,7 +503,11 @@ impl AgentCatalogs {
|
||||
}
|
||||
known.catalogs.insert(
|
||||
shared.root_key(),
|
||||
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
|
||||
SavedCatalog {
|
||||
fingerprint: entry.context.fingerprint(),
|
||||
schema: CATALOG_SCHEMA,
|
||||
catalog: catalog.clone(),
|
||||
},
|
||||
);
|
||||
entry.catalog = Some(catalog);
|
||||
shared.persist_known(&cache);
|
||||
|
||||
@@ -65,7 +65,7 @@ fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
}
|
||||
|
||||
/// Moves options that approve everything without asking to a value that asks: the agent's
|
||||
/// default or ask mode, else its first one that asks.
|
||||
/// own default (when it asks), else `default` or `ask`, else its first one that asks.
|
||||
pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
for option in config {
|
||||
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
|
||||
@@ -73,9 +73,15 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
continue;
|
||||
}
|
||||
let asks = |v: &&AgentConfigValue| !bypass(&v.value);
|
||||
let value = ["default", "ask"]
|
||||
.iter()
|
||||
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
|
||||
let value = option
|
||||
.default_value
|
||||
.as_deref()
|
||||
.and_then(|def| option.values.iter().filter(asks).find(|v| v.value == def))
|
||||
.or_else(|| {
|
||||
["default", "ask"]
|
||||
.iter()
|
||||
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
|
||||
})
|
||||
.or_else(|| option.values.iter().find(asks));
|
||||
if let Some(value) = value {
|
||||
option.current = Some(value.value.clone());
|
||||
@@ -83,11 +89,26 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode that approves everything without asking (`bypassPermissions`, `yolo`, `full-access`…), if the agent has one.
|
||||
pub(crate) fn bypass_mode(options: &[AgentConfigOption]) -> Option<(&AgentConfigOption, &AgentConfigValue)> {
|
||||
let option = options.iter().find(|o| o.category.as_deref() == Some("mode"))?;
|
||||
let value = option.values.iter().find(|v| is_bypass_mode(&v.value))?;
|
||||
Some((option, value))
|
||||
/// Moves approval-bearing options (`mode`, `permissions`, `approval`) to their approving value.
|
||||
pub(crate) fn apply_bypass_approvals(config: &mut [AgentConfigOption]) {
|
||||
for option in config {
|
||||
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
|
||||
if let Some(value) = option.values.iter().find(|v| bypass(&v.value)) {
|
||||
option.current = Some(value.value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies provider-specific defaults to per-model options for new tasks without altering `default_value`.
|
||||
pub(crate) fn apply_model_defaults(provider: &str, options: &mut [AgentConfigOption]) {
|
||||
if provider != "cursor" {
|
||||
return;
|
||||
}
|
||||
if let Some(fast) = options.iter_mut().find(|o| is_fast_option(&o.id))
|
||||
&& fast.values.iter().any(|v| v.value == "false")
|
||||
{
|
||||
fast.current = Some("false".into());
|
||||
}
|
||||
}
|
||||
|
||||
fn is_bypass_mode(mode: &str) -> bool {
|
||||
@@ -126,14 +147,20 @@ pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
|
||||
}
|
||||
|
||||
pub(crate) fn is_context_option(id: &str) -> bool {
|
||||
matches!(id, "context_tier" | "contextTier")
|
||||
matches!(id, "context" | "context_tier" | "contextTier")
|
||||
}
|
||||
|
||||
pub(crate) fn is_fast_option(id: &str) -> bool {
|
||||
id == "fast"
|
||||
}
|
||||
|
||||
/// Whether an option's available values and default belong to the selected model
|
||||
/// (`thought_level` and model context-tier options) rather than the provider as a whole.
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
|
||||
/// rather than the provider as a whole.
|
||||
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier"))
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|
||||
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
|| is_fast_option(&o.id)
|
||||
|| is_context_option(&o.id)
|
||||
}
|
||||
|
||||
@@ -164,7 +191,7 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
|
||||
matches!(id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
.then(|| "thought_level".into())
|
||||
})
|
||||
.or_else(|| (id == "fast" || is_context_option(&id)).then(|| "model_config".into()))
|
||||
.or_else(|| (is_fast_option(&id) || is_context_option(&id)).then(|| "model_config".into()))
|
||||
}),
|
||||
current,
|
||||
default_value,
|
||||
@@ -337,6 +364,11 @@ fn legacy(
|
||||
}
|
||||
}
|
||||
|
||||
fn clean_label(s: String, fallback: &str) -> String {
|
||||
let trimmed = s.trim_matches(|c: char| c.is_whitespace() || matches!(c, '\u{200B}'..='\u{200D}' | '\u{FEFF}'));
|
||||
if trimmed.is_empty() { fallback.to_owned() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
fn value_of(v: &Value) -> Option<AgentConfigValue> {
|
||||
let value = v.get("value")?.as_str()?.to_owned();
|
||||
let meta = v.get("_meta");
|
||||
@@ -352,7 +384,7 @@ fn value_of(v: &Value) -> Option<AgentConfigValue> {
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
Some(AgentConfigValue {
|
||||
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
|
||||
name: str_of(v, "name").map(|n| clean_label(n, &value)).unwrap_or_else(|| value.clone()),
|
||||
description: str_of(v, "description"),
|
||||
cost_category,
|
||||
usage_multiplier,
|
||||
@@ -434,19 +466,16 @@ mod tests {
|
||||
]}
|
||||
}));
|
||||
assert!(bypass_approvals(&full_access));
|
||||
assert_eq!(bypass_mode(&full_access).map(|(_, v)| v.value.as_str()), Some("full-access"));
|
||||
|
||||
let asking = options_of(&json!({
|
||||
let mut asking = options_of(&json!({
|
||||
"modes": {"currentModeId": "ask", "availableModes": [
|
||||
{"id": "ask", "name": "Ask"}, {"id": "full-access", "name": "Full Access"}
|
||||
]}
|
||||
}));
|
||||
assert!(!bypass_approvals(&asking));
|
||||
assert_eq!(
|
||||
bypass_mode(&asking).map(|(_, v)| v.value.as_str()),
|
||||
Some("full-access"),
|
||||
"the offered bypass mode stays available"
|
||||
);
|
||||
apply_bypass_approvals(&mut asking);
|
||||
assert_eq!(asking[0].current.as_deref(), Some("full-access"));
|
||||
assert!(bypass_approvals(&asking));
|
||||
|
||||
let permissions = |current: &str| {
|
||||
options_of(&json!({"configOptions": [{
|
||||
@@ -503,7 +532,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effort_and_fast_categories_are_inferred_from_ids() {
|
||||
fn effort_context_and_fast_are_per_model_options() {
|
||||
let mut c = options_of(&json!({
|
||||
"configOptions": [
|
||||
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
|
||||
@@ -512,19 +541,39 @@ mod tests {
|
||||
"_meta": {"copilotPriceCategory": "Medium", "copilotUsage": "1x"}}]},
|
||||
{"id": "effort", "type": "select", "currentValue": "medium",
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
|
||||
{"id": "context", "type": "select", "currentValue": "256k",
|
||||
"options": [{"value": "256k", "name": "256K"}, {"value": "500k", "name": "500K"}]},
|
||||
{"id": "contextTier", "type": "select", "currentValue": "default",
|
||||
"options": [{"value": "default", "name": "200K"}, {"value": "long_context", "name": "1M"}]},
|
||||
{"id": "fast", "type": "select", "currentValue": "false",
|
||||
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]}
|
||||
{"id": "fast", "type": "select", "currentValue": "true",
|
||||
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "Fast\u{200b}\u{200b}"}]}
|
||||
]
|
||||
}));
|
||||
assert_eq!(c.len(), 4);
|
||||
assert_eq!(c.len(), 5);
|
||||
assert_eq!(c[0].values[0].cost_category.as_deref(), Some("medium"));
|
||||
assert_eq!(c[0].values[0].usage_multiplier.as_deref(), Some("1x"));
|
||||
assert_eq!(c[1].category.as_deref(), Some("thought_level"));
|
||||
assert_eq!(c[1].default_value.as_deref(), Some("medium"));
|
||||
assert_eq!(c[2].category.as_deref(), Some("model_config"));
|
||||
assert!(is_per_model_option(&c[1]) && is_per_model_option(&c[2]) && !is_per_model_option(&c[3]));
|
||||
assert_eq!(c[3].category.as_deref(), Some("model_config"));
|
||||
assert_eq!(c[4].category.as_deref(), Some("model_config"));
|
||||
assert_eq!(c[4].values[1].name, "Fast");
|
||||
assert!(
|
||||
is_per_model_option(&c[1])
|
||||
&& is_per_model_option(&c[2])
|
||||
&& is_per_model_option(&c[3])
|
||||
&& is_per_model_option(&c[4])
|
||||
);
|
||||
assert!(!is_per_model_option(&c[0]));
|
||||
|
||||
// Cursor defaults fast off for new tasks while preserving the agent's own default_value.
|
||||
let mut cursor_opts = c.clone();
|
||||
apply_model_defaults("cursor", &mut cursor_opts);
|
||||
let fast = cursor_opts.iter().find(|o| o.id == "fast").unwrap();
|
||||
assert_eq!((fast.current.as_deref(), fast.default_value.as_deref()), (Some("false"), Some("true")));
|
||||
let mut other_opts = c.clone();
|
||||
apply_model_defaults("claude", &mut other_opts);
|
||||
assert_eq!(other_opts.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("true"));
|
||||
|
||||
// Editing effort on the same model preserves its initial `default_value` for Reset.
|
||||
merge_update(
|
||||
@@ -546,11 +595,34 @@ mod tests {
|
||||
{"id": "model", "type": "select", "currentValue": "gpt-6-sol",
|
||||
"options": [{"value": "gemini-4-carbon"}, {"value": "gpt-6-sol"}]},
|
||||
{"id": "effort", "type": "select", "currentValue": "low",
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]}
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
|
||||
{"id": "context", "type": "select", "currentValue": "1m",
|
||||
"options": [{"value": "300k", "name": "300K"}, {"value": "1m", "name": "1M"}]}
|
||||
]),
|
||||
);
|
||||
let effort = c.iter().find(|o| o.id == "effort").unwrap();
|
||||
assert_eq!((effort.current.as_deref(), effort.default_value.as_deref()), (Some("low"), Some("low")));
|
||||
let context = c.iter().find(|o| o.id == "context").unwrap();
|
||||
assert_eq!((context.current.as_deref(), context.default_value.as_deref()), (Some("1m"), Some("1m")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_bypass_approvals_covers_mode_permissions_and_approval() {
|
||||
let mut c = options_of(&json!({"configOptions": [
|
||||
{"id": "mode", "category": "mode", "type": "select", "currentValue": "ask",
|
||||
"options": [{"value": "ask"}, {"value": "full-access"}]},
|
||||
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "off",
|
||||
"options": [{"value": "off"}, {"value": "on"}]},
|
||||
{"id": "approval", "category": "approval", "type": "select", "currentValue": "ask",
|
||||
"options": [{"value": "ask"}, {"value": "bypass"}]}
|
||||
]}));
|
||||
apply_bypass_approvals(&mut c);
|
||||
assert_eq!(ids(&c), [("mode", Some("full-access")), ("allow_all", Some("on")), ("approval", Some("bypass"))]);
|
||||
// Original agent default_values stay intact.
|
||||
assert_eq!(
|
||||
c.iter().map(|o| o.default_value.as_deref()).collect::<Vec<_>>(),
|
||||
[Some("ask"), Some("off"), Some("ask")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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<AgentImage> {
|
||||
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<AgentImage> {
|
||||
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<AgentImage> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
+215
-48
@@ -16,6 +16,7 @@ mod conversation;
|
||||
mod elicitation;
|
||||
mod external;
|
||||
pub mod hermes;
|
||||
mod images;
|
||||
pub mod mcp;
|
||||
mod model;
|
||||
mod native;
|
||||
@@ -330,19 +331,23 @@ impl Shared {
|
||||
let hook = self.new_task_approvals.read().clone();
|
||||
if hook.is_some_and(|ask| ask() == ide_core::settings::NewTaskApprovals::Ask) {
|
||||
config::ask_for_approvals(&mut config);
|
||||
return config;
|
||||
}
|
||||
if let Some((o, v)) = config::bypass_mode(&config).map(|(o, v)| (o.id.clone(), v.value.clone()))
|
||||
&& let Some(o) = config.iter_mut().find(|c| c.id == o)
|
||||
{
|
||||
o.current = Some(v);
|
||||
}
|
||||
if let Some(o) = config.iter_mut().find(|o| o.id == config::CURSOR_APPROVAL) {
|
||||
o.current = Some("bypass".into());
|
||||
} else {
|
||||
config::apply_bypass_approvals(&mut config);
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
pub(crate) fn thought_levels_for_new_task(
|
||||
&self,
|
||||
mut levels: BTreeMap<String, Vec<AgentConfigOption>>,
|
||||
provider: &str,
|
||||
) -> BTreeMap<String, Vec<AgentConfigOption>> {
|
||||
for options in levels.values_mut() {
|
||||
config::apply_model_defaults(provider, options);
|
||||
}
|
||||
levels
|
||||
}
|
||||
|
||||
/// The commands the agent offered last time in this project.
|
||||
fn known_commands(&self, provider: &str) -> Vec<AgentCommand> {
|
||||
let cache = self.known.lock();
|
||||
@@ -374,8 +379,19 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
// Discovery reads one model's options; a session on another model reports that model's.
|
||||
// Restore each option's agent default so a session's manual overrides never pollute the catalog.
|
||||
if acp && let Some((model, config)) = model.zip(config) {
|
||||
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
|
||||
let levels: Vec<_> = config
|
||||
.iter()
|
||||
.filter(|o| config::is_per_model_option(o))
|
||||
.cloned()
|
||||
.map(|mut o| {
|
||||
if let Some(def) = o.default_value.clone().filter(|d| o.values.iter().any(|v| v.value == *d)) {
|
||||
o.current = Some(def);
|
||||
}
|
||||
o
|
||||
})
|
||||
.collect();
|
||||
if !levels.is_empty() {
|
||||
self.paths.catalogs.learn_levels(self, provider, model, levels);
|
||||
}
|
||||
@@ -419,9 +435,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<BTreeSet<String>>,
|
||||
/// The checkout as the last turn started, its copies in the store's `<id>.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<worktree::TurnStart>,
|
||||
/// The checkout as each turn of the conversation started (by turn, `None` where it wasn't
|
||||
/// recorded), the copies in the store's `<id>.turn` folder.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
turns: Vec<Option<worktree::TurnStart>>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
subagents: Vec<SavedSubagent>,
|
||||
/// Turns to drop from the session once it is loaded (a fork of an earlier point).
|
||||
@@ -455,6 +475,16 @@ impl PendingModel {
|
||||
/// The changed files of a checkout, stamped.
|
||||
type Snapshot = BTreeMap<String, worktree::Stamp>;
|
||||
|
||||
/// Holds `TaskState::busy` for the duration of an operation so concurrent prompts or rollbacks
|
||||
/// wait until it finishes.
|
||||
struct BusyGuard(Arc<Task>);
|
||||
|
||||
impl Drop for BusyGuard {
|
||||
fn drop(&mut self) {
|
||||
self.0.state.lock().busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
struct TaskState {
|
||||
task: AgentTask,
|
||||
session_id: Option<String>,
|
||||
@@ -467,8 +497,8 @@ struct TaskState {
|
||||
saved: Option<String>,
|
||||
/// See `TaskFile::touched`.
|
||||
touched: Option<Arc<BTreeSet<String>>>,
|
||||
/// See `TaskFile::turn`.
|
||||
turn: Option<Arc<worktree::TurnStart>>,
|
||||
/// See `TaskFile::turns`.
|
||||
turns: Vec<Option<Arc<worktree::TurnStart>>>,
|
||||
pending_rollback: u32,
|
||||
/// The user named the task; see `TaskFile::title_renamed`.
|
||||
title_renamed: bool,
|
||||
@@ -721,7 +751,7 @@ impl AgentManager {
|
||||
let mut info = provider::describe(p);
|
||||
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
|
||||
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
|
||||
info.thought_levels = catalog.thought_levels;
|
||||
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
|
||||
info.commands = self.shared.known_commands(&p.id);
|
||||
info
|
||||
})
|
||||
@@ -989,6 +1019,7 @@ impl AgentManager {
|
||||
saved: None,
|
||||
touched: Some(BTreeSet::new()),
|
||||
turn: None,
|
||||
turns: Vec::new(),
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: true,
|
||||
@@ -1043,7 +1074,7 @@ impl AgentManager {
|
||||
};
|
||||
// Until the session reports its own, show what the agent offered last time with the choices applied.
|
||||
let catalog = self.shared.paths.catalogs.cached(&self.shared, &spec.id);
|
||||
let mut levels = catalog.thought_levels;
|
||||
let mut levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &spec.id);
|
||||
let mut config = self.shared.config_for_new_task(catalog.config, &spec.id);
|
||||
for choice in &req.config {
|
||||
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
|
||||
@@ -1116,6 +1147,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 +1510,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 +1529,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<Option<AgentPrompt>> {
|
||||
/// 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<Option<AgentPrompt>> {
|
||||
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 +1570,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 +1600,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 +1966,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<Task>,
|
||||
turn: usize,
|
||||
total_turns: usize,
|
||||
) -> IdeResult<Vec<worktree::PutBack>> {
|
||||
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::<BTreeSet<String>>()
|
||||
});
|
||||
(
|
||||
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<Task>,
|
||||
planned: Vec<worktree::PutBack>,
|
||||
) -> IdeResult<Vec<(String, worktree::Stamp)>> {
|
||||
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<Option<Arc<worktree::TurnStart>>>) {
|
||||
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 +2114,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 +2366,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 +2406,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 +2445,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 +2453,38 @@ impl Task {
|
||||
/// The checkout as the last turn started, with the folder of its copies.
|
||||
fn last_turn(&self) -> (PathBuf, Option<Arc<worktree::TurnStart>>, 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<Self>) {
|
||||
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 +2506,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 +2679,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 +3837,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<Self>, 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;
|
||||
}
|
||||
|
||||
@@ -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<Value> = 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(
|
||||
|
||||
@@ -348,36 +348,18 @@ pub(super) fn user_input(prompt: &Value) -> Vec<Value> {
|
||||
}
|
||||
"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!("<file path=\"{path}\">\n{text}\n</file>") }))
|
||||
}
|
||||
"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<crate::model::AgentImage> {
|
||||
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<Value> {
|
||||
"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));
|
||||
}
|
||||
|
||||
+158
-11
@@ -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");
|
||||
@@ -3942,14 +3942,10 @@ async fn composer_commands_discover_cursor_effort_and_fast() {
|
||||
assert!(calls.iter().any(|m| m.as_str() == "session/new"));
|
||||
assert_eq!(calls.iter().filter(|m| m.as_str() == "initialize").count(), 1);
|
||||
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
|
||||
assert_eq!(cursor.config.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("false"));
|
||||
assert!(
|
||||
cursor
|
||||
.thought_levels
|
||||
.values()
|
||||
.next()
|
||||
.is_some_and(|levels| { levels.iter().any(|o| o.category.as_deref() == Some("thought_level")) })
|
||||
);
|
||||
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
|
||||
let levels = cursor.thought_levels.values().next().expect("discovered model options");
|
||||
assert_eq!(levels.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("false"));
|
||||
assert!(levels.iter().any(|o| o.category.as_deref() == Some("thought_level")));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -4665,6 +4661,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);
|
||||
|
||||
@@ -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<AgentEntry>,
|
||||
@@ -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<String>
|
||||
})
|
||||
}
|
||||
|
||||
/// Folds a tool update's content into its output, diffs and images.
|
||||
fn merge_content(
|
||||
content: &[Value],
|
||||
output: &mut Option<String>,
|
||||
images: &mut Vec<AgentImage>,
|
||||
diffs: &mut Vec<AgentToolDiff>,
|
||||
) {
|
||||
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::<AgentEntry>(&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();
|
||||
|
||||
@@ -697,12 +697,24 @@ pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
|
||||
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<String, Stamp>, dir: &Pa
|
||||
Ok(saved)
|
||||
}
|
||||
|
||||
fn restore_content(
|
||||
cwd: &Path,
|
||||
rev: Option<&str>,
|
||||
change: &AgentChange,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<Option<Vec<u8>>> {
|
||||
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<String, Stamp>,
|
||||
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<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<PutBack>> {
|
||||
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<Vec<u8>> {
|
||||
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<BTreeSet<String>>,
|
||||
/// 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<String> {
|
||||
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<TurnStart> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::default()) };
|
||||
pub(crate) fn start_turn(cwd: &Path, dir: &Path) -> IdeResult<TurnStart> {
|
||||
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<Item = &'a TurnStart>) {
|
||||
let used: BTreeSet<String> =
|
||||
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<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// 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<String>) -> IdeResult<Vec<PutBack>> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
|
||||
let mut lower_counts: BTreeMap<String, usize> = 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<PutBack>,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<Vec<(String, Stamp)>> {
|
||||
// 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<S
|
||||
fn at_turn_start(at: &TurnRepos, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
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::<BTreeSet<_>>();
|
||||
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<String> = 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");
|
||||
|
||||
@@ -10,3 +10,6 @@ ide-core.workspace = true
|
||||
serde.workspace = true
|
||||
specta.workspace = true
|
||||
which = "8"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -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<PathBuf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The SDK's `emulator` executable, which starts AVDs.
|
||||
pub fn emulator_executable() -> Option<PathBuf> {
|
||||
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<Vec<AndroidDevice>> {
|
||||
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() {
|
||||
|
||||
@@ -965,6 +965,7 @@ pub struct LaunchBuild {
|
||||
|
||||
/// Compiles the module at `module` with its build system before a JVM launch and
|
||||
/// returns the class directories it wrote, to put ahead of the jdtls classpath.
|
||||
/// The build's console, messages and progress stream to `on_event` as it runs.
|
||||
pub fn build_for_launch(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
@@ -972,8 +973,9 @@ pub fn build_for_launch(
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<LaunchBuild> {
|
||||
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel)?;
|
||||
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel, on_event)?;
|
||||
Ok(built.pop().unwrap())
|
||||
}
|
||||
|
||||
@@ -986,9 +988,10 @@ pub fn build_for_launches(
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<Vec<LaunchBuild>> {
|
||||
let plan = merged_launch_plan(root, model, modules, test, kind, cancel)?;
|
||||
let result = run(root, &plan, cancel, &|_| {})?;
|
||||
let result = run(root, &plan, cancel, on_event)?;
|
||||
let failure = if !result.success {
|
||||
let errors: Vec<String> = result
|
||||
.messages
|
||||
@@ -1822,8 +1825,16 @@ mod tests {
|
||||
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let mut model = reactor_model();
|
||||
model.maven.as_mut().unwrap().projects[0].command = wrapper.to_string_lossy().into_owned();
|
||||
let dirs = build_for_launch(root, &model, &root.join("app"), true, BuildKind::Build, &CancellationToken::new())
|
||||
.unwrap();
|
||||
let dirs = build_for_launch(
|
||||
root,
|
||||
&model,
|
||||
&root.join("app"),
|
||||
true,
|
||||
BuildKind::Build,
|
||||
&CancellationToken::new(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
dirs.class_dirs,
|
||||
["app/target/test-classes", "app/target/classes", "middle/target/classes", "lib/target/classes"]
|
||||
@@ -1834,16 +1845,25 @@ mod tests {
|
||||
"mvnw",
|
||||
"#!/bin/sh\necho '[ERROR] Kotlin compilation failed: unresolved reference broken' >&2\nexit 1\n",
|
||||
);
|
||||
let error =
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new())
|
||||
.unwrap()
|
||||
.failure
|
||||
.unwrap();
|
||||
let error = build_for_launch(
|
||||
root,
|
||||
&model,
|
||||
&root.join("app"),
|
||||
false,
|
||||
BuildKind::Build,
|
||||
&CancellationToken::new(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap()
|
||||
.failure
|
||||
.unwrap();
|
||||
assert!(error.contains("Kotlin compilation failed"), "{error}");
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert_eq!(
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel).unwrap_err().kind,
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel, &|_| {})
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ide_core::error::ErrorKind::Cancelled
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ mod process;
|
||||
#[cfg(test)]
|
||||
mod process_numbers;
|
||||
pub mod sbt;
|
||||
pub mod surefire;
|
||||
mod sync;
|
||||
pub mod web;
|
||||
mod xml;
|
||||
|
||||
@@ -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 `<properties>`.
|
||||
|
||||
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 {
|
||||
/// `<argLine>`, split into JVM options.
|
||||
pub arg_line: Vec<String>,
|
||||
/// `<systemPropertyVariables>` and the older `<systemProperties>`.
|
||||
pub system_properties: BTreeMap<String, String>,
|
||||
/// `<environmentVariables>`.
|
||||
pub environment: BTreeMap<String, String>,
|
||||
pub working_directory: Option<String>,
|
||||
/// `<additionalClasspathElements>`.
|
||||
pub additional_classpath: Vec<String>,
|
||||
/// `<classpathDependencyExcludes>`: `groupId:artifactId`.
|
||||
pub classpath_excludes: Vec<String>,
|
||||
}
|
||||
|
||||
/// 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<SurefireConfig> {
|
||||
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<Element> = 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<String, String> = 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))
|
||||
}
|
||||
|
||||
/// `<build><plugins>` Surefire's configuration, then its `default-test` execution's.
|
||||
fn read(project: &Element, props: &HashMap<String, String>, 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));
|
||||
}
|
||||
// `<systemProperties>`: `<property><name/><value/></property>` (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<String> {
|
||||
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, String>) -> 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<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut current: Option<String> = None;
|
||||
let mut quote: Option<char> = 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#"<project>
|
||||
<groupId>com.example</groupId><artifactId>orders</artifactId><version>1</version>
|
||||
<properties><openideaFail>true</openideaFail><mockito>/m2/mockito.jar</mockito></properties>
|
||||
<build><plugins><plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>@{argLine} @{jacoco} -javaagent:${mockito} --add-opens "java.base/java.lang=ALL-UNNAMED" -Dx=${undefined}</argLine>
|
||||
<systemPropertyVariables><openidea.fail>${openideaFail}</openidea.fail><dir>${project.build.directory}</dir></systemPropertyVariables>
|
||||
<systemProperties><property><name>old</name><value>style</value></property></systemProperties>
|
||||
<environmentVariables><TZ>UTC</TZ></environmentVariables>
|
||||
<additionalClasspathElements><additionalClasspathElement>${basedir}/extra</additionalClasspathElement></additionalClasspathElements>
|
||||
<classpathDependencyExcludes><classpathDependencyExclude>org.slf4j:slf4j-simple</classpathDependencyExclude></classpathDependencyExcludes>
|
||||
</configuration>
|
||||
<executions><execution><id>default-test</id><configuration><workingDirectory>${basedir}/work</workingDirectory></configuration></execution></executions>
|
||||
</plugin></plugins></build>
|
||||
</project>"#;
|
||||
|
||||
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("<argLine>", "<argLine>-Xmx1g ").replace("<TZ>UTC</TZ>", "<TZ>Asia/Tokyo</TZ>");
|
||||
std::fs::write(cache.join("effective-pom-0.xml"), format!("<projects>{effective}</projects>")).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", ""]);
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<u8>> {
|
||||
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<u8> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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<PathBuf> {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
@@ -201,6 +201,7 @@ pub struct FoldingSettings {
|
||||
pub file_header: bool,
|
||||
pub imports: bool,
|
||||
pub doc_comments: bool,
|
||||
pub go_short_blocks: bool,
|
||||
}
|
||||
|
||||
impl Default for FoldingSettings {
|
||||
@@ -211,6 +212,7 @@ impl Default for FoldingSettings {
|
||||
file_header: true,
|
||||
imports: true,
|
||||
doc_comments: false,
|
||||
go_short_blocks: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -362,6 +364,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<String>,
|
||||
/// Code vision as a whole (usages, author and language-server lenses); the switches below apply while it is on.
|
||||
pub code_vision: bool,
|
||||
@@ -394,6 +398,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,
|
||||
|
||||
@@ -264,6 +264,20 @@ pub struct FlutterDevice {
|
||||
pub emulator: bool,
|
||||
/// The adb state keeping it from being used (`unauthorized`, `offline`, …).
|
||||
pub unavailable: Option<String>,
|
||||
/// The [`FlutterEmulator`] it runs on: an AVD name, or `apple_ios_simulator`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub emulator_id: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
/// See [`FlutterDeviceList`].
|
||||
@@ -289,6 +303,10 @@ pub enum FlutterDaemonStatus {
|
||||
pub struct FlutterDeviceList {
|
||||
pub status: FlutterDaemonStatus,
|
||||
pub devices: Vec<FlutterDevice>,
|
||||
/// The emulators that no listed device runs on.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub emulators: Vec<FlutterEmulator>,
|
||||
}
|
||||
|
||||
/// See [`IdeEvent::Direnv`].
|
||||
|
||||
@@ -145,7 +145,7 @@ impl Default for AgentSettings {
|
||||
show_work_time: true,
|
||||
show_usage_limits: true,
|
||||
show_cost: false,
|
||||
fold_turns: true,
|
||||
fold_turns: false,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
@@ -1657,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 {
|
||||
@@ -2099,8 +2113,10 @@ mod tests {
|
||||
assert!(old.agents.show_cost);
|
||||
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
|
||||
assert!(!old.agents.fit_window_width);
|
||||
assert!(!old.agents.fold_turns);
|
||||
assert!(!Settings::default().agents.show_cost);
|
||||
assert!(!Settings::default().agents.fit_window_width);
|
||||
assert!(!Settings::default().agents.fold_turns);
|
||||
let mut settings = Settings::default();
|
||||
settings.agents.show_usage_limits = false;
|
||||
settings.agents.fit_window_width = true;
|
||||
@@ -2318,6 +2334,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();
|
||||
|
||||
@@ -30,7 +30,7 @@ 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 use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, VirtualThreadsNote, 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];
|
||||
|
||||
@@ -33,6 +33,7 @@ pub(crate) trait AttachProbe: Send + Sync {
|
||||
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;
|
||||
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError>;
|
||||
}
|
||||
|
||||
pub(super) struct JdkProbe {
|
||||
@@ -91,6 +92,10 @@ impl AttachProbe for JdkProbe {
|
||||
fn is_application_jvm(&self, pid: u32) -> bool {
|
||||
ide_jvm_attach::is_application_jvm(pid)
|
||||
}
|
||||
|
||||
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError> {
|
||||
ide_jvm_attach::thread_dump_json(pid, dir, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
|
||||
}
|
||||
}
|
||||
|
||||
fn alive(pid: u32) -> bool {
|
||||
|
||||
@@ -47,6 +47,8 @@ struct FakeProbe {
|
||||
application_jvms: Vec<u32>,
|
||||
/// Pids `ensure_listener` was asked for.
|
||||
ensured: parking_lot::Mutex<Vec<u32>>,
|
||||
json_dumps: parking_lot::Mutex<VecDeque<Result<String, AttachError>>>,
|
||||
json_dirs: parking_lot::Mutex<Vec<PathBuf>>,
|
||||
}
|
||||
|
||||
type StopHook = Box<dyn Fn() + Send + Sync>;
|
||||
@@ -109,6 +111,8 @@ impl FakeProbe {
|
||||
listener_starts: parking_lot::Mutex::new(VecDeque::new()),
|
||||
application_jvms: Vec::new(),
|
||||
ensured: parking_lot::Mutex::new(Vec::new()),
|
||||
json_dumps: parking_lot::Mutex::new(VecDeque::new()),
|
||||
json_dirs: parking_lot::Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,6 +197,12 @@ impl AttachProbe for FakeProbe {
|
||||
fn is_application_jvm(&self, pid: u32) -> bool {
|
||||
self.application_jvms.contains(&pid)
|
||||
}
|
||||
fn thread_dump_json(&self, _pid: u32, dir: &Path) -> Result<String, AttachError> {
|
||||
self.enter("thread_dump_json");
|
||||
self.json_dirs.lock().push(dir.to_owned());
|
||||
self.leave();
|
||||
self.json_dumps.lock().pop_front().expect("unexpected JSON thread dump request")
|
||||
}
|
||||
}
|
||||
|
||||
const FLAGS: &str = "-XX:+UseCompressedOops -XX:+StartAttachListener";
|
||||
@@ -1205,10 +1215,95 @@ fn threads_jvm(reason: JvmMemoryUnavailable) -> JvmThreadsUnavailable {
|
||||
JvmThreadsUnavailable::Jvm { reason }
|
||||
}
|
||||
|
||||
/// The text dump alone: without a directory no JSON dump is asked for.
|
||||
fn dump_text(fake: &FakeProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
|
||||
dump_threads(fake, pid, suspended, None, &|| suspended)
|
||||
}
|
||||
|
||||
fn ready_dump(r: JvmThreadsResult) -> JvmThreadDump {
|
||||
match r {
|
||||
JvmThreadsResult::Ready { dump } => dump,
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
const VIRTUAL_JSON: &str = r#"{"threadDump":{"threadContainers":[]}}"#;
|
||||
|
||||
fn json_dir() -> &'static Path {
|
||||
Path::new("/data/cache/heap-snapshots/x")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_below_21_ask_for_no_json() {
|
||||
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
|
||||
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, None));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_on_21_add_the_json_after_the_text() {
|
||||
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
|
||||
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
|
||||
assert_eq!(dump.text, THREADS);
|
||||
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
|
||||
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_json_dump_keeps_the_text_dump() {
|
||||
let cases = [
|
||||
(AttachError::TooLarge, VirtualThreadsNote::TooLarge),
|
||||
(AttachError::Timeout, VirtualThreadsNote::Failed),
|
||||
(AttachError::Protocol("no thread dump file".into()), VirtualThreadsNote::Failed),
|
||||
];
|
||||
for (error, note) in cases {
|
||||
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
*fake.json_dumps.lock() = vec![Err(error)].into();
|
||||
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
|
||||
assert_eq!((dump.text.as_str(), dump.virtual_json, dump.virtual_note), (THREADS, None, Some(note)));
|
||||
}
|
||||
|
||||
// No directory to write the file into.
|
||||
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
let dump = ready_dump(dump_text(&fake, 12, false));
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::Failed)));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_text_dump_asks_for_no_json() {
|
||||
let fake = dumping_threads(99, vec![Err(AttachError::Timeout)]);
|
||||
let r = dump_threads(&fake, 12, false, Some(json_dir()), &|| false);
|
||||
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::TimedOut));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_while_suspended_on_21_skip_the_json() {
|
||||
let fake = dumping_threads(12, vec![Ok(THREADS.into())]);
|
||||
let dump = ready_dump(dump_threads(&fake, 12, true, Some(json_dir()), &|| true));
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["thread_print"]);
|
||||
|
||||
// The program hits a breakpoint while the text dump is taken.
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
let stop = stopped.clone();
|
||||
fake.stops_on = Some(("thread_print", Box::new(move || stop.store(true, Ordering::SeqCst))));
|
||||
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| stopped.load(Ordering::SeqCst)));
|
||||
assert!(!dump.taken_while_suspended);
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[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 r = dump_text(&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);
|
||||
@@ -1218,10 +1313,7 @@ fn threads_while_running_start_the_listener() {
|
||||
#[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_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
}
|
||||
|
||||
@@ -1230,12 +1322,12 @@ 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_unavailable(dump_text(&fake, 12, true)),
|
||||
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })
|
||||
);
|
||||
fake.version = None;
|
||||
assert_eq!(
|
||||
threads_unavailable(dump_threads(&fake, 12, true)),
|
||||
threads_unavailable(dump_text(&fake, 12, true)),
|
||||
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 })
|
||||
);
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
@@ -1245,7 +1337,7 @@ fn threads_while_suspended_on_11_are_refused() {
|
||||
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 r = dump_text(&fake, 12, true);
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert!(dump.taken_while_suspended);
|
||||
assert_eq!(dump.java_version, "17.0.13");
|
||||
@@ -1257,7 +1349,7 @@ 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 r = dump_tree(&fake, &[10, 11, 12], false, None, &|| false);
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!(dump.pid, 12);
|
||||
assert_eq!(*fake.ensured.lock(), [12]);
|
||||
@@ -1266,7 +1358,7 @@ fn threads_of_a_tree_without_a_listener_go_to_its_first_application_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_unavailable(dump_tree(&fake, &[10, 11], false, None, &|| false)),
|
||||
threads_jvm(JvmMemoryUnavailable::NoJvmProcess)
|
||||
);
|
||||
assert_eq!(*fake.ensured.lock(), [10]);
|
||||
@@ -1290,7 +1382,7 @@ async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reporte
|
||||
let fake = Arc::new(fake);
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let target = JvmTarget::Launched(std::process::id() as i32);
|
||||
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
|
||||
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!(dump.pid, jvm);
|
||||
assert_eq!(*fake.ensured.lock(), [jvm]);
|
||||
@@ -1340,7 +1432,7 @@ async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
|
||||
let bare = stopped_attach(0);
|
||||
let fake = Arc::new(dumping_threads(99, Vec::new()));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
|
||||
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
|
||||
@@ -1348,7 +1440,7 @@ async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
|
||||
let bare = bare_session("attach");
|
||||
let fake = Arc::new(dumping_threads(99, vec![Ok(THREADS.into())]));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 555, None).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]);
|
||||
@@ -1369,26 +1461,71 @@ async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() {
|
||||
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
|
||||
let fake = Arc::new(fake);
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).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<dyn AttachProbe> = fake.clone();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).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<dyn AttachProbe> = Arc::new(fake);
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).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_asks_for_no_json_while_the_session_holds_it() {
|
||||
let bare = stopped_attach(4242);
|
||||
let fake = Arc::new(dumping_threads(4242, vec![Ok(THREADS.into())]));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
|
||||
assert!(dump.taken_while_suspended);
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["thread_print"]);
|
||||
|
||||
// Running at first, the program hits a breakpoint while the text dump is taken.
|
||||
let bare = bare_session("attach");
|
||||
bare.session.jvm_pid.store(4242, Ordering::Release);
|
||||
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
|
||||
let session = bare.session.clone();
|
||||
fake.stops_on = Some(("thread_print", Box::new(move || session.suspended.stopped(None, true))));
|
||||
let fake = Arc::new(fake);
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
|
||||
assert!(!dump.taken_while_suspended);
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_dump_through_a_linked_session_whose_jvm_is_not_located_asks_for_no_json_while_stopped() {
|
||||
// Gradle bootRun Debug after an earlier run dump opened the listener: the session's pid is still 0.
|
||||
let bare = stopped_attach(0);
|
||||
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
|
||||
assert_eq!((dump.pid, dump.taken_while_suspended), (555, true));
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["thread_print"]);
|
||||
|
||||
// Running, the same session gets the JSON dump too.
|
||||
let bare = bare_session("attach");
|
||||
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
|
||||
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
|
||||
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
|
||||
let bare = bare_session("attach");
|
||||
@@ -1397,7 +1534,7 @@ async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
|
||||
let histogram = bare.session.jvm_memory.lock().await;
|
||||
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242));
|
||||
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242, None));
|
||||
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);
|
||||
@@ -1411,28 +1548,28 @@ 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));
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
assert_eq!(threads_unavailable(dump_text(&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));
|
||||
assert_eq!(threads_unavailable(dump_text(&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!(threads_unavailable(dump_text(&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));
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
|
||||
fake.alive = false;
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
assert_eq!(threads_unavailable(dump_text(&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 {
|
||||
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_text(&fake, 12, false)) else {
|
||||
panic!("not a failure")
|
||||
};
|
||||
assert!(message.contains("no"), "{message}");
|
||||
@@ -1456,14 +1593,20 @@ fn thread_results_serialize_with_camel_case_tags() {
|
||||
java_version: String::new(),
|
||||
taken_while_suspended: true,
|
||||
elapsed_ms: 3,
|
||||
virtual_json: None,
|
||||
virtual_note: Some(VirtualThreadsNote::WhileSuspended),
|
||||
};
|
||||
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}
|
||||
"dump": {
|
||||
"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3,
|
||||
"virtualJson": null, "virtualNote": "whileSuspended"
|
||||
}
|
||||
})
|
||||
);
|
||||
assert_eq!(serde_json::to_value(VirtualThreadsNote::TooLarge).unwrap(), serde_json::json!("tooLarge"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -1479,7 +1622,7 @@ async fn threads_take_the_memory_lock() {
|
||||
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))
|
||||
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32), None)
|
||||
);
|
||||
assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. }));
|
||||
let threads = threads.unwrap();
|
||||
@@ -1493,12 +1636,14 @@ async fn threads_take_the_memory_lock() {
|
||||
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 suspended = Arc::new(Suspension::default());
|
||||
let fake = Arc::new(dumping_threads(0, Vec::new()));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
|
||||
let running = state.lock().await;
|
||||
let mut queued = Box::pin(thread_dump(&state, || suspended.get(), |_| probe, JvmTarget::Launched(pid as i32)));
|
||||
let stopped = suspended.clone();
|
||||
let target = JvmTarget::Launched(pid as i32);
|
||||
let mut queued = Box::pin(thread_dump(&state, move || stopped.get(), |_| probe, target, Some(json_dir().into())));
|
||||
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);
|
||||
@@ -1515,12 +1660,27 @@ async fn attached_thread_dump_keeps_the_scanned_jvm() {
|
||||
fake.jdwp = Some((5005, 4242));
|
||||
let probe: Arc<dyn AttachProbe> = 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 r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!(dump.pid, 4242);
|
||||
assert_eq!(jvm_pid.load(Ordering::SeqCst), 4242);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn session_thread_dump_writes_the_json_into_the_given_directory() {
|
||||
let pid = std::process::id();
|
||||
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
|
||||
let fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
|
||||
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
|
||||
let fake = Arc::new(fake);
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let target = JvmTarget::Launched(pid as i32);
|
||||
let r = thread_dump(&state, || false, |_| probe, target, Some(json_dir().into())).await.unwrap();
|
||||
assert_eq!(ready_dump(r).virtual_json.as_deref(), Some(VIRTUAL_JSON));
|
||||
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capability_matches_memory() {
|
||||
for adapter in JVM_MEMORY_ADAPTERS.iter().copied().chain(["debugpy"]) {
|
||||
|
||||
@@ -8,11 +8,15 @@ use super::{
|
||||
};
|
||||
use crate::session::Session;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_jvm_attach::AttachError;
|
||||
use ide_jvm_attach::{AttachError, JavaVersion};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The first release whose virtual threads are final and that writes the JSON dump.
|
||||
const VIRTUAL_THREADS_MAJOR: u32 = 21;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JvmThreadDump {
|
||||
@@ -23,6 +27,20 @@ pub struct JvmThreadDump {
|
||||
pub taken_while_suspended: bool,
|
||||
/// Wall time of the `Thread.print` request.
|
||||
pub elapsed_ms: u32,
|
||||
/// `Thread.dump_to_file -format=json`, which also lists virtual threads; JDK 21+ only.
|
||||
pub virtual_json: Option<String>,
|
||||
/// Why `virtual_json` is missing from a JDK 21+ dump; none below 21.
|
||||
pub virtual_note: Option<VirtualThreadsNote>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VirtualThreadsNote {
|
||||
/// A debugger holds the VM, which would hang the JSON request until it resumes.
|
||||
WhileSuspended,
|
||||
/// Over the attach reply limit (64 MiB).
|
||||
TooLarge,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -48,13 +66,17 @@ pub enum JvmThreadsResult {
|
||||
Unavailable { reason: JvmThreadsUnavailable },
|
||||
}
|
||||
|
||||
/// A thread dump of `pid`, a JVM no debugger holds. Blocking for up to the listener start and
|
||||
/// A thread dump of `pid`, a JVM no debugger holds; `json_dir` is an absolute, owner-only
|
||||
/// directory the JVM may write the JSON dump into. 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 fn run_jvm_thread_dump(pid: u32, json_dir: Option<&Path>) -> JvmThreadsResult {
|
||||
dump_threads(&JdkProbe { suspended: false }, pid, false, json_dir, &|| false)
|
||||
}
|
||||
|
||||
pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmThreadsResult> {
|
||||
pub(crate) async fn session_thread_dump(
|
||||
session: Arc<Session>,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
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
|
||||
@@ -62,7 +84,9 @@ pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmT
|
||||
tokio::spawn(async move {
|
||||
let target = session_target(&session, launched);
|
||||
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
|
||||
thread_dump(&session.jvm_memory, || capture_suspended(&session), probe, target).await
|
||||
let stopped = session.clone();
|
||||
let suspended = move || capture_suspended(&stopped);
|
||||
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
|
||||
@@ -70,43 +94,53 @@ pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmT
|
||||
|
||||
/// 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<Session>, pid: u32) -> IdeResult<JvmThreadsResult> {
|
||||
pub(crate) async fn debugged_run_thread_dump(
|
||||
session: Arc<Session>,
|
||||
pid: u32,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
// Detached for the same reason as `session_thread_dump`.
|
||||
tokio::spawn(async move {
|
||||
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
|
||||
known_pid_dump(&session, probe, pid).await
|
||||
known_pid_dump(&session, probe, pid, json_dir).await
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
|
||||
}
|
||||
|
||||
/// The session's suspension decides the JSON dump too: it is read again before that request.
|
||||
pub(super) async fn known_pid_dump(
|
||||
session: &Session,
|
||||
session: &Arc<Session>,
|
||||
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
|
||||
pid: u32,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
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
|
||||
let stopped = session.clone();
|
||||
let suspended = move || capture_suspended(&stopped);
|
||||
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).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.
|
||||
/// session; `suspended_now` and then `probe` are read once it is held, and `suspended_now` again
|
||||
/// before the JSON dump.
|
||||
pub(super) async fn thread_dump(
|
||||
state: &tokio::sync::Mutex<JvmMemoryState>,
|
||||
suspended: impl FnOnce() -> bool,
|
||||
suspended_now: impl Fn() -> bool + Send + Sync + 'static,
|
||||
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
|
||||
target: JvmTarget<'_>,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
let _turn = state.lock().await;
|
||||
let suspended = suspended();
|
||||
let suspended = suspended_now();
|
||||
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)),
|
||||
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended, json_dir.as_deref(), &suspended_now)),
|
||||
Err(reason) => (None, jvm(reason)),
|
||||
})
|
||||
.await
|
||||
@@ -118,19 +152,32 @@ pub(super) async fn thread_dump(
|
||||
/// `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 {
|
||||
pub(super) fn dump_tree(
|
||||
probe: &dyn AttachProbe,
|
||||
tree: &[i32],
|
||||
suspended: bool,
|
||||
json_dir: Option<&Path>,
|
||||
suspended_now: &dyn Fn() -> 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),
|
||||
Some(pid) => dump_threads(probe, pid, suspended, json_dir, suspended_now),
|
||||
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 {
|
||||
/// The JSON dump follows a text dump that succeeded; its failure only sets the note.
|
||||
pub(crate) fn dump_threads(
|
||||
probe: &dyn AttachProbe,
|
||||
pid: u32,
|
||||
suspended: bool,
|
||||
json_dir: Option<&Path>,
|
||||
suspended_now: &dyn Fn() -> bool,
|
||||
) -> JvmThreadsResult {
|
||||
if suspended {
|
||||
if !probe.has_listener(pid) {
|
||||
return jvm(gone(probe, pid));
|
||||
@@ -149,6 +196,8 @@ pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -
|
||||
Err(e) => return failure(probe, pid, e),
|
||||
};
|
||||
let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
|
||||
let (virtual_json, virtual_note) =
|
||||
virtual_threads(probe, pid, version.as_ref(), suspended, json_dir, suspended_now);
|
||||
JvmThreadsResult::Ready {
|
||||
dump: JvmThreadDump {
|
||||
text,
|
||||
@@ -156,10 +205,40 @@ pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -
|
||||
java_version: version.map(|v| v.text).unwrap_or_default(),
|
||||
taken_while_suspended: suspended,
|
||||
elapsed_ms,
|
||||
virtual_json,
|
||||
virtual_note,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The program may have stopped during the text dump, so the suspension is read again.
|
||||
fn virtual_threads(
|
||||
probe: &dyn AttachProbe,
|
||||
pid: u32,
|
||||
version: Option<&JavaVersion>,
|
||||
suspended: bool,
|
||||
json_dir: Option<&Path>,
|
||||
suspended_now: &dyn Fn() -> bool,
|
||||
) -> (Option<String>, Option<VirtualThreadsNote>) {
|
||||
if version.is_none_or(|v| v.major < VIRTUAL_THREADS_MAJOR) {
|
||||
return (None, None);
|
||||
}
|
||||
if suspended || suspended_now() {
|
||||
return (None, Some(VirtualThreadsNote::WhileSuspended));
|
||||
}
|
||||
let Some(dir) = json_dir else {
|
||||
return (None, Some(VirtualThreadsNote::Failed));
|
||||
};
|
||||
match probe.thread_dump_json(pid, dir) {
|
||||
Ok(json) => (Some(json), None),
|
||||
Err(AttachError::TooLarge) => (None, Some(VirtualThreadsNote::TooLarge)),
|
||||
Err(e) => {
|
||||
tracing::warn!("JSON thread dump of JVM {pid}: {e}");
|
||||
(None, Some(VirtualThreadsNote::Failed))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn failure(probe: &dyn AttachProbe, pid: u32, error: AttachError) -> JvmThreadsResult {
|
||||
let reason = match error {
|
||||
AttachError::ListenerDidNotStart => JvmThreadsUnavailable::ListenerDidNotStart,
|
||||
|
||||
@@ -1977,20 +1977,27 @@ 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<JvmThreadsResult> {
|
||||
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn, and on JDK
|
||||
/// 21+ the JSON dump written into `json_dir`. 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, json_dir: Option<PathBuf>) -> IdeResult<JvmThreadsResult> {
|
||||
let session = self.session(s)?;
|
||||
jvm_memory::session_thread_dump(session).await
|
||||
jvm_memory::session_thread_dump(session, json_dir).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<IdeResult<JvmThreadsResult>> {
|
||||
/// it, under that session's turn and suspension, so a suspended JVM is not asked for the JSON
|
||||
/// dump either. `None` when no session debugs `pid`.
|
||||
pub async fn debugged_jvm_thread_dump(
|
||||
&self,
|
||||
run: RunId,
|
||||
pid: u32,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> Option<IdeResult<JvmThreadsResult>> {
|
||||
let session = self.jvm_session_of(run, pid)?;
|
||||
Some(jvm_memory::debugged_run_thread_dump(session, pid).await)
|
||||
Some(jvm_memory::debugged_run_thread_dump(session, pid, json_dir).await)
|
||||
}
|
||||
|
||||
/// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan
|
||||
|
||||
@@ -3096,7 +3096,7 @@ async fn a_run_dump_goes_through_the_session_attached_to_the_run() {
|
||||
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 dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid, None).await.unwrap().unwrap();
|
||||
let alive = jvm.try_wait().unwrap().is_none();
|
||||
let _ = jvm.kill();
|
||||
let _ = jvm.wait();
|
||||
@@ -3120,7 +3120,7 @@ async fn a_run_jvm_is_found_by_the_session_attached_to_it() {
|
||||
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());
|
||||
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243, None).await.is_none());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
||||
+93
-40
@@ -67,7 +67,7 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
|
||||
AND has_schema_privilege(nspname, 'USAGE') ORDER BY 1"
|
||||
}
|
||||
DbDriver::Mysql if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
|
||||
DbDriver::SqlServer if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
|
||||
DbDriver::SqlServer if system => "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA ORDER BY 1",
|
||||
DbDriver::Snowflake if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
|
||||
DbDriver::Snowflake => {
|
||||
"SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'INFORMATION_SCHEMA' ORDER BY 1"
|
||||
@@ -89,8 +89,8 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
|
||||
WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') ORDER BY 1"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
"SELECT schema_name FROM information_schema.schemata \
|
||||
WHERE schema_name NOT IN ('sys', 'information_schema', 'guest') ORDER BY 1"
|
||||
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA \
|
||||
WHERE SCHEMA_NAME NOT IN ('sys', 'INFORMATION_SCHEMA', 'guest') ORDER BY 1"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -133,8 +133,8 @@ pub fn tables(driver: DbDriver, schema: &str) -> String {
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
"SELECT TABLE_NAME, CASE WHEN TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
}
|
||||
@@ -177,14 +177,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
ORDER BY ordinal_position"
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT column_name, data_type, is_nullable, column_default, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM information_schema.table_constraints tc \
|
||||
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
|
||||
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = {s} \
|
||||
AND tc.table_name = {t} AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
|
||||
ORDER BY c.ordinal_position"
|
||||
"SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
|
||||
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME \
|
||||
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
|
||||
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = {s} \
|
||||
AND tc.TABLE_NAME = {t} AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END \
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c WHERE c.TABLE_SCHEMA = {s} AND c.TABLE_NAME = {t} \
|
||||
ORDER BY c.ORDINAL_POSITION"
|
||||
),
|
||||
DbDriver::Snowflake => format!(
|
||||
"SELECT column_name, {SNOWFLAKE_TYPE}, is_nullable, column_default, 0 \
|
||||
@@ -300,18 +300,18 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.data_type, c.is_nullable, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM information_schema.table_constraints tc \
|
||||
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
|
||||
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema NOT IN ('sys', 'information_schema') \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position"
|
||||
"SELECT c.TABLE_SCHEMA, c.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
|
||||
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME \
|
||||
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
|
||||
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA \
|
||||
AND tc.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
|
||||
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA') \
|
||||
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION"
|
||||
}
|
||||
DbDriver::Snowflake => {
|
||||
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
|
||||
@@ -372,11 +372,12 @@ pub fn foreign_keys(driver: DbDriver) -> &'static str {
|
||||
ORDER BY table_schema, table_name, constraint_name, ordinal_position LIMIT 20000"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
"SELECT table_schema, table_name, constraint_name, column_name, \
|
||||
referenced_table_schema, referenced_table_name, referenced_column_name \
|
||||
FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL \
|
||||
AND table_schema NOT IN ('sys', 'information_schema') \
|
||||
ORDER BY table_schema, table_name, constraint_name, ordinal_position"
|
||||
"SELECT OBJECT_SCHEMA_NAME(fk.parent_object_id), OBJECT_NAME(fk.parent_object_id), fk.name, pc.name, \
|
||||
OBJECT_SCHEMA_NAME(fk.referenced_object_id), OBJECT_NAME(fk.referenced_object_id), rc.name \
|
||||
FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id \
|
||||
JOIN sys.columns pc ON pc.object_id = fkc.parent_object_id AND pc.column_id = fkc.parent_column_id \
|
||||
JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id AND rc.column_id = fkc.referenced_column_id \
|
||||
WHERE fk.is_ms_shipped = 0 ORDER BY 1, 2, 3, fkc.constraint_column_id"
|
||||
}
|
||||
DbDriver::Oracle => {
|
||||
"SELECT con.owner, con.table_name, con.constraint_name, col.column_name, \
|
||||
@@ -410,7 +411,13 @@ pub fn table_foreign_keys(driver: DbDriver, schema: &str, table: &str) -> String
|
||||
"SELECT table_schema, table_name, constraint_name, column_name, referenced_table_schema, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND table_schema = {s} AND table_name = {t} ORDER BY constraint_name, ordinal_position"
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT table_schema, table_name, constraint_name, column_name, referenced_table_schema, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND table_schema = {s} AND table_name = {t} ORDER BY constraint_name, ordinal_position"
|
||||
"SELECT OBJECT_SCHEMA_NAME(fk.parent_object_id), OBJECT_NAME(fk.parent_object_id), fk.name, pc.name, \
|
||||
OBJECT_SCHEMA_NAME(fk.referenced_object_id), OBJECT_NAME(fk.referenced_object_id), rc.name \
|
||||
FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id \
|
||||
JOIN sys.columns pc ON pc.object_id = fkc.parent_object_id AND pc.column_id = fkc.parent_column_id \
|
||||
JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id AND rc.column_id = fkc.referenced_column_id \
|
||||
WHERE fk.parent_object_id = OBJECT_ID(N{}) ORDER BY 3, fkc.constraint_column_id",
|
||||
quote_literal(driver, &qualified(driver, schema, table))
|
||||
),
|
||||
DbDriver::Oracle => format!(
|
||||
"SELECT con.owner, con.table_name, con.constraint_name, col.column_name, rcon.owner, rcon.table_name, rcol.column_name FROM all_constraints con JOIN all_cons_columns col ON col.owner = con.owner AND col.table_name = con.table_name AND col.constraint_name = con.constraint_name JOIN all_constraints rcon ON rcon.owner = con.r_owner AND rcon.constraint_name = con.r_constraint_name JOIN all_cons_columns rcol ON rcol.owner = rcon.owner AND rcol.table_name = rcon.table_name AND rcol.constraint_name = rcon.constraint_name WHERE con.constraint_type = 'R' AND con.owner = {s} AND con.table_name = {t} ORDER BY con.constraint_name, col.position"
|
||||
@@ -712,8 +719,8 @@ pub fn routines(driver: DbDriver, schema: &str) -> Option<String> {
|
||||
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
|
||||
)),
|
||||
DbDriver::SqlServer => Some(format!(
|
||||
"SELECT r.routine_name, lower(r.routine_type), '', r.data_type \
|
||||
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
|
||||
"SELECT r.ROUTINE_NAME, lower(r.ROUTINE_TYPE), '', r.DATA_TYPE \
|
||||
FROM INFORMATION_SCHEMA.ROUTINES r WHERE r.ROUTINE_SCHEMA = {s} ORDER BY 1"
|
||||
)),
|
||||
DbDriver::Snowflake => Some(format!(
|
||||
"SELECT function_name, 'function', argument_signature, data_type FROM information_schema.functions \
|
||||
@@ -1019,19 +1026,65 @@ mod tests {
|
||||
assert_eq!(crate::conn::begin_statement(DbDriver::SqlServer), "BEGIN TRAN");
|
||||
assert_eq!(
|
||||
schemas(DbDriver::SqlServer, true),
|
||||
"SELECT schema_name FROM information_schema.schemata ORDER BY 1"
|
||||
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA ORDER BY 1"
|
||||
);
|
||||
assert!(schemas(DbDriver::SqlServer, false).contains("NOT IN ('sys', 'information_schema', 'guest')"));
|
||||
assert!(schemas(DbDriver::SqlServer, false).contains("NOT IN ('sys', 'INFORMATION_SCHEMA', 'guest')"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlserver_introspection_queries() {
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("information_schema.tables"));
|
||||
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("information_schema.columns"));
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("INFORMATION_SCHEMA.TABLES"));
|
||||
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("referenced_table_name IS NOT NULL"));
|
||||
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("table_schema = 'dbo'"));
|
||||
assert!(completion_columns(DbDriver::SqlServer).contains("information_schema.columns"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
|
||||
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("OBJECT_ID(N'[dbo].[t]')"));
|
||||
assert!(completion_columns(DbDriver::SqlServer).contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
}
|
||||
|
||||
/// Under a case-sensitive or binary collation, catalog names only resolve as declared:
|
||||
/// `INFORMATION_SCHEMA` views and their columns in upper case, `sys` views in lower case.
|
||||
#[test]
|
||||
fn sqlserver_catalog_names_keep_their_declared_case() {
|
||||
let d = DbDriver::SqlServer;
|
||||
let queries = [
|
||||
schemas(d, true).to_owned(),
|
||||
schemas(d, false).to_owned(),
|
||||
tables(d, "dbo"),
|
||||
columns(d, "dbo", "t"),
|
||||
indexes(d, "dbo", "t"),
|
||||
completion_columns(d).to_owned(),
|
||||
foreign_keys(d).to_owned(),
|
||||
table_foreign_keys(d, "dbo", "t"),
|
||||
routines(d, "dbo").unwrap(),
|
||||
];
|
||||
const COLUMNS: [&str; 15] = [
|
||||
"information_schema",
|
||||
"schema_name",
|
||||
"table_name",
|
||||
"table_schema",
|
||||
"table_type",
|
||||
"column_name",
|
||||
"data_type",
|
||||
"is_nullable",
|
||||
"column_default",
|
||||
"constraint_name",
|
||||
"constraint_type",
|
||||
"ordinal_position",
|
||||
"routine_name",
|
||||
"routine_type",
|
||||
"routine_schema",
|
||||
];
|
||||
for q in queries {
|
||||
let words: Vec<&str> = q.split(|c: char| !c.is_alphanumeric() && c != '_').collect();
|
||||
for (i, word) in words.iter().enumerate() {
|
||||
let catalog = COLUMNS.contains(&word.to_lowercase().as_str())
|
||||
|| i > 0 && words[i - 1] == "INFORMATION_SCHEMA" && !word.is_empty();
|
||||
if catalog {
|
||||
assert_eq!(*word, word.to_uppercase(), "{word} in {q}");
|
||||
}
|
||||
}
|
||||
assert!(!q.contains("referenced_table_name"), "SQL Server has no referenced_* columns: {q}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -136,3 +136,62 @@ async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
|
||||
assert!(!db.databases("s").await.unwrap().names.contains(&name));
|
||||
drop(held);
|
||||
}
|
||||
|
||||
/// #5772: a case-sensitive collation resolves catalog names only in their declared case.
|
||||
#[tokio::test]
|
||||
async fn sqlserver_introspection_works_under_a_case_sensitive_collation() {
|
||||
use ide_db::sql;
|
||||
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
|
||||
let parts = server.splitn(4, ':');
|
||||
let source = |database: &str| DataSource {
|
||||
driver: DbDriver::SqlServer,
|
||||
host: parts.clone().next().unwrap().into(),
|
||||
port: Some(parts.clone().nth(1).unwrap().parse().unwrap()),
|
||||
user: parts.clone().nth(2).unwrap().into(),
|
||||
database: database.into(),
|
||||
ssl: DbSslMode::Disable,
|
||||
..Default::default()
|
||||
};
|
||||
let password = parts.clone().nth(3);
|
||||
let name = format!("oi_cs_catalog_{}", std::process::id());
|
||||
let master = Pool::connect(&source("master"), password, None).await.unwrap();
|
||||
master.rows(&format!("CREATE DATABASE {name} COLLATE Latin1_General_CS_AS"), 1).await.unwrap();
|
||||
let pool = Pool::connect(&source(&name), password, None).await.unwrap();
|
||||
pool.rows("CREATE TABLE dbo.Parent (Id int PRIMARY KEY)", 1).await.unwrap();
|
||||
pool.rows("CREATE TABLE dbo.Child (Id int PRIMARY KEY, ParentId int CONSTRAINT FK_Child_Parent REFERENCES dbo.Parent (Id))", 1)
|
||||
.await
|
||||
.unwrap();
|
||||
pool.rows("CREATE VIEW dbo.Kids AS SELECT Id FROM dbo.Child", 1).await.unwrap();
|
||||
pool.rows("CREATE PROCEDURE dbo.Touch AS SELECT 1", 1).await.unwrap();
|
||||
let d = DbDriver::SqlServer;
|
||||
let cells = |rows: Vec<Vec<Option<String>>>| -> Vec<Vec<String>> {
|
||||
rows.into_iter().map(|r| r.into_iter().map(Option::unwrap_or_default).collect()).collect()
|
||||
};
|
||||
let schemas = cells(pool.rows(sql::schemas(d, false), 100).await.unwrap());
|
||||
assert!(schemas.contains(&vec!["dbo".to_owned()]));
|
||||
assert!(!schemas.iter().any(|s| s[0] == "INFORMATION_SCHEMA" || s[0] == "sys"));
|
||||
assert!(
|
||||
cells(pool.rows(sql::schemas(d, true), 100).await.unwrap()).contains(&vec!["INFORMATION_SCHEMA".to_owned()])
|
||||
);
|
||||
assert_eq!(
|
||||
cells(pool.rows(&sql::tables(d, "dbo"), 100).await.unwrap()),
|
||||
[["Child", "table"], ["Kids", "view"], ["Parent", "table"]]
|
||||
);
|
||||
assert_eq!(
|
||||
cells(pool.rows(&sql::columns(d, "dbo", "Child"), 100).await.unwrap())
|
||||
.iter()
|
||||
.map(|c| (c[0].as_str(), c[4].as_str()))
|
||||
.collect::<Vec<_>>(),
|
||||
[("Id", "1"), ("ParentId", "0")]
|
||||
);
|
||||
let fk = ["dbo", "Child", "FK_Child_Parent", "ParentId", "dbo", "Parent", "Id"];
|
||||
assert_eq!(cells(pool.rows(&sql::table_foreign_keys(d, "dbo", "Child"), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::foreign_keys(d), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::completion_columns(d), 100).await.unwrap()).len(), 4);
|
||||
assert_eq!(cells(pool.rows(&sql::routines(d, "dbo").unwrap(), 100).await.unwrap())[0][..2], ["Touch", "procedure"]);
|
||||
drop(pool);
|
||||
master
|
||||
.rows(&format!("ALTER DATABASE {name} SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE {name}"), 1)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
+174
-13
@@ -3,6 +3,7 @@
|
||||
//! The daemon speaks JSON-RPC over stdio, one bracketed message per line. After
|
||||
//! `daemon.connected` it is asked for `device.enable`, which makes it report `device.added` /
|
||||
//! `device.removed`, and once for `device.getDevices`, whose answer ends the "discovering" state.
|
||||
//! `emulator.getEmulators` lists what can be started, then and whenever the chooser opens.
|
||||
//!
|
||||
//! The daemon keeps running after its stdin closes, so closing the pipe does not end it: on Unix
|
||||
//! a watcher in its process group ends the group once the IDE is gone, even after a crash. A
|
||||
@@ -13,21 +14,25 @@ mod devtools;
|
||||
pub use devtools::DevToolsServer;
|
||||
|
||||
use ide_android::AndroidDevice;
|
||||
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList};
|
||||
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList, FlutterEmulator};
|
||||
use ide_core::process::{kill_tree, own_group, prepare, terminate_tree};
|
||||
use ide_core::tool_path::{find_command, search_path_in};
|
||||
use ide_core::{IdeEvent, SharedSink};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::collections::{BTreeMap, HashMap, VecDeque};
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
const ENABLE: u64 = 1;
|
||||
const GET_DEVICES: u64 = 2;
|
||||
const GET_EMULATORS: u64 = 3;
|
||||
/// `emulator.launch` waits for `xcrun simctl` or similar; past this the daemon is stuck.
|
||||
const LAUNCH_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
/// How long the daemon gets to exit on `SIGTERM`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(200);
|
||||
/// Lines of unrecognised output kept to explain a failure.
|
||||
@@ -39,6 +44,9 @@ enum Message {
|
||||
Added(FlutterDevice),
|
||||
Removed(String),
|
||||
Devices(Vec<FlutterDevice>),
|
||||
Emulators(Vec<FlutterEmulator>),
|
||||
/// The answer to a request of ours other than the ones above.
|
||||
Response(u64, Result<(), String>),
|
||||
Other,
|
||||
}
|
||||
|
||||
@@ -51,9 +59,15 @@ fn device(value: &Value) -> Option<FlutterDevice> {
|
||||
category: text("category"),
|
||||
emulator: value.get("emulator").and_then(Value::as_bool).unwrap_or(false),
|
||||
unavailable: None,
|
||||
emulator_id: text("emulatorId"),
|
||||
})
|
||||
}
|
||||
|
||||
fn emulator(value: &Value) -> Option<FlutterEmulator> {
|
||||
let text = |key| value.get(key).and_then(Value::as_str).map(str::to_owned);
|
||||
Some(FlutterEmulator { id: text("id")?, name: text("name")?, platform_type: text("platformType") })
|
||||
}
|
||||
|
||||
/// The messages of one stdout line; `None` for anything outside the protocol (the tool's own
|
||||
/// chatter, such as waiting for the startup lock).
|
||||
fn parse_line(line: &str) -> Option<Vec<Message>> {
|
||||
@@ -74,11 +88,23 @@ fn parse_message(message: &Value) -> Message {
|
||||
params.get("id").and_then(Value::as_str).map_or(Message::Other, |id| Message::Removed(id.to_owned()))
|
||||
}
|
||||
Some(_) => Message::Other,
|
||||
None if message.get("id").and_then(Value::as_u64) == Some(GET_DEVICES) => {
|
||||
let result = message.get("result").and_then(Value::as_array);
|
||||
Message::Devices(result.into_iter().flatten().filter_map(device).collect())
|
||||
None => {
|
||||
let result = message.get("result").and_then(Value::as_array).into_iter().flatten();
|
||||
match message.get("id").and_then(Value::as_u64) {
|
||||
Some(ENABLE) | None => Message::Other,
|
||||
Some(GET_DEVICES) => Message::Devices(result.filter_map(device).collect()),
|
||||
// A failure (no Android SDK, no Xcode) lists none.
|
||||
Some(GET_EMULATORS) => Message::Emulators(result.filter_map(emulator).collect()),
|
||||
Some(id) => Message::Response(
|
||||
id,
|
||||
match message.get("error") {
|
||||
None | Some(Value::Null) => Ok(()),
|
||||
Some(Value::String(error)) => Err(error.clone()),
|
||||
Some(error) => Err(error.to_string()),
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
None => Message::Other,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,6 +112,12 @@ fn request(id: u64, method: &str) -> String {
|
||||
format!("{}\n", json!([{ "id": id, "method": method }]))
|
||||
}
|
||||
|
||||
/// The emulators no device runs on.
|
||||
fn idle_emulators(emulators: &[FlutterEmulator], devices: &BTreeMap<String, FlutterDevice>) -> Vec<FlutterEmulator> {
|
||||
let running = |e: &FlutterEmulator| devices.values().any(|d| d.emulator_id.as_ref() == Some(&e.id));
|
||||
emulators.iter().filter(|e| !running(e)).cloned().collect()
|
||||
}
|
||||
|
||||
/// The daemon's devices, plus the Android devices adb sees that Flutter leaves out until they
|
||||
/// are usable. A daemon Android device's id is its adb serial.
|
||||
fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Vec<FlutterDevice> {
|
||||
@@ -97,6 +129,7 @@ fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Ve
|
||||
category: Some("mobile".into()),
|
||||
emulator: d.serial.starts_with("emulator-"),
|
||||
unavailable: Some(d.state.clone()),
|
||||
emulator_id: None,
|
||||
}));
|
||||
let rank = |d: &FlutterDevice| match d.category.as_deref() {
|
||||
Some("mobile") => 0,
|
||||
@@ -121,15 +154,30 @@ struct State {
|
||||
status: FlutterDaemonStatus,
|
||||
devices: BTreeMap<String, FlutterDevice>,
|
||||
adb: Vec<AndroidDevice>,
|
||||
emulators: Vec<FlutterEmulator>,
|
||||
/// Requests awaiting their answer; dropped with the daemon, which fails them.
|
||||
pending: HashMap<u64, mpsc::Sender<Result<(), String>>>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn list(&self) -> FlutterDeviceList {
|
||||
FlutterDeviceList { status: self.status.clone(), devices: merged(&self.devices, &self.adb) }
|
||||
FlutterDeviceList {
|
||||
status: self.status.clone(),
|
||||
devices: merged(&self.devices, &self.adb),
|
||||
emulators: idle_emulators(&self.emulators, &self.devices),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `requests` to the daemon; false without one.
|
||||
fn send(&mut self, requests: &str) -> bool {
|
||||
let Some(stdin) = self.running.as_mut().and_then(|r| r.stdin.as_mut()) else { return false };
|
||||
stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush()).is_ok()
|
||||
}
|
||||
|
||||
fn shut_down(&mut self) {
|
||||
self.generation += 1;
|
||||
self.pending.clear();
|
||||
if let Some(Running { mut child, stdin }) = self.running.take() {
|
||||
drop(stdin);
|
||||
// Off the caller's thread: closing a window must not wait for the grace period.
|
||||
@@ -181,12 +229,48 @@ impl FlutterDaemon {
|
||||
state.list()
|
||||
}
|
||||
|
||||
/// Reads adb again: a device awaiting authorization changes no daemon event.
|
||||
/// Reads adb again (a device awaiting authorization changes no daemon event) and asks the
|
||||
/// daemon for its emulators again (one may have been created since).
|
||||
pub fn refresh(&self) {
|
||||
let generation = self.0.state.lock().generation;
|
||||
let mut state = self.0.state.lock();
|
||||
if state.status == FlutterDaemonStatus::Ready {
|
||||
state.send(&request(GET_EMULATORS, "emulator.getEmulators"));
|
||||
}
|
||||
let generation = state.generation;
|
||||
drop(state);
|
||||
refresh_adb(&self.0, generation);
|
||||
}
|
||||
|
||||
/// Starts an emulator the list offers; it shows up as a device once booted. Blocks until the
|
||||
/// launch is under way. An AVD is started by `ide-android` rather than the daemon, which
|
||||
/// would make it a child of its process group and end it with the daemon.
|
||||
pub fn launch_emulator(&self, id: &str) -> Result<(), String> {
|
||||
let mut state = self.0.state.lock();
|
||||
let android = state.emulators.iter().any(|e| e.id == id && e.platform_type.as_deref() == Some("android"));
|
||||
if android {
|
||||
drop(state);
|
||||
return ide_android::launch_emulator(id).map_err(|e| e.message);
|
||||
}
|
||||
state.next_id = state.next_id.max(GET_EMULATORS) + 1;
|
||||
let request_id = state.next_id;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
state.pending.insert(request_id, tx);
|
||||
let params = json!({ "emulatorId": id });
|
||||
let line = format!("{}\n", json!([{ "id": request_id, "method": "emulator.launch", "params": params }]));
|
||||
if !state.send(&line) {
|
||||
state.pending.remove(&request_id);
|
||||
return Err("the Flutter daemon is not running".into());
|
||||
}
|
||||
drop(state);
|
||||
let answer = rx.recv_timeout(LAUNCH_TIMEOUT);
|
||||
self.0.state.lock().pending.remove(&request_id);
|
||||
match answer {
|
||||
Ok(result) => result,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => Err("the Flutter daemon did not answer".into()),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => Err("the Flutter daemon exited".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the daemon (project closed, or no longer trusted).
|
||||
pub fn stop(&self) {
|
||||
let mut state = self.0.state.lock();
|
||||
@@ -194,6 +278,7 @@ impl FlutterDaemon {
|
||||
state.status = FlutterDaemonStatus::Stopped;
|
||||
state.devices.clear();
|
||||
state.adb.clear();
|
||||
state.emulators.clear();
|
||||
}
|
||||
|
||||
/// Ends the daemon before returning, for a process about to exit.
|
||||
@@ -211,6 +296,7 @@ fn start(shared: &Arc<Shared>, state: &mut State) {
|
||||
state.status = FlutterDaemonStatus::Starting;
|
||||
state.devices.clear();
|
||||
state.adb.clear();
|
||||
state.emulators.clear();
|
||||
let (shared, generation) = (shared.clone(), state.generation);
|
||||
std::thread::spawn(move || run(&shared, generation));
|
||||
}
|
||||
@@ -265,6 +351,7 @@ fn finish(shared: &Shared, generation: u64, status: FlutterDaemonStatus) {
|
||||
return;
|
||||
}
|
||||
let running = state.running.take();
|
||||
state.pending.clear();
|
||||
state.status = status;
|
||||
let list = state.list();
|
||||
drop(state);
|
||||
@@ -358,12 +445,25 @@ fn handle(shared: &Arc<Shared>, generation: u64, message: Message) -> bool {
|
||||
match message {
|
||||
Message::Other => return true,
|
||||
Message::Connected => {
|
||||
if let Some(stdin) = state.running.as_mut().and_then(|r| r.stdin.as_mut()) {
|
||||
let requests = request(ENABLE, "device.enable") + &request(GET_DEVICES, "device.getDevices");
|
||||
let _ = stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush());
|
||||
state.send(
|
||||
&(request(ENABLE, "device.enable")
|
||||
+ &request(GET_DEVICES, "device.getDevices")
|
||||
+ &request(GET_EMULATORS, "emulator.getEmulators")),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
Message::Response(id, result) => {
|
||||
if let Some(tx) = state.pending.remove(&id) {
|
||||
let _ = tx.send(result);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
Message::Emulators(emulators) => {
|
||||
if state.emulators == emulators {
|
||||
return true;
|
||||
}
|
||||
state.emulators = emulators;
|
||||
}
|
||||
Message::Added(device) => {
|
||||
state.devices.insert(device.id.clone(), device);
|
||||
}
|
||||
@@ -395,6 +495,7 @@ mod tests {
|
||||
category: Some(category.into()),
|
||||
emulator,
|
||||
unavailable: None,
|
||||
emulator_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -433,6 +534,33 @@ mod tests {
|
||||
let Some([Message::Devices(devices)]) = answer.as_deref() else { panic!("{answer:?}") };
|
||||
assert_eq!((devices[0].id.as_str(), devices[0].category.as_deref()), ("chrome", None));
|
||||
assert_eq!(parse_line(r#"[{"id":1,"result":null}]"#), Some(vec![Message::Other]));
|
||||
let emulators = parse_line(
|
||||
r#"[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","category":"mobile","platformType":"ios"}]}]"#,
|
||||
);
|
||||
let Some([Message::Emulators(emulators)]) = emulators.as_deref() else { panic!("{emulators:?}") };
|
||||
assert_eq!(
|
||||
(emulators[0].id.as_str(), emulators[0].platform_type.as_deref()),
|
||||
("apple_ios_simulator", Some("ios"))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_line(r#"[{"id":3,"error":"Unable to find Android SDK","trace":""}]"#),
|
||||
Some(vec![Message::Emulators(vec![])])
|
||||
);
|
||||
assert_eq!(parse_line(r#"[{"id":7,"result":null}]"#), Some(vec![Message::Response(7, Ok(()))]));
|
||||
assert_eq!(
|
||||
parse_line(r#"[{"id":7,"error":"emulator 'x' not found","trace":"..."}]"#),
|
||||
Some(vec![Message::Response(7, Err("emulator 'x' not found".into()))])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offers_only_the_emulators_no_device_runs_on() {
|
||||
let emulator = |id: &str| FlutterEmulator { id: id.into(), name: id.into(), platform_type: None };
|
||||
let mut pixel = dev("emulator-5554", "Pixel", "mobile", true);
|
||||
pixel.emulator_id = Some("Pixel_9".into());
|
||||
let devices: BTreeMap<_, _> = [(pixel.id.clone(), pixel)].into_iter().collect();
|
||||
let idle = idle_emulators(&[emulator("Pixel_9"), emulator("apple_ios_simulator")], &devices);
|
||||
assert_eq!(idle, [emulator("apple_ios_simulator")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -498,8 +626,9 @@ mod tests {
|
||||
echo $$ > pid
|
||||
echo 'Waiting for another flutter command to release the startup lock...'
|
||||
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
|
||||
read enable; read get; echo "$enable$get" > requests
|
||||
read enable; read get; read emulators; echo "$enable$get$emulators" > requests
|
||||
echo '[{"id":1,"result":null}]'
|
||||
echo '[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","category":"mobile","platformType":"ios"}]}]'
|
||||
echo '[{"id":2,"result":[{"id":"macos","name":"macOS","category":"desktop","emulator":false}]}]'
|
||||
echo '[{"event":"device.added","params":{"id":"chrome","name":"Chrome","category":"web","emulator":false}}]'
|
||||
echo '[{"event":"device.removed","params":{"id":"macos","name":"macOS"}}]'
|
||||
@@ -518,6 +647,8 @@ cat > /dev/null
|
||||
});
|
||||
let requests = std::fs::read_to_string(dir.path().join("requests")).unwrap();
|
||||
assert!(requests.contains("device.enable") && requests.contains("device.getDevices"), "{requests}");
|
||||
assert!(requests.contains("emulator.getEmulators"), "{requests}");
|
||||
assert_eq!(daemon.devices().emulators[0].name, "iOS Simulator");
|
||||
assert!(lists.0.lock().iter().any(|l| l.devices.iter().any(|d| d.id == "macos")));
|
||||
|
||||
let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
|
||||
@@ -529,6 +660,36 @@ cat > /dev/null
|
||||
assert_eq!(daemon.0.state.lock().status, FlutterDaemonStatus::Stopped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launches_an_emulator_through_the_daemon_and_reports_its_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let script = r#"
|
||||
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
|
||||
read enable; read get; read emulators
|
||||
echo '[{"id":2,"result":[]}]'
|
||||
echo '[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","platformType":"ios"}]}]'
|
||||
read launch; echo "$launch" > launch
|
||||
echo '[{"id":4,"result":null}]'
|
||||
read launch
|
||||
echo '[{"id":5,"error":"Unable to run Simulator: xcrun not found","trace":""}]'
|
||||
cat > /dev/null
|
||||
"#;
|
||||
let (daemon, _lists) = daemon(dir.path(), script);
|
||||
daemon.devices();
|
||||
wait_for("the emulators", || !daemon.devices().emulators.is_empty());
|
||||
assert_eq!(daemon.launch_emulator("apple_ios_simulator"), Ok(()));
|
||||
let launch = std::fs::read_to_string(dir.path().join("launch")).unwrap();
|
||||
let launch: Value = serde_json::from_str(&launch).unwrap();
|
||||
assert_eq!(launch[0]["method"], "emulator.launch");
|
||||
assert_eq!(launch[0]["params"], json!({ "emulatorId": "apple_ios_simulator" }));
|
||||
assert_eq!(
|
||||
daemon.launch_emulator("apple_ios_simulator"),
|
||||
Err("Unable to run Simulator: xcrun not found".into())
|
||||
);
|
||||
daemon.stop();
|
||||
assert_eq!(daemon.launch_emulator("apple_ios_simulator"), Err("the Flutter daemon is not running".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_daemon_does_not_outlive_the_ide() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -515,6 +515,7 @@ async fn resolve_jvm_application(
|
||||
test == Some(true),
|
||||
policy,
|
||||
&cancel,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
use ide_lsp::jdtls::JavaBuildStatus;
|
||||
|
||||
@@ -360,10 +360,17 @@ pub async fn agent_fork(host: &Host, window: &str, task: String, turns: Option<u
|
||||
}
|
||||
|
||||
/// Drops the task's turns after its first `turns`; returns the message of the first dropped one.
|
||||
/// With `files`, the files those turns changed go back as they were before them.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_rollback(host: &Host, window: &str, task: String, turns: u32) -> IdeResult<Option<AgentPrompt>> {
|
||||
pub async fn agent_rollback(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
turns: u32,
|
||||
files: bool,
|
||||
) -> IdeResult<Option<AgentPrompt>> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.rollback(&task, turns).await
|
||||
host.project(window)?.agents.rollback(&task, turns, files).await
|
||||
}
|
||||
|
||||
/// Checks the selected installation without modifying it.
|
||||
|
||||
@@ -114,6 +114,12 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
extra["__adapterJavaHome"] = serde_json::json!(runtime.home);
|
||||
config.extra_json = Some(extra.to_string());
|
||||
}
|
||||
if finds_java_sources(&config)
|
||||
&& let Ok(project) = host.project(window)
|
||||
{
|
||||
let roots = host.blocking(move || Ok(java_source_roots(&project))).await?;
|
||||
config = add_java_source_paths(config, &roots);
|
||||
}
|
||||
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
|
||||
let mut ruby_tools = Vec::new();
|
||||
if config.adapter == "rdbg" && config.request == "launch" {
|
||||
@@ -308,6 +314,46 @@ fn start_java_attach_listener(mut config: LaunchConfig, windows: bool) -> Launch
|
||||
config
|
||||
}
|
||||
|
||||
/// The project's source and test roots, as the IDE detects them (no Maven / Gradle import needed).
|
||||
fn java_source_roots(project: &crate::project::Project) -> Vec<PathBuf> {
|
||||
use ide_workspace::roots::RootKind;
|
||||
project
|
||||
.roots()
|
||||
.roots
|
||||
.iter()
|
||||
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
|
||||
.map(|r| project.root.join(&r.path))
|
||||
.filter(|p| p.is_dir())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Debuggers that look a frame's source up in `sourcePaths` when their own model has no file:
|
||||
/// java-debug after jdtls (which has not imported a project whose Maven sync failed), and
|
||||
/// java-analyzer after the module it debugs (whose sibling modules it does not load).
|
||||
fn finds_java_sources(config: &LaunchConfig) -> bool {
|
||||
matches!(config.adapter.as_str(), "java-debug" | ide_dap::adapter::JAVA_ANALYZER)
|
||||
}
|
||||
|
||||
/// Without a file for the stopped frame the editor cannot follow the execution point, so Java
|
||||
/// sessions get every source root of the project. The user's own list wins.
|
||||
fn add_java_source_paths(mut config: LaunchConfig, roots: &[PathBuf]) -> LaunchConfig {
|
||||
if !finds_java_sources(&config) || roots.is_empty() {
|
||||
return config;
|
||||
}
|
||||
let mut extra = match config.extra_json.as_deref().map(serde_json::from_str) {
|
||||
None => serde_json::Map::new(),
|
||||
Some(Ok(serde_json::Value::Object(extra))) => extra,
|
||||
Some(_) => return config,
|
||||
};
|
||||
if extra.get("sourcePaths").is_some_and(|v| !v.is_null()) {
|
||||
return config;
|
||||
}
|
||||
let paths: Vec<String> = roots.iter().map(|r| r.to_string_lossy().into_owned()).collect();
|
||||
extra.insert("sourcePaths".into(), paths.into());
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
config
|
||||
}
|
||||
|
||||
/// A JVM launched by java-debug writes what java-debug decodes its output as
|
||||
/// (see [`ide_core::output_encoding::java_debug_vm_args`]).
|
||||
fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchConfig {
|
||||
@@ -671,11 +717,21 @@ pub async fn debug_jvm_memory_classes(
|
||||
host.debugger.jvm_memory_classes(session).await
|
||||
}
|
||||
|
||||
/// A `Thread.print -l` of the debuggee JVM, or why it cannot be taken.
|
||||
/// A `Thread.print -l` of the debuggee JVM (with the JSON dump on JDK 21+), or why it cannot be
|
||||
/// taken.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_jvm_thread_dump(host: &Host, window: &str, session: DebugSessionId) -> IdeResult<JvmThreadsResult> {
|
||||
host.require_trust(window)?;
|
||||
host.debugger.jvm_thread_dump(session).await
|
||||
let heap_root = host.heap.root().to_path_buf();
|
||||
let dir = host.blocking(move || Ok(super::thread_dump::json_dir(&heap_root))).await?;
|
||||
let result = host.debugger.jvm_thread_dump(session, dir.clone()).await;
|
||||
let _ = host
|
||||
.blocking(move || {
|
||||
super::thread_dump::discard_json_dir(dir);
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
result
|
||||
}
|
||||
|
||||
/// Up to `limit` live instances of the class in the stopped JVM.
|
||||
@@ -737,6 +793,34 @@ mod tests {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["vmArgs"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_debug_sessions_look_up_sources_in_project_roots() {
|
||||
let roots = [PathBuf::from("/p/src/main/java"), PathBuf::from("/p/src/test/java")];
|
||||
let source_paths = |config: &LaunchConfig| {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["sourcePaths"]
|
||||
.clone()
|
||||
};
|
||||
for adapter in ["java-debug", ide_dap::adapter::JAVA_ANALYZER] {
|
||||
for request in ["launch", "attach"] {
|
||||
let config = add_java_source_paths(launch(adapter, request, serde_json::json!({"port": 5005})), &roots);
|
||||
assert_eq!(source_paths(&config), serde_json::json!(["/p/src/main/java", "/p/src/test/java"]));
|
||||
}
|
||||
}
|
||||
let mut bare = launch("java-debug", "attach", serde_json::json!({}));
|
||||
bare.extra_json = None;
|
||||
assert_eq!(
|
||||
source_paths(&add_java_source_paths(bare, &roots)),
|
||||
serde_json::json!(["/p/src/main/java", "/p/src/test/java"])
|
||||
);
|
||||
|
||||
let own = launch("java-debug", "launch", serde_json::json!({"sourcePaths": ["/elsewhere"]}));
|
||||
assert_eq!(source_paths(&add_java_source_paths(own, &roots)), serde_json::json!(["/elsewhere"]));
|
||||
let other = launch("debugpy", "launch", serde_json::json!({}));
|
||||
assert_eq!(add_java_source_paths(other.clone(), &roots).extra_json, other.extra_json);
|
||||
let none = launch("java-debug", "launch", serde_json::json!({}));
|
||||
assert_eq!(add_java_source_paths(none.clone(), &[]).extra_json, none.extra_json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_debug_launches_on_windows_write_utf8() {
|
||||
let extra =
|
||||
|
||||
@@ -25,6 +25,16 @@ pub fn flutter_daemon_restart(host: &Host, window: &str) -> IdeResult<FlutterDev
|
||||
Ok(host.project(window)?.flutter.restart())
|
||||
}
|
||||
|
||||
/// Starts an emulator from [`FlutterDeviceList::emulators`]. Returns once the launch is under way: the device follows as `IdeEvent::FlutterDevices`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn flutter_emulator_launch(host: &Host, window: &str, id: String) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || project.flutter.launch_emulator(&id))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
.map_err(IdeError::unavailable)
|
||||
}
|
||||
|
||||
/// The address of the project's DevTools server, started on first use. A server that failed or
|
||||
/// exited is only started again by the next request.
|
||||
#[command(trust = trusted)]
|
||||
@@ -36,4 +46,5 @@ pub async fn flutter_devtools_url(host: &Host, window: &str) -> IdeResult<String
|
||||
.map_err(IdeError::unavailable)
|
||||
}
|
||||
|
||||
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_devtools_url);
|
||||
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_emulator_launch,
|
||||
flutter_devtools_url);
|
||||
@@ -4,9 +4,11 @@ pub(crate) mod cache;
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use super::Channel;
|
||||
use super::build::{load, with_profiles, workspace};
|
||||
use cache::LaunchEvents;
|
||||
use ide_build::BuildModel;
|
||||
use ide_build::compile;
|
||||
use ide_build::compile::{self, BuildEvent};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
@@ -18,6 +20,8 @@ use std::path::{Path, PathBuf};
|
||||
/// Builds according to `policy`, then resolves the runtime (or test)
|
||||
/// classpath and the JDK of the module at `module` (absolute, or relative to the project root).
|
||||
/// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
|
||||
/// The build streams its console, messages and progress on `on_event` while it runs; a launch
|
||||
/// whose build another launch's build joins receives that build's events.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_resolve_launch(
|
||||
host: &Host,
|
||||
@@ -26,12 +30,16 @@ pub async fn java_resolve_launch(
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
request: RequestId,
|
||||
on_event: Channel<BuildEvent>,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
// Resources a Gradle build filters or renames are processed by Gradle, replacing the language
|
||||
// server's plain copies.
|
||||
host.require_trust(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = resolve_launch(host, window, module, test, policy, &cancel).await;
|
||||
let events: LaunchEvents = std::sync::Arc::new(move |event| {
|
||||
let _ = on_event.send(event);
|
||||
});
|
||||
let result = resolve_launch(host, window, module, test, policy, &cancel, Some(events)).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
@@ -43,8 +51,15 @@ pub(crate) async fn resolve_launch(
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
cancel: &CancellationToken,
|
||||
events: Option<LaunchEvents>,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let progress = |message: &str| {
|
||||
if let Some(events) = &events {
|
||||
events(BuildEvent::Progress { message: message.to_owned(), fraction: None });
|
||||
}
|
||||
};
|
||||
progress("Resolving the module");
|
||||
let project = host.project(window)?;
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let scope = {
|
||||
@@ -54,11 +69,11 @@ pub(crate) async fn resolve_launch(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??
|
||||
};
|
||||
if !project.lsp.java_served_by_jdtls(&module) {
|
||||
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
|
||||
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await;
|
||||
}
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let launches = project.java_launches.for_cache(&scope.cache);
|
||||
let waiting = launches.waiting.add(module.clone(), test, policy);
|
||||
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
|
||||
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
|
||||
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
|
||||
let build = policy != BuildPolicy::NoBuild;
|
||||
@@ -90,6 +105,9 @@ pub(crate) async fn resolve_launch(
|
||||
};
|
||||
let mut external_build =
|
||||
if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
|
||||
if build && !delegated {
|
||||
progress("Compiling with the Java language server");
|
||||
}
|
||||
let mut info = project.lsp.java_launch(&module, test, build && !delegated, full, delegated, cancel).await?;
|
||||
if info.errors.iter().any(|e| processor_recreated_a_file(&e.message)) {
|
||||
if build && !delegated && is_maven {
|
||||
@@ -118,6 +136,11 @@ pub(crate) async fn resolve_launch(
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _external_build = external_build;
|
||||
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
|
||||
let on_event = |event: BuildEvent| {
|
||||
if let Some(events) = &events {
|
||||
events(event);
|
||||
}
|
||||
};
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
// Module outputs the launch runs from a snapshot of: the originals must not come back.
|
||||
let mut snapshotted = Vec::new();
|
||||
@@ -130,7 +153,7 @@ pub(crate) async fn resolve_launch(
|
||||
root,
|
||||
&model,
|
||||
&module,
|
||||
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
|
||||
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members, events: events.clone() },
|
||||
local_repo.clone(),
|
||||
&cancel,
|
||||
)?;
|
||||
@@ -140,7 +163,7 @@ pub(crate) async fn resolve_launch(
|
||||
snapshotted = outputs.originals;
|
||||
copies
|
||||
} else if external {
|
||||
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
|
||||
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel, &on_event)?;
|
||||
if let Some(failure) = built.failure {
|
||||
if policy != BuildPolicy::MakeAndContinueOnErrors {
|
||||
return Err(IdeError::internal(failure));
|
||||
@@ -154,6 +177,7 @@ pub(crate) async fn resolve_launch(
|
||||
};
|
||||
let mut class_paths: Vec<String> = built.iter().map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
if delegated {
|
||||
on_event(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
|
||||
// m2e runs inside jdtls on the server JDK and can resolve a different
|
||||
// Maven profile/classifier than the module build. Ask the same Maven
|
||||
// process that built the module for its runtime/test dependencies.
|
||||
@@ -203,6 +227,7 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
|
||||
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
|
||||
/// build tool compiles it, and the classpath comes from that server, else from Maven.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn resolve_launch_without_jdtls(
|
||||
host: &Host,
|
||||
project: &std::sync::Arc<crate::Project>,
|
||||
@@ -211,18 +236,24 @@ async fn resolve_launch_without_jdtls(
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
cancel: &CancellationToken,
|
||||
events: Option<LaunchEvents>,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, built) = {
|
||||
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
|
||||
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = load_launch_model(&scope);
|
||||
let on_event = |event: BuildEvent| {
|
||||
if let Some(events) = &events {
|
||||
events(event);
|
||||
}
|
||||
};
|
||||
let built = if policy == BuildPolicy::NoBuild {
|
||||
None
|
||||
} else {
|
||||
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
|
||||
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event))
|
||||
};
|
||||
(model, built)
|
||||
})
|
||||
@@ -254,6 +285,9 @@ async fn resolve_launch_without_jdtls(
|
||||
}
|
||||
}
|
||||
let build_ms = started.elapsed().as_millis();
|
||||
if let Some(events) = &events {
|
||||
events(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
|
||||
}
|
||||
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let cancel = cancel.clone();
|
||||
@@ -474,6 +508,7 @@ async fn build_members(
|
||||
members.push(cache::Member {
|
||||
module: launch.module.clone(),
|
||||
rebuild_on_jdt_errors: rebuild_on_jdt_errors(launch.policy, prefer_maven, errors),
|
||||
events: launch.events.clone(),
|
||||
});
|
||||
}
|
||||
Ok(members)
|
||||
@@ -646,6 +681,129 @@ pub async fn java_build_workspace(
|
||||
result
|
||||
}
|
||||
|
||||
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
/// classpath has one; from the engine's repository, else downloaded once from Maven Central), and,
|
||||
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_junit_runner(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
module: PathBuf,
|
||||
class_paths: Vec<String>,
|
||||
) -> IdeResult<JunitLaunch> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let scope = workspace::scope_for(&project, &module)?;
|
||||
let model = load_launch_model(&scope);
|
||||
let surefire = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.and_then(|maven| ide_build::surefire::surefire_config(&scope.root, &scope.cache, maven, &module))
|
||||
.unwrap_or_default();
|
||||
let runner = ide_sdk::java::junit_runner_jar(&data_dir)
|
||||
.ok_or_else(|| IdeError::internal("Cannot install the JUnit runner"))?;
|
||||
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
|
||||
ide_sdk::java::JunitLauncher::OnClasspath => None,
|
||||
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
|
||||
ide_sdk::java::JunitLauncher::NoPlatform => {
|
||||
return Err(IdeError::unavailable(
|
||||
"No JUnit Platform (junit-platform-engine) on the test classpath. To run these tests through \
|
||||
Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(junit_launch(&module, class_paths, surefire, [Some(runner), launcher].into_iter().flatten()))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// The test JVM of OpenIDEA's JUnit runner.
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JunitLaunch {
|
||||
pub class_paths: Vec<String>,
|
||||
/// Surefire's `argLine`, then its system properties as `-Dkey=value`.
|
||||
pub vm_args: Vec<String>,
|
||||
pub env: std::collections::BTreeMap<String, String>,
|
||||
pub working_directory: Option<String>,
|
||||
/// The Surefire settings that were applied (`argLine`, `systemPropertyVariables`…), for the console.
|
||||
pub surefire: Vec<String>,
|
||||
}
|
||||
|
||||
fn junit_launch(
|
||||
module: &Path,
|
||||
class_paths: Vec<String>,
|
||||
surefire: ide_build::surefire::SurefireConfig,
|
||||
runner: impl Iterator<Item = PathBuf>,
|
||||
) -> JunitLaunch {
|
||||
let mut applied = Vec::new();
|
||||
let mut note = |used: bool, name: &str| {
|
||||
if used {
|
||||
applied.push(name.to_owned());
|
||||
}
|
||||
};
|
||||
note(!surefire.arg_line.is_empty(), "argLine");
|
||||
note(!surefire.system_properties.is_empty(), "systemPropertyVariables");
|
||||
note(!surefire.environment.is_empty(), "environmentVariables");
|
||||
note(surefire.working_directory.is_some(), "workingDirectory");
|
||||
note(!surefire.additional_classpath.is_empty(), "additionalClasspathElements");
|
||||
note(!surefire.classpath_excludes.is_empty(), "classpathDependencyExcludes");
|
||||
// `group:artifact` in a Maven repository (`g/r/p/artifact/…`) or the Gradle cache (`g.r.p/artifact/…`).
|
||||
let excluded = |path: &str| {
|
||||
let path = path.replace('\\', "/");
|
||||
surefire.classpath_excludes.iter().any(|e| {
|
||||
e.split_once(':').is_some_and(|(group, artifact)| {
|
||||
path.contains(&format!("/{}/{artifact}/", group.replace('.', "/")))
|
||||
|| path.contains(&format!("/{group}/{artifact}/"))
|
||||
})
|
||||
})
|
||||
};
|
||||
let mut class_paths: Vec<String> = class_paths.into_iter().filter(|p| !excluded(p)).collect();
|
||||
class_paths.extend(surefire.additional_classpath);
|
||||
class_paths.extend(runner.map(|p| p.to_string_lossy().into_owned()));
|
||||
let mut vm_args = surefire.arg_line;
|
||||
vm_args.extend(surefire.system_properties.into_iter().map(|(k, v)| format!("-D{k}={v}")));
|
||||
JunitLaunch {
|
||||
class_paths,
|
||||
vm_args,
|
||||
env: surefire.environment,
|
||||
working_directory: surefire.working_directory.map(|d| module.join(d).to_string_lossy().into_owned()),
|
||||
surefire: applied,
|
||||
}
|
||||
}
|
||||
|
||||
fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf> {
|
||||
if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) {
|
||||
return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'")));
|
||||
}
|
||||
let name = format!("junit-platform-launcher-{version}.jar");
|
||||
let dest = data_dir.join("junit").join(&name);
|
||||
if dest.is_file() {
|
||||
return Ok(dest);
|
||||
}
|
||||
std::fs::create_dir_all(dest.parent().expect("has a parent"))?;
|
||||
let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}");
|
||||
let partial = dest.with_extension("jar.part");
|
||||
// ponytail: unverified like the Lombok download (Central publishes SHA-1 only); HTTPS from Central.
|
||||
let fetched = ide_tools::Http::new(&ide_core::tool_path::search_path())
|
||||
.map(ide_tools::Http::https_only)
|
||||
.and_then(|http| http.download(&url, &partial, None, &CancellationToken::new(), &|_| {}))
|
||||
.and_then(|()| Ok(std::fs::rename(&partial, &dest)?));
|
||||
fetched.map(|()| dest).map_err(|e| {
|
||||
IdeError::unavailable(format!(
|
||||
"Cannot download {name} from Maven Central ({}). Add org.junit.platform:junit-platform-launcher to the \
|
||||
test dependencies, or set Settings › Build Tools › Maven › Run tests using to Maven.",
|
||||
e.message
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// An annotation processor's error for writing a file this build already wrote (JDT's
|
||||
/// `IdeFilerImpl`: "Source file already created", javac's Filer: "Attempt to recreate a file").
|
||||
fn processor_recreated_a_file(message: &str) -> bool {
|
||||
@@ -663,6 +821,35 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn junit_launch_applies_the_surefire_configuration() {
|
||||
let surefire = ide_build::surefire::SurefireConfig {
|
||||
arg_line: vec!["-Xmx1g".into()],
|
||||
system_properties: [("openidea.fail".to_owned(), "true".to_owned())].into(),
|
||||
environment: [("TZ".to_owned(), "UTC".to_owned())].into(),
|
||||
working_directory: Some("work".into()),
|
||||
additional_classpath: vec!["/extra".into()],
|
||||
classpath_excludes: vec!["org.slf4j:slf4j-simple".into(), "com.acme:gone".into()],
|
||||
};
|
||||
let classpath = vec![
|
||||
"/m/target/test-classes".into(),
|
||||
"/m2/org/slf4j/slf4j-simple/2.0/slf4j-simple-2.0.jar".into(),
|
||||
"/gradle/files-2.1/com.acme/gone/1/abc/gone-1.jar".into(),
|
||||
"/m2/org/slf4j/slf4j-api/2.0/slf4j-api-2.0.jar".into(),
|
||||
];
|
||||
let launch = junit_launch(Path::new("/m"), classpath, surefire, [PathBuf::from("/runner.jar")].into_iter());
|
||||
assert_eq!(
|
||||
launch.class_paths,
|
||||
["/m/target/test-classes", "/m2/org/slf4j/slf4j-api/2.0/slf4j-api-2.0.jar", "/extra", "/runner.jar"]
|
||||
);
|
||||
assert_eq!(launch.vm_args, ["-Xmx1g", "-Dopenidea.fail=true"]);
|
||||
assert_eq!(launch.env["TZ"], "UTC");
|
||||
assert_eq!(launch.working_directory.as_deref(), Path::new("/m").join("work").to_str());
|
||||
assert_eq!(launch.surefire.len(), 6);
|
||||
let plain = junit_launch(Path::new("/m"), vec![], Default::default(), std::iter::empty());
|
||||
assert!(plain.surefire.is_empty() && plain.vm_args.is_empty() && plain.working_directory.is_none());
|
||||
}
|
||||
|
||||
fn fake_jdk(dir: &Path, version: Option<&str>) -> PathBuf {
|
||||
let bin = dir.join("bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
@@ -946,4 +1133,4 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_resolve_launch);
|
||||
ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_junit_runner, java_resolve_launch);
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Immutable Maven outputs retained in the project cache, including across close/reopen.
|
||||
use ide_build::compile::{self, LaunchFingerprint};
|
||||
use ide_build::compile::{self, BuildEvent, LaunchFingerprint};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use ide_run::BuildPolicy;
|
||||
use parking_lot::Mutex;
|
||||
@@ -131,6 +131,10 @@ pub(super) fn has_record(root: &Path, cache: &Path, module: &Path) -> bool {
|
||||
[false, true].into_iter().any(|test| record_path(root, cache, module, test).is_some_and(|record| record.is_file()))
|
||||
}
|
||||
|
||||
/// Where the build of a launch streams its console, messages and progress: the run
|
||||
/// console, the status bar and the Build tool window of the launch's request.
|
||||
pub(in crate::ops) type LaunchEvents = Arc<dyn Fn(BuildEvent) + Send + Sync>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct BuildOptions {
|
||||
pub test: bool,
|
||||
@@ -142,13 +146,15 @@ pub(super) struct BuildOptions {
|
||||
/// together, #3971): their modules join this Maven run, and their launches then reuse
|
||||
/// the snapshots recorded here instead of running Maven again.
|
||||
pub members: Vec<Member>,
|
||||
/// The launch's own events; members that join the build get them too.
|
||||
pub events: Option<LaunchEvents>,
|
||||
}
|
||||
|
||||
/// A launch module joining another launch's build; see [`BuildOptions::members`].
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Member {
|
||||
pub module: PathBuf,
|
||||
pub rebuild_on_jdt_errors: bool,
|
||||
pub events: Option<LaunchEvents>,
|
||||
}
|
||||
|
||||
/// Launches share a build only within the same workspace project's cache.
|
||||
@@ -180,11 +186,12 @@ impl Sessions {
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Waiting(Arc<Mutex<Vec<Arc<WaitingLaunch>>>>);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct WaitingLaunch {
|
||||
pub module: PathBuf,
|
||||
pub test: bool,
|
||||
pub policy: BuildPolicy,
|
||||
/// The launch's build events, for a build it joins.
|
||||
pub events: Option<LaunchEvents>,
|
||||
}
|
||||
|
||||
/// Leaves [`Waiting`] when dropped.
|
||||
@@ -194,8 +201,14 @@ pub(super) struct WaitingGuard {
|
||||
}
|
||||
|
||||
impl Waiting {
|
||||
pub(super) fn add(&self, module: PathBuf, test: bool, policy: BuildPolicy) -> WaitingGuard {
|
||||
let launch = Arc::new(WaitingLaunch { module, test, policy });
|
||||
pub(super) fn add(
|
||||
&self,
|
||||
module: PathBuf,
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
events: Option<LaunchEvents>,
|
||||
) -> WaitingGuard {
|
||||
let launch = Arc::new(WaitingLaunch { module, test, policy, events });
|
||||
self.0.lock().push(launch.clone());
|
||||
WaitingGuard { all: self.0.clone(), launch }
|
||||
}
|
||||
@@ -266,7 +279,7 @@ impl Session {
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Outputs> {
|
||||
self.initialize();
|
||||
let BuildOptions { test, policy, rebuild_on_jdt_errors, members } = options;
|
||||
let BuildOptions { test, policy, rebuild_on_jdt_errors, members, events } = options;
|
||||
let mut lead = match self.prepare(root, model, module, test, policy, &local_repo, cancel)? {
|
||||
Ok(outputs) => return Ok(outputs),
|
||||
Err(pending) => pending,
|
||||
@@ -284,11 +297,13 @@ impl Session {
|
||||
let policy = if rebuild_on_jdt_errors { BuildPolicy::Rebuild } else { policy };
|
||||
let mut joined = Vec::new();
|
||||
let mut rebuild = policy == BuildPolicy::Rebuild;
|
||||
let mut sinks: Vec<LaunchEvents> = events.into_iter().collect();
|
||||
for member in members {
|
||||
if let Err(pending) =
|
||||
self.prepare(root, model, &member.module, test, BuildPolicy::Make, &local_repo, cancel)?
|
||||
{
|
||||
rebuild |= member.rebuild_on_jdt_errors;
|
||||
sinks.extend(member.events);
|
||||
joined.push(pending);
|
||||
}
|
||||
}
|
||||
@@ -298,7 +313,13 @@ impl Session {
|
||||
tracing::info!(?modules, "Building the launch modules in one Maven run");
|
||||
}
|
||||
let kind = if rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let mut built = compile::build_for_launches(root, model, &modules, test, kind, cancel)?.into_iter();
|
||||
// Every launch waiting for this build follows it.
|
||||
let on_event = |event: BuildEvent| {
|
||||
for sink in &sinks {
|
||||
sink(event.clone());
|
||||
}
|
||||
};
|
||||
let mut built = compile::build_for_launches(root, model, &modules, test, kind, cancel, &on_event)?.into_iter();
|
||||
let lead_built = built.next().unwrap();
|
||||
for (pending, built) in joined.into_iter().zip(built) {
|
||||
match built.failure {
|
||||
@@ -648,10 +669,31 @@ mod tests {
|
||||
let mut session = Session::new(root.join("cache"));
|
||||
let (a, b) = (root.join("a"), root.join("b"));
|
||||
let with = |rebuild_on_jdt_errors: bool| BuildOptions {
|
||||
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors }],
|
||||
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors, events: None }],
|
||||
..Default::default()
|
||||
};
|
||||
let lead = session.build(root, &model, &a, with(false), None, &cancel).unwrap();
|
||||
// The lead's and the member's launches both follow the shared build.
|
||||
let seen = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = |name: &'static str| -> LaunchEvents {
|
||||
let seen = seen.clone();
|
||||
Arc::new(move |event| {
|
||||
if let BuildEvent::Step { command, .. } = event {
|
||||
seen.lock().push(format!("{name}: {command}"));
|
||||
}
|
||||
})
|
||||
};
|
||||
let options = BuildOptions {
|
||||
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors: false, events: Some(sink("b")) }],
|
||||
events: Some(sink("a")),
|
||||
..Default::default()
|
||||
};
|
||||
let lead = session.build(root, &model, &a, options, None, &cancel).unwrap();
|
||||
let seen = seen.lock().clone();
|
||||
assert_eq!(seen.len(), 2, "{seen:?}");
|
||||
assert!(
|
||||
seen[0].starts_with("a: ") && seen[1].starts_with("b: ") && seen[0].contains("-pl a,b -am"),
|
||||
"{seen:?}"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(lead.snapshot.join("0/Main.class")).unwrap(), "a");
|
||||
assert_eq!(fs::read_to_string(lead.snapshot.join("1/Main.class")).unwrap(), "lib");
|
||||
// b's own launch runs from the snapshot the shared build recorded for it.
|
||||
@@ -690,17 +732,17 @@ mod tests {
|
||||
let root = dir.path();
|
||||
let model = reactor_fixture(root);
|
||||
let waiting = Waiting::default();
|
||||
let lead = waiting.add(root.join("a"), false, BuildPolicy::Automatic);
|
||||
let lead = waiting.add(root.join("a"), false, BuildPolicy::Automatic, None);
|
||||
let _guards = [
|
||||
waiting.add(root.join("b"), false, BuildPolicy::Make),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::Automatic),
|
||||
waiting.add(root.join("b"), false, BuildPolicy::Automatic),
|
||||
waiting.add(root.join("a"), false, BuildPolicy::Automatic),
|
||||
waiting.add(root.join("lib"), true, BuildPolicy::Automatic),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::Rebuild),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::MakeAndContinueOnErrors),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::NoBuild),
|
||||
waiting.add(root.join("other"), false, BuildPolicy::Automatic),
|
||||
waiting.add(root.join("b"), false, BuildPolicy::Make, None),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::Automatic, None),
|
||||
waiting.add(root.join("b"), false, BuildPolicy::Automatic, None),
|
||||
waiting.add(root.join("a"), false, BuildPolicy::Automatic, None),
|
||||
waiting.add(root.join("lib"), true, BuildPolicy::Automatic, None),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::Rebuild, None),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::MakeAndContinueOnErrors, None),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::NoBuild, None),
|
||||
waiting.add(root.join("other"), false, BuildPolicy::Automatic, None),
|
||||
];
|
||||
let join = |prefer_maven| {
|
||||
super::super::joining_launches(
|
||||
|
||||
@@ -3,6 +3,7 @@ use ide_command::command;
|
||||
use ide_core::{IdeResult, RunId};
|
||||
use ide_dap::{JvmMemoryUnavailable, JvmThreadsResult, JvmThreadsUnavailable};
|
||||
use ide_jvm_attach::{ProcEntry, is_hotspot, process_table, select_run_jvm};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A `Thread.print -l` of the JVM a run started: the deepest HotSpot JVM of the run's process
|
||||
@@ -22,13 +23,43 @@ pub async fn run_jvm_thread_dump(
|
||||
Ok(pid) => pid,
|
||||
Err(refused) => return Ok(refused),
|
||||
};
|
||||
let heap_root = host.heap.root().to_path_buf();
|
||||
let dir = host.blocking(move || Ok(json_dir(&heap_root))).await?;
|
||||
// A debugger attached to this run or JVM (Debug of a build tool's run, Attach to Process)
|
||||
// may hold it suspended, which only its session knows.
|
||||
if let Some(dump) = host.debugger.debugged_jvm_thread_dump(id, pid).await {
|
||||
return dump;
|
||||
let result = match host.debugger.debugged_jvm_thread_dump(id, pid, dir.clone()).await {
|
||||
Some(dump) => dump,
|
||||
None => {
|
||||
let json = dir.clone();
|
||||
// The attach handshake blocks for seconds.
|
||||
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid, json.as_deref()))).await
|
||||
}
|
||||
};
|
||||
let _ = host
|
||||
.blocking(move || {
|
||||
discard_json_dir(dir);
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
result
|
||||
}
|
||||
|
||||
/// A fresh owner-only directory for the JVM's JSON dump under the heap snapshot root, whose
|
||||
/// stale-directory sweep also removes a file a JVM writes after its request timed out. `None`
|
||||
/// when it cannot be created: the dump then goes without virtual threads.
|
||||
pub(crate) fn json_dir(heap_root: &Path) -> Option<PathBuf> {
|
||||
ide_heap::create_snapshot_dir(heap_root)
|
||||
.inspect_err(|e| tracing::warn!("no directory for the JSON thread dump under {}: {e}", heap_root.display()))
|
||||
.ok()
|
||||
}
|
||||
|
||||
pub(crate) fn discard_json_dir(dir: Option<PathBuf>) {
|
||||
if let Some(dir) = dir
|
||||
&& let Err(e) = std::fs::remove_dir_all(&dir)
|
||||
&& e.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
tracing::warn!("could not delete thread dump directory {}: {e}", dir.display());
|
||||
}
|
||||
// The attach handshake blocks for seconds.
|
||||
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid))).await
|
||||
}
|
||||
|
||||
fn unavailable(reason: JvmThreadsUnavailable) -> JvmThreadsResult {
|
||||
@@ -100,6 +131,30 @@ mod tests {
|
||||
assert_eq!(run_jvm(false, Some(10), None, table, |pid| pid == 11), Ok(11));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn json_dir_is_private_and_removed_afterwards() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let heap_root = root.path().join("heap-snapshots");
|
||||
let dir = json_dir(&heap_root).expect("a directory");
|
||||
assert_eq!(dir.parent(), Some(heap_root.as_path()));
|
||||
assert_eq!(std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
// A file the JVM wrote after its request timed out goes with the directory.
|
||||
std::fs::write(dir.join("threads-1-2.json"), "{}").unwrap();
|
||||
discard_json_dir(Some(dir.clone()));
|
||||
assert!(!dir.exists());
|
||||
discard_json_dir(None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_dir_is_none_when_it_cannot_be_created() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let blocked = root.path().join("file");
|
||||
std::fs::write(&blocked, "").unwrap();
|
||||
assert_eq!(json_dir(&blocked), None);
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
#[test]
|
||||
fn unsupported_without_reading_the_process_table() {
|
||||
|
||||
@@ -136,6 +136,10 @@ pub trait PluginWorkspace: Send + Sync {
|
||||
fn apply_edits(&self, path: &Path, version: u64, edits: &[TextEdit], background: bool) -> Result<u64, HostError>;
|
||||
/// Code from the project may run (git hooks and config on fetch).
|
||||
fn trusted(&self, root: &Path) -> bool;
|
||||
/// Git roots with the same directory mappings as the VCS tool window.
|
||||
fn repositories(&self, _root: &Path) -> Result<ide_vcs::Repos, HostError> {
|
||||
Err(HostError::NotFound("no open project repositories".into()))
|
||||
}
|
||||
/// The git executable of the project at `root` (see [`crate::Project::git_executable`]).
|
||||
fn git_executable(&self, _root: &Path) -> Option<PathBuf> {
|
||||
None
|
||||
@@ -2394,8 +2398,40 @@ impl HostApi for PluginApi {
|
||||
|
||||
fn vcs_remotes(&self, root: &Path) -> Result<Vec<(String, String)>, HostError> {
|
||||
let Some(repo) = ide_vcs::Repo::discover(root).map_err(failed)? else { return Ok(Vec::new()) };
|
||||
let remotes = repo.remotes().map_err(failed)?;
|
||||
Ok(remotes.into_iter().map(|r| (r.name, without_credentials(&r.url))).collect())
|
||||
plugin_remotes(&repo)
|
||||
}
|
||||
|
||||
fn vcs_roots(&self, root: &Path) -> Result<Vec<String>, HostError> {
|
||||
let workspace = self.shared.workspace().ok_or(HostError::Cancelled)?;
|
||||
Ok(workspace
|
||||
.repositories(root)?
|
||||
.roots()
|
||||
.iter()
|
||||
.filter(|r| r.starts_with(root) || root.starts_with(r))
|
||||
.map(|r| to_ipc(r))
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn vcs_repository_at(&self, root: &Path, path: &str) -> Result<Option<ide_plugin::RepositoryInfo>, HostError> {
|
||||
let workspace = self.shared.workspace().ok_or(HostError::Cancelled)?;
|
||||
if !workspace.trusted(root) {
|
||||
return Err(HostError::Failed("the project is in Restricted Mode: git does not run there".into()));
|
||||
}
|
||||
let path = ide_plugin::resolve_in_root(root, path).map_err(HostError::Invalid)?;
|
||||
let repos = workspace.repositories(root)?;
|
||||
// A link to a nested worktree directory denotes that worktree, not its entry in the parent.
|
||||
let Some(repo) = repos.at_root(&path).or_else(|| repos.for_path(&path)) else { return Ok(None) };
|
||||
let relative = path.strip_prefix(repo.root()).map_err(failed)?;
|
||||
let info = repo.branch_info().map_err(failed)?;
|
||||
Ok(Some(ide_plugin::RepositoryInfo {
|
||||
root: to_ipc(repo.root()),
|
||||
relative_path: to_ipc(relative),
|
||||
branch: info.head,
|
||||
commit: info.head_commit,
|
||||
upstream: info.upstream,
|
||||
ahead: info.ahead,
|
||||
remotes: plugin_remotes(repo)?,
|
||||
}))
|
||||
}
|
||||
|
||||
fn vcs_fetch(&self, root: &Path, cancel: &CancellationToken) -> Result<(), HostError> {
|
||||
@@ -3730,6 +3766,13 @@ impl PluginWorkspace for HostWorkspace {
|
||||
HostWorkspace::project_covering(self, root).is_some_and(|p| p.is_trusted())
|
||||
}
|
||||
|
||||
fn repositories(&self, root: &Path) -> Result<ide_vcs::Repos, HostError> {
|
||||
Ok(self
|
||||
.project_covering(root)
|
||||
.ok_or_else(|| HostError::NotFound("the project is no longer open".into()))?
|
||||
.repos())
|
||||
}
|
||||
|
||||
fn git_executable(&self, root: &Path) -> Option<PathBuf> {
|
||||
HostWorkspace::project_covering(self, root)?.git_executable()
|
||||
}
|
||||
@@ -4694,6 +4737,10 @@ fn from_window<'a>(client: Option<&'a str>, what: &str) -> Result<&'a str, HostE
|
||||
client.ok_or_else(|| HostError::Invalid(format!("can only {what} from a command the user invoked")))
|
||||
}
|
||||
|
||||
fn plugin_remotes(repo: &ide_vcs::Repo) -> Result<Vec<(String, String)>, HostError> {
|
||||
Ok(repo.remotes().map_err(failed)?.into_iter().map(|r| (r.name, without_credentials(&r.url))).collect())
|
||||
}
|
||||
|
||||
/// `url` without the `user:password@` a remote may carry (`https://user:token@host/…`):
|
||||
/// `vcs.read` must not hand out credentials. scp-style `git@host:path` has no password.
|
||||
fn without_credentials(url: &str) -> String {
|
||||
|
||||
@@ -2361,8 +2361,11 @@ fn git_metadata_watch(root: &Path, sink: &SharedSink) -> Option<Arc<ide_vcs::Met
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Whether a VCS metadata path changed for a reason other than our own status run
|
||||
/// refreshing an index: the main repository's `.git/index` or a linked worktree's
|
||||
/// `.git/worktrees/<id>/index`.
|
||||
fn vcs_path_changed(path: &Path) -> bool {
|
||||
!path.ends_with(".git/index") || !ide_vcs::is_own_index_write(path)
|
||||
path.file_name().is_none_or(|n| n != "index") || !ide_vcs::is_own_index_write(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2446,6 +2449,40 @@ mod index_event_tests {
|
||||
std::fs::remove_file(&index).unwrap();
|
||||
assert!(vcs_path_changed(&index));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_write_in_a_linked_worktree_is_suppressed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let main = tmp.path().join("main");
|
||||
std::fs::create_dir(&main).unwrap();
|
||||
let git = |dir: &std::path::Path, args: &[&str]| {
|
||||
let output = std::process::Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
};
|
||||
git(&main, &["init", "-q"]);
|
||||
std::fs::write(main.join("file.txt"), "original\n").unwrap();
|
||||
git(&main, &["add", "file.txt"]);
|
||||
git(&main, &["commit", "-qm", "init"]);
|
||||
let linked = tmp.path().join("linked");
|
||||
git(&main, &["worktree", "add", "-q", linked.to_str().unwrap()]);
|
||||
std::fs::File::options()
|
||||
.write(true)
|
||||
.open(linked.join("file.txt"))
|
||||
.unwrap()
|
||||
.set_modified(std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1))
|
||||
.unwrap();
|
||||
let index = main.join(".git/worktrees/linked/index");
|
||||
let before = std::fs::read(&index).unwrap();
|
||||
ide_vcs::Repo::discover(&linked).unwrap().unwrap().status().unwrap();
|
||||
assert_ne!(before, std::fs::read(&index).unwrap(), "status must actually write the index");
|
||||
assert!(!vcs_path_changed(&index));
|
||||
assert!(vcs_path_changed(&main.join(".git/worktrees/linked/HEAD")));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
|
||||
@@ -81,6 +81,10 @@ impl TestWorkspace {
|
||||
}
|
||||
|
||||
impl PluginWorkspace for TestWorkspace {
|
||||
fn repositories(&self, root: &Path) -> Result<ide_vcs::Repos, HostError> {
|
||||
ide_vcs::Repos::discover(root, &|_| false).map_err(|e| HostError::Failed(e.message))
|
||||
}
|
||||
|
||||
fn run_configuration(&self, _client: &str, plugin: &str, id: &str) -> Result<ide_run::RunConfig, HostError> {
|
||||
if !(plugin == "execution" && matches!(id, "detected" | "dynamic") || plugin == "api14" && id == "tests") {
|
||||
return Err(HostError::NotFound(id.into()));
|
||||
@@ -3609,6 +3613,36 @@ fn commands_see_the_paths_they_were_run_on() {
|
||||
assert_eq!(f.run("jobs", "selection", None).unwrap().as_deref(), Some(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_reads_the_repository_owning_the_path() {
|
||||
let f = fixture(Limits::default());
|
||||
f.install(&sample("jobs"));
|
||||
let lookup = |path: Option<&str>| f.run("jobs", "repository-at", path);
|
||||
for name in ["alpha", "beta", "alpha/nested"] {
|
||||
let dir = f.project.join(name);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
git(&dir, &["init", "-b", "work"]);
|
||||
git(&dir, &["remote", "add", "origin", &format!("https://user:[email protected]/{name}.git")]);
|
||||
std::fs::write(dir.join("file.txt"), name).unwrap();
|
||||
}
|
||||
assert_eq!(lookup(None).unwrap().unwrap().lines().count(), 3);
|
||||
for (path, repo, relative) in [
|
||||
("alpha/file.txt", "alpha", "file.txt"),
|
||||
("beta/file.txt", "beta", "file.txt"),
|
||||
("alpha/nested/file.txt", "alpha/nested", "file.txt"),
|
||||
("alpha/nested", "alpha/nested", ""),
|
||||
] {
|
||||
let root = to_ipc(&f.project.join(repo));
|
||||
let expected = format!("{root}|{relative}|work|[(\"origin\", \"https://example.org/{repo}.git\")]");
|
||||
assert_eq!(lookup(Some(path)).unwrap().as_deref(), Some(expected.as_str()));
|
||||
}
|
||||
assert_eq!(lookup(Some(".")).unwrap(), None);
|
||||
assert!(lookup(Some("..")).unwrap_err().contains("outside"));
|
||||
f.host.set_capability("jobs", "vcs.read", false).unwrap();
|
||||
assert!(lookup(None).unwrap_err().contains("vcs.read"));
|
||||
assert!(lookup(Some("alpha/file.txt")).unwrap_err().contains("vcs.read"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vcs_remotes_clipboard_and_open_url() {
|
||||
let f = fixture(Limits::default());
|
||||
|
||||
@@ -85,9 +85,26 @@ done
|
||||
for (index, root) in roots.into_iter().enumerate() {
|
||||
let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") };
|
||||
let test = index != 0;
|
||||
let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next())
|
||||
.await
|
||||
.unwrap();
|
||||
let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
let channel = ops::Channel::new(move |event: ide_build::compile::BuildEvent| sink.lock().unwrap().push(event));
|
||||
let info =
|
||||
ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next(), channel)
|
||||
.await
|
||||
.unwrap();
|
||||
// The build streams its command and progress while it runs.
|
||||
use ide_build::compile::BuildEvent;
|
||||
let events = events.lock().unwrap();
|
||||
assert!(
|
||||
events.iter().any(|e| matches!(e, BuildEvent::Step { command, .. } if command.contains("-pl app -am"))),
|
||||
"{events:?}"
|
||||
);
|
||||
assert!(
|
||||
events
|
||||
.iter()
|
||||
.any(|e| matches!(e, BuildEvent::Progress { message, .. } if message == "Resolving the classpath")),
|
||||
"{events:?}"
|
||||
);
|
||||
let out = root.join("app/target").join(if test { "test-classes" } else { "classes" });
|
||||
let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" });
|
||||
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
|
||||
|
||||
@@ -18,11 +18,16 @@ const DUMP_BASE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// Only `-all` and a quoted path: any argument the DCmd rejects while the VM is suspended
|
||||
/// hangs the attach listener (17/21/25) until resume, and so does an unquoted path with a space.
|
||||
pub fn heap_dump_command(path: &Path) -> Result<String, AttachError> {
|
||||
let text = path.to_str().ok_or_else(|| AttachError::Protocol(format!("heap dump path {path:?} is not UTF-8")))?;
|
||||
Ok(format!("GC.heap_dump -all {}", quoted_path(path, "heap dump")?))
|
||||
}
|
||||
|
||||
/// `path` in double quotes, as a DCmd argument; `what` names the file in errors.
|
||||
pub(crate) fn quoted_path(path: &Path, what: &str) -> Result<String, AttachError> {
|
||||
let text = path.to_str().ok_or_else(|| AttachError::Protocol(format!("{what} path {path:?} is not UTF-8")))?;
|
||||
if text.contains(['"', '\0', '\n', '\r']) {
|
||||
return Err(AttachError::Protocol(format!("heap dump path {text:?} cannot be quoted for the JVM")));
|
||||
return Err(AttachError::Protocol(format!("{what} path {text:?} cannot be quoted for the JVM")));
|
||||
}
|
||||
Ok(format!("GC.heap_dump -all \"{text}\""))
|
||||
Ok(format!("\"{text}\""))
|
||||
}
|
||||
|
||||
/// The JVM answers result code 0 for IO failures too, so success is told apart by its text.
|
||||
|
||||
@@ -20,5 +20,6 @@ pub use listener::{LISTENER_START_TIMEOUT, ensure_listener, is_hotspot};
|
||||
pub use properties::{jdwp_port, parse_properties};
|
||||
pub use socket::{AttachError, MAX_OUTPUT, agent_properties, has_listener, jcmd, temp_dir};
|
||||
pub use threads::{
|
||||
ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm, thread_print,
|
||||
ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm,
|
||||
thread_dump_json, thread_print,
|
||||
};
|
||||
@@ -1,9 +1,12 @@
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::heap_dump::quoted_path;
|
||||
use crate::listener::is_hotspot;
|
||||
use crate::socket::{AttachError, jcmd};
|
||||
use crate::socket::{AttachError, MAX_OUTPUT, jcmd};
|
||||
|
||||
/// Default budget for `thread_print`; a dump of a healthy JVM takes milliseconds, so this only
|
||||
/// bounds a JVM stuck at a safepoint.
|
||||
@@ -30,6 +33,55 @@ pub fn thread_print(pid: u32, timeout: Duration) -> Result<String, AttachError>
|
||||
jcmd(pid, "Thread.print -l", timeout)
|
||||
}
|
||||
|
||||
/// `Thread.dump_to_file -format=json`, the only dump that lists virtual threads (JDK 21+). The
|
||||
/// JVM writes it into `dir`, an absolute directory; the file is read up to [`MAX_OUTPUT`] and
|
||||
/// deleted whatever the outcome. Never send it to a VM a debugger holds suspended: 21 and 25 hang
|
||||
/// the request, and every later attach request behind it, until the VM resumes.
|
||||
pub fn thread_dump_json(pid: u32, dir: &Path, timeout: Duration) -> Result<String, AttachError> {
|
||||
dump_json_with(pid, dir, MAX_OUTPUT, |command| jcmd(pid, command, timeout))
|
||||
}
|
||||
|
||||
fn dump_json_with(
|
||||
pid: u32,
|
||||
dir: &Path,
|
||||
max: usize,
|
||||
send: impl FnOnce(&str) -> Result<String, AttachError>,
|
||||
) -> Result<String, AttachError> {
|
||||
// The JVM resolves a relative path against its own working directory.
|
||||
if !dir.is_absolute() {
|
||||
return Err(AttachError::Protocol(format!("thread dump directory {dir:?} is not absolute")));
|
||||
}
|
||||
// JDK 21 has no `-overwrite` and writes nothing when the file exists.
|
||||
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |since| since.as_nanos());
|
||||
let path = dir.join(format!("threads-{pid}-{nanos}.json"));
|
||||
let command = format!("Thread.dump_to_file -format=json {}", quoted_path(&path, "thread dump")?);
|
||||
let _delete = DeleteOnDrop(&path);
|
||||
let reply = send(&command)?;
|
||||
read_capped(&path, max).map_err(|e| match e {
|
||||
AttachError::Io(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
AttachError::Protocol(format!("the JVM wrote no thread dump: {}", reply.trim()))
|
||||
}
|
||||
e => e,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_capped(path: &Path, max: usize) -> Result<String, AttachError> {
|
||||
let mut bytes = Vec::new();
|
||||
std::fs::File::open(path)?.take(max as u64 + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() > max {
|
||||
return Err(AttachError::TooLarge);
|
||||
}
|
||||
String::from_utf8(bytes).map_err(|_| AttachError::Protocol("the thread dump is not UTF-8".into()))
|
||||
}
|
||||
|
||||
struct DeleteOnDrop<'a>(&'a Path);
|
||||
|
||||
impl Drop for DeleteOnDrop<'_> {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ProcEntry {
|
||||
pub pid: u32,
|
||||
@@ -119,6 +171,7 @@ fn deepest_jvm_in_tree(table: &[ProcEntry], root: u32, is_hotspot: &dyn Fn(u32)
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn entry(pid: u32, ppid: u32, command: &str) -> ProcEntry {
|
||||
ProcEntry { pid, ppid, command: command.to_string() }
|
||||
@@ -239,6 +292,77 @@ mod tests {
|
||||
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(11));
|
||||
}
|
||||
|
||||
/// The path the fake JVM is asked to write, from `Thread.dump_to_file … "<path>"`.
|
||||
fn requested_path(command: &str) -> PathBuf {
|
||||
PathBuf::from(command.split('"').nth(1).expect("quoted path"))
|
||||
}
|
||||
|
||||
fn is_empty(dir: &Path) -> bool {
|
||||
std::fs::read_dir(dir).unwrap().next().is_none()
|
||||
}
|
||||
|
||||
/// `<tmp>/a b`: the space is what an unquoted path would break on.
|
||||
fn dir_with_space() -> (tempfile::TempDir, PathBuf) {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let dir = root.path().join("a b");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
(root, dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_dump_reads_the_file_and_deletes_it() {
|
||||
let (_root, dir) = dir_with_space();
|
||||
let mut sent = String::new();
|
||||
let json = dump_json_with(42, &dir, 1024, |command| {
|
||||
sent = command.to_owned();
|
||||
std::fs::write(requested_path(command), "{\"threadDump\":{}}").unwrap();
|
||||
Ok(format!("Created {}\n", requested_path(command).display()))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(json, "{\"threadDump\":{}}");
|
||||
let prefix = format!("Thread.dump_to_file -format=json \"{}/threads-42-", dir.display());
|
||||
assert!(sent.starts_with(&prefix) && sent.ends_with(".json\""), "{sent}");
|
||||
assert!(is_empty(&dir));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_dump_file_is_deleted_when_it_is_too_large() {
|
||||
let (_root, dir) = dir_with_space();
|
||||
let result = dump_json_with(42, &dir, 1024, |command| {
|
||||
std::fs::write(requested_path(command), vec![b' '; 1025]).unwrap();
|
||||
Ok(String::new())
|
||||
});
|
||||
assert!(matches!(result, Err(AttachError::TooLarge)), "{result:?}");
|
||||
assert!(is_empty(&dir));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_dump_file_is_deleted_when_the_request_fails() {
|
||||
let (_root, dir) = dir_with_space();
|
||||
let result = dump_json_with(42, &dir, 1024, |command| {
|
||||
// The JVM wrote the file but the reply came too late.
|
||||
std::fs::write(requested_path(command), "{}").unwrap();
|
||||
Err(AttachError::Timeout)
|
||||
});
|
||||
assert!(matches!(result, Err(AttachError::Timeout)), "{result:?}");
|
||||
assert!(is_empty(&dir));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_dump_without_a_file_reports_the_reply() {
|
||||
let (_root, dir) = dir_with_space();
|
||||
// JDK 21 answers result code 0 when it writes nothing.
|
||||
let result = dump_json_with(42, &dir, 1024, |_| Ok("/x.json exists, use -overwrite to overwrite\n".into()));
|
||||
let Err(AttachError::Protocol(message)) = result else { panic!("{result:?}") };
|
||||
assert!(message.contains("exists"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_dump_refuses_a_relative_directory() {
|
||||
let result = dump_json_with(42, Path::new("dumps"), 1024, |_| panic!("sent a relative path"));
|
||||
assert!(matches!(result, Err(AttachError::Protocol(_))), "{result:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_skips_gradle_workers_and_the_kotlin_daemon() {
|
||||
// `--no-daemon`: the build's helper JVMs sit beside the application in the run's tree.
|
||||
|
||||
@@ -11,7 +11,7 @@ use ide_jvm_attach::{
|
||||
AttachError, HeapDumpReply, LISTENER_START_TIMEOUT, THREAD_DUMP_TIMEOUT, agent_properties, ensure_listener,
|
||||
find_jvm_by_jdwp_port, has_listener, heap_dump, heap_dump_command, histogram_safe_while_suspended, is_hotspot,
|
||||
java_version_of, jcmd, jdwp_port, parse_class_histogram, parse_heap_dump_reply, parse_release, process_table,
|
||||
select_run_jvm, temp_dir, thread_print, vm_flags,
|
||||
select_run_jvm, temp_dir, thread_dump_json, thread_print, vm_flags,
|
||||
};
|
||||
|
||||
/// Two threads that each hold one monitor and wait for the other's after 200 ms.
|
||||
@@ -33,6 +33,25 @@ public class Deadlock {
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Two virtual threads in a monitor deadlock, which `Thread.print` does not list.
|
||||
const VIRTUAL_DEADLOCK_JAVA: &str = r#"
|
||||
public class VirtualDeadlock {
|
||||
static final Object A = new Object(), B = new Object();
|
||||
|
||||
static void sleep(long ms) {
|
||||
try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); }
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Thread.ofVirtual().name("v-sync-1").start(() -> { synchronized (A) { sleep(200); synchronized (B) { } } });
|
||||
Thread.ofVirtual().name("v-sync-2").start(() -> { synchronized (B) { sleep(200); synchronized (A) { } } });
|
||||
System.out.println("READY");
|
||||
System.out.flush();
|
||||
sleep(60_000);
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
const MAIN_JAVA: &str = r#"
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -386,3 +405,33 @@ fn thread_print_reports_a_deadlock() {
|
||||
assert!(table.iter().any(|entry| entry.pid == pid && entry.command.contains("Deadlock")));
|
||||
assert_eq!(select_run_jvm(&table, pid, None, is_hotspot), Some(pid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs a real JDK >= 21: set OPENIDEA_TEST_JAVA to its bin/java"]
|
||||
fn thread_dump_json_lists_virtual_threads() {
|
||||
let Some(java) = std::env::var_os("OPENIDEA_TEST_JAVA").map(PathBuf::from) else {
|
||||
eprintln!("OPENIDEA_TEST_JAVA is not set; skipping");
|
||||
return;
|
||||
};
|
||||
let major = reported_major(&java);
|
||||
if major < 21 {
|
||||
eprintln!("JDK {major} has no virtual threads; skipping");
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut guard =
|
||||
launch_class(&java, dir.path(), "VirtualDeadlock", VIRTUAL_DEADLOCK_JAVA, &["-XX:+StartAttachListener"]);
|
||||
let pid = guard.0.id();
|
||||
wait_for_ready(&output_lines(&mut guard.0));
|
||||
wait_for_listener(pid);
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
|
||||
let dumps = dir.path().join("a b");
|
||||
std::fs::create_dir(&dumps).unwrap();
|
||||
let started = Instant::now();
|
||||
let json = thread_dump_json(pid, &dumps, THREAD_DUMP_TIMEOUT).unwrap();
|
||||
eprintln!("JDK {major} JSON thread dump: {} bytes in {:?}", json.len(), started.elapsed());
|
||||
assert!(json.contains("\"threadContainers\""), "{json}");
|
||||
assert!(json.contains("\"v-sync-1\"") && json.contains("\"v-sync-2\""), "{json}");
|
||||
assert!(std::fs::read_dir(&dumps).unwrap().next().is_none(), "dump file left in {dumps:?}");
|
||||
}
|
||||
@@ -358,6 +358,7 @@ pub enum FoldKind {
|
||||
Region,
|
||||
Comment,
|
||||
Imports,
|
||||
Compact,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -144,7 +144,11 @@ pub(super) fn folding(
|
||||
if !node.is_named() {
|
||||
return true;
|
||||
}
|
||||
if let Some(close_row) = kinds.bracket_close_row(&node) {
|
||||
if spec.name == "go"
|
||||
&& let Some(end) = go_compact_end(&node, text)
|
||||
{
|
||||
push(&mut out, start, end, FoldKind::Compact);
|
||||
} else if let Some(close_row) = kinds.bracket_close_row(&node) {
|
||||
push(&mut out, start, close_row, FoldKind::Region);
|
||||
} else if kinds.has(&node, FOLD_NODE) {
|
||||
push(&mut out, start, last_content_row(&node, text), FoldKind::Region);
|
||||
@@ -157,6 +161,71 @@ pub(super) fn folding(
|
||||
out
|
||||
}
|
||||
|
||||
// Only join a single statement on the next line. Comments, blank lines and
|
||||
// nested multi-line statements must keep their own lines.
|
||||
fn go_compact_end(node: &Node, text: &str) -> Option<usize> {
|
||||
let start = node.start_position().row;
|
||||
let braced = match node.kind() {
|
||||
"block" => {
|
||||
let parent = node.parent()?;
|
||||
if parent.kind() != "if_statement"
|
||||
|| parent.child_by_field_name("consequence") != Some(*node)
|
||||
|| !go_error_guard(parent.child_by_field_name("condition")?, text)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
true
|
||||
}
|
||||
"expression_case" | "type_case" | "communication_case" | "default_case" => false,
|
||||
_ => return None,
|
||||
};
|
||||
let body = node.named_child(node.named_child_count().checked_sub(1)?)?;
|
||||
if body.kind() != "statement_list" || body.named_child_count() != 1 {
|
||||
return None;
|
||||
}
|
||||
let header_end = body.prev_sibling()?;
|
||||
if header_end.kind() != if braced { "{" } else { ":" } || header_end.end_position().row != start {
|
||||
return None;
|
||||
}
|
||||
let statement = body.named_child(0)?;
|
||||
let position = statement.start_position();
|
||||
if statement.has_error()
|
||||
|| statement.is_extra()
|
||||
|| position.row != start + 1
|
||||
|| statement.end_position().row != position.row
|
||||
|| !own_line(text, statement.start_byte(), position.column)
|
||||
|| !text.get(header_end.end_byte()..statement.start_byte())?.trim().is_empty()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let tail = text.get(statement.end_byte()..)?.split('\n').next()?.trim();
|
||||
if !matches!(tail, "" | ";") {
|
||||
return None;
|
||||
}
|
||||
let end = start + if braced { 2 } else { 1 };
|
||||
(!braced || node.end_position().row == end).then_some(end)
|
||||
}
|
||||
|
||||
// Folding runs without Go type information. Recognize conventional error
|
||||
// guards and leave other nil checks alone.
|
||||
fn go_error_guard(condition: Node, text: &str) -> bool {
|
||||
if condition.kind() != "binary_expression"
|
||||
|| !condition.child_by_field_name("operator").is_some_and(|op| op.kind() == "!=")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let (Some(left), Some(right)) = (condition.child_by_field_name("left"), condition.child_by_field_name("right"))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let name = match (left.kind(), right.kind()) {
|
||||
("identifier", "nil") => left,
|
||||
("nil", "identifier") => right,
|
||||
_ => return false,
|
||||
};
|
||||
name.utf8_text(text.as_bytes()).is_ok_and(|name| name == "err" || name.ends_with("Err"))
|
||||
}
|
||||
|
||||
fn push(out: &mut Vec<FoldRange>, start: usize, end: usize, kind: FoldKind) {
|
||||
if end > start {
|
||||
out.push(FoldRange { start_line: start as u32, end_line: end as u32, kind });
|
||||
|
||||
@@ -1206,6 +1206,56 @@ fn folding_go_imports_and_ruby_ends() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_compact_folds_keep_only_single_line_statements_inline() {
|
||||
let src = r#"package main
|
||||
|
||||
func f() {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
return err // keep the comment on its own line
|
||||
}
|
||||
switch mode {
|
||||
case "compact":
|
||||
run()
|
||||
case "multi":
|
||||
run()
|
||||
stop()
|
||||
default:
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf(
|
||||
"keep both lines")
|
||||
}
|
||||
}
|
||||
"#;
|
||||
let found = folds("go", src);
|
||||
let compact: Vec<_> = found.iter().copied().filter(|r| r.2 == FoldKind::Compact).collect();
|
||||
assert_eq!(compact, [(3, 5, FoldKind::Compact), (10, 11, FoldKind::Compact), (15, 16, FoldKind::Compact)]);
|
||||
assert!(found.contains(&(6, 8, FoldKind::Region)));
|
||||
assert!(found.contains(&(18, 21, FoldKind::Region)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_compact_if_folds_are_limited_to_conventional_error_guards() {
|
||||
for (guard, kind) in [
|
||||
("err != nil", FoldKind::Compact),
|
||||
("nil != err", FoldKind::Compact),
|
||||
("parseErr := parse(); parseErr != nil", FoldKind::Compact),
|
||||
("cfg != nil", FoldKind::Region),
|
||||
("err == nil", FoldKind::Region),
|
||||
("invalid", FoldKind::Region),
|
||||
] {
|
||||
let source = format!(
|
||||
"package main\nfunc f() error {{\n if {guard} {{\n return err\n }}\n return nil\n}}\n"
|
||||
);
|
||||
assert!(folds("go", &source).contains(&(2, 4, kind)), "unexpected fold for {guard}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_swift_control_flow_and_haskell_binds() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! The Dart analysis server's closing labels (`dart/textDocument/publishClosingLabels`): the
|
||||
//! widget or call a closing `)` / `]` ends, shown after it at the end of the line (`// Column`).
|
||||
|
||||
use crate::convert::Conv;
|
||||
use crate::text::{DocText, Encoding, col_to_byte, units};
|
||||
use crate::types::{InlayHint, InlayKind};
|
||||
use ide_core::Pos;
|
||||
use lsp_types as lsp;
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
#[cfg(test)]
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct Params {
|
||||
pub uri: String,
|
||||
pub labels: Vec<Label>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub(crate) struct Label {
|
||||
range: lsp::Range,
|
||||
label: String,
|
||||
}
|
||||
|
||||
/// One end-of-line hint per line, as the Flutter plugin shows them: `// Padding // Center` when
|
||||
/// several constructs close on one line. A label whose range no longer ends in `)` or `]` (the
|
||||
/// text changed since the analysis) is left out.
|
||||
pub(crate) fn hints(conv: &Conv, path: &Path, text: &DocText, labels: Vec<Label>) -> Vec<InlayHint> {
|
||||
let mut lines: BTreeMap<u32, Vec<String>> = BTreeMap::new();
|
||||
for l in labels {
|
||||
let end = conv.pos(path, l.range.end);
|
||||
let line = text.line(end.line as usize);
|
||||
let before = &line[..col_to_byte(line, end.col as usize, Encoding::Utf16)];
|
||||
if before.ends_with([')', ']']) {
|
||||
lines.entry(end.line).or_default().push(l.label);
|
||||
}
|
||||
}
|
||||
lines
|
||||
.into_iter()
|
||||
.map(|(line, labels)| InlayHint {
|
||||
position: Pos::new(line, units(text.line(line as usize), Encoding::Utf16) as u32),
|
||||
label: format!("// {}", labels.join(" // ")),
|
||||
kind: InlayKind::ClosingLabel,
|
||||
padding_left: true,
|
||||
padding_right: false,
|
||||
tooltip: None,
|
||||
parts: Vec::new(),
|
||||
text_edits: Vec::new(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn labels(v: serde_json::Value) -> Vec<Label> {
|
||||
serde_json::from_value(v).unwrap()
|
||||
}
|
||||
|
||||
fn label(line: u32, from: u32, to: u32, label: &str) -> serde_json::Value {
|
||||
json!({ "label": label, "range": { "start": { "line": line, "character": from }, "end": { "line": line, "character": to } } })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_go_to_the_end_of_the_line_and_share_it() {
|
||||
let text = DocText::new("return Center(\n child: Padding(\n child: Text('a'))), // x\n");
|
||||
let conv = Conv::new(Encoding::Utf16, |_: &Path| None::<Arc<DocText>>);
|
||||
let hints = hints(
|
||||
&conv,
|
||||
Path::new("/a.dart"),
|
||||
&text,
|
||||
labels(json!([label(2, 4, 21, "Padding"), label(2, 4, 22, "Center"), label(2, 11, 20, "Text")])),
|
||||
);
|
||||
assert_eq!(hints.len(), 1);
|
||||
assert_eq!(hints[0].label, "// Padding // Center // Text");
|
||||
assert_eq!(hints[0].position, Pos::new(2, 28));
|
||||
assert_eq!(hints[0].kind, InlayKind::ClosingLabel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_label_that_no_longer_ends_at_a_bracket_is_dropped() {
|
||||
let text = DocText::new("Column(children: [])\nRow(\n");
|
||||
let conv = Conv::new(Encoding::Utf16, |_: &Path| None::<Arc<DocText>>);
|
||||
let hints = hints(
|
||||
&conv,
|
||||
Path::new("/a.dart"),
|
||||
&text,
|
||||
labels(json!([label(0, 0, 19, "<Widget>[]"), label(1, 0, 3, "Row")])),
|
||||
);
|
||||
assert_eq!(hints.iter().map(|h| h.label.as_str()).collect::<Vec<_>>(), ["// <Widget>[]"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf8_servers_and_wide_characters_give_utf16_columns() {
|
||||
let text = Arc::new(DocText::new("Text('🙂')\n"));
|
||||
let doc = text.clone();
|
||||
let conv = Conv::new(Encoding::Utf8, move |_: &Path| Some(doc.clone()));
|
||||
let hints = hints(&conv, Path::new("/a.dart"), &text, labels(json!([label(0, 0, 12, "Text")])));
|
||||
assert_eq!(hints[0].position, Pos::new(0, 10));
|
||||
}
|
||||
}
|
||||
@@ -414,6 +414,23 @@ impl ClientHandler {
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_closing_labels(&self, mgr: &LspManager, params: Value) {
|
||||
let params: crate::closing_labels::Params = match serde_json::from_value(params) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
tracing::debug!("{}: bad publishClosingLabels: {e}", self.server.name);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let Some(path) = uri_to_path(¶ms.uri) else { return };
|
||||
if !self.server.is_live(self.generation) {
|
||||
return;
|
||||
}
|
||||
if mgr.set_closing_labels(&path, &self.server, self.generation, self.encoding(), params.labels) {
|
||||
mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::InlayHints });
|
||||
}
|
||||
}
|
||||
|
||||
/// Once per unresolved plugin, whether m2e marked a `pom.xml` or only logged it.
|
||||
fn build_plan_failure(&self, mgr: &LspManager, (plugin, body): (String, String)) {
|
||||
if mgr.first_message(&self.server.name, &format!("build plan: {plugin}")) {
|
||||
@@ -622,6 +639,7 @@ impl Handler for ClientHandler {
|
||||
}
|
||||
"textDocument/publishDiagnostics" => self.publish_diagnostics(&mgr, params),
|
||||
"dart/textDocument/publishFlutterOutline" => self.publish_flutter_outline(&mgr, params),
|
||||
"dart/textDocument/publishClosingLabels" => self.publish_closing_labels(&mgr, params),
|
||||
"window/showMessage" => self.show_message(&mgr, ¶ms),
|
||||
"window/logMessage" => {
|
||||
let text = params.get("message").and_then(Value::as_str).unwrap_or_default();
|
||||
|
||||
@@ -10,6 +10,7 @@ mod angular;
|
||||
mod arduino;
|
||||
mod caps;
|
||||
mod clang_tidy;
|
||||
mod closing_labels;
|
||||
mod compose;
|
||||
mod convert;
|
||||
mod external_project;
|
||||
@@ -150,6 +151,14 @@ struct DocState {
|
||||
/// When the servers last got new text (open or change): diagnostics published before are stale.
|
||||
changed: std::time::Instant,
|
||||
flutter_outline: Option<FlutterOutline>,
|
||||
/// The Dart server's closing labels for the current text; dropped on the next change.
|
||||
closing_labels: Option<ClosingLabels>,
|
||||
}
|
||||
|
||||
struct ClosingLabels {
|
||||
server: ide_core::ServerId,
|
||||
generation: u64,
|
||||
hints: Vec<InlayHint>,
|
||||
}
|
||||
|
||||
/// The widget tree last published for a document, valid while that server instance runs.
|
||||
@@ -1303,6 +1312,7 @@ impl LspManager {
|
||||
notebook: None,
|
||||
changed: std::time::Instant::now(),
|
||||
flutter_outline: None,
|
||||
closing_labels: None,
|
||||
};
|
||||
let compose_added = {
|
||||
let mut docs = self.docs.lock();
|
||||
@@ -1351,6 +1361,7 @@ impl LspManager {
|
||||
let Some(d) = docs.get_mut(&doc) else { return };
|
||||
d.version = version as i32;
|
||||
d.changed = std::time::Instant::now();
|
||||
d.closing_labels = None;
|
||||
|
||||
// Servers that have this document open on their current instance.
|
||||
let targets: Vec<(Arc<Server>, Running, SyncKind, Encoding)> = d
|
||||
@@ -2453,6 +2464,37 @@ impl LspManager {
|
||||
changed
|
||||
}
|
||||
|
||||
/// Records published closing labels; whether what the open documents of `path` show changed.
|
||||
fn set_closing_labels(
|
||||
&self,
|
||||
path: &Path,
|
||||
server: &Server,
|
||||
generation: u64,
|
||||
enc: Encoding,
|
||||
labels: Vec<closing_labels::Label>,
|
||||
) -> bool {
|
||||
let mut changed = false;
|
||||
for d in self.docs.lock().values_mut().filter(|d| d.path == path && d.notebook.is_none()) {
|
||||
// Not `self.conv`: it would lock `docs` again for a UTF-8 server's text.
|
||||
let text = d.text.clone();
|
||||
let conv = Conv::new(enc, move |_: &Path| Some(text.clone()));
|
||||
let hints = closing_labels::hints(&conv, path, &d.text, labels.clone());
|
||||
changed |= !hints.is_empty() || d.closing_labels.as_ref().is_some_and(|c| !c.hints.is_empty());
|
||||
d.closing_labels = Some(ClosingLabels { server: server.id, generation, hints });
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn closing_label_hints(&self, doc: DocId, range: Range) -> Vec<InlayHint> {
|
||||
let docs = self.docs.lock();
|
||||
let Some(d) = docs.get(&doc) else { return Vec::new() };
|
||||
let Some(c) = d.closing_labels.as_ref() else { return Vec::new() };
|
||||
if !d.servers.iter().any(|a| a.server.id == c.server && a.server.is_live(c.generation)) {
|
||||
return Vec::new();
|
||||
}
|
||||
c.hints.iter().filter(|h| range.start <= h.position && h.position <= range.end).cloned().collect()
|
||||
}
|
||||
|
||||
pub async fn workspace_symbols(&self, query: &str, cancel: CancellationToken) -> IdeResult<Vec<WorkspaceSymbol>> {
|
||||
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
|
||||
let targets = self.ready_targets(&servers, |c| c.has("workspaceSymbolProvider")).await;
|
||||
@@ -3315,6 +3357,7 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
let mut v = out.finish(Vec::new())?;
|
||||
v.extend(self.closing_label_hints(doc, range));
|
||||
v.sort_by_key(|h| h.position);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
@@ -237,6 +237,7 @@ impl LspManager {
|
||||
notebook: Some(path.to_owned()),
|
||||
changed: std::time::Instant::now(),
|
||||
flutter_outline: None,
|
||||
closing_labels: None,
|
||||
},
|
||||
);
|
||||
state.cells.push((cell.id.clone(), doc));
|
||||
|
||||
@@ -247,6 +247,8 @@ pub enum InlayKind {
|
||||
Type,
|
||||
Parameter,
|
||||
Other,
|
||||
/// What a closing bracket ends, at the end of its line (the Dart server's closing labels).
|
||||
ClosingLabel,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -1549,6 +1549,40 @@ async fn flutter_outline_follows_the_document_and_the_server_instance() {
|
||||
assert!(h.mgr.flutter_outline(reopened).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn closing_labels_join_the_inlay_hints_until_the_next_edit() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let (doc, path) = h.open("a.mk", "Center(\n child: Text('x'))\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("mock");
|
||||
s.respond("textDocument/inlayHint", json!([]));
|
||||
let refreshes = || {
|
||||
h.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::InlayHints, .. }))
|
||||
.count()
|
||||
};
|
||||
let at = |l0: u32, c0: u32, c1: u32| json!({"start":{"line":l0,"character":c0},"end":{"line":1,"character":c1}});
|
||||
let labels = json!({ "uri": uri_of(&path), "labels": [
|
||||
{ "range": at(1, 9, 18), "label": "Text" },
|
||||
{ "range": at(0, 0, 19), "label": "Center" },
|
||||
]});
|
||||
s.peer().notify("dart/textDocument/publishClosingLabels", labels).unwrap();
|
||||
eventually(|| refreshes() == 1).await;
|
||||
let whole = Range::new(Pos::new(0, 0), Pos::new(2, 0));
|
||||
let hints = h.mgr.inlay_hints(doc, whole).await.unwrap();
|
||||
assert_eq!(hints.len(), 1);
|
||||
assert_eq!(hints[0].label, "// Text // Center");
|
||||
assert_eq!(hints[0].position, Pos::new(1, 19));
|
||||
assert_eq!(hints[0].kind, InlayKind::ClosingLabel);
|
||||
assert!(h.mgr.inlay_hints(doc, Range::new(Pos::new(0, 0), Pos::new(0, 7))).await.unwrap().is_empty());
|
||||
|
||||
// Edited text: the labels wait for the next analysis.
|
||||
h.mgr.did_change(doc, 2, &[change(rng(0, 0, 0, 0), " ")], &|| unreachable!());
|
||||
assert!(h.mgr.inlay_hints(doc, whole).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn diagnostics_become_events_and_feed_code_actions() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
|
||||
@@ -317,6 +317,8 @@ pub trait HostApi: Send + Sync {
|
||||
fn storage_keys(&self, prefix: &str) -> Result<Vec<String>, HostError>;
|
||||
fn vcs_status(&self, root: &Path) -> Result<Option<RepositoryStatus>, HostError>;
|
||||
fn vcs_remotes(&self, root: &Path) -> Result<Vec<(String, String)>, HostError>;
|
||||
fn vcs_roots(&self, root: &Path) -> Result<Vec<String>, HostError>;
|
||||
fn vcs_repository_at(&self, root: &Path, path: &str) -> Result<Option<crate::RepositoryInfo>, HostError>;
|
||||
fn vcs_fetch(&self, root: &Path, cancel: &CancellationToken) -> Result<(), HostError>;
|
||||
/// The commit being prepared in `client`'s window (`None`: no repository),
|
||||
/// waiting for the window until `cancel` fires.
|
||||
|
||||
@@ -408,6 +408,18 @@ pub struct RepositoryStatus {
|
||||
pub changed_files: u32,
|
||||
}
|
||||
|
||||
/// Reference and remotes of a path's mapped worktree (WIT `vcs.repository-info`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct RepositoryInfo {
|
||||
pub root: String,
|
||||
pub relative_path: String,
|
||||
pub branch: Option<String>,
|
||||
pub commit: Option<String>,
|
||||
pub upstream: Option<String>,
|
||||
pub ahead: u32,
|
||||
pub remotes: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// A file a pending commit changes (WIT `commit.commit-change`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -1446,6 +1446,34 @@ impl vcs::Host for StoreData {
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
Ok(self.host.vcs_remotes(&root).map_err(to_wit))
|
||||
}
|
||||
|
||||
fn roots(&mut self, project: Resource<ProjectRes>) -> Fallible<Vec<String>> {
|
||||
if let Err(e) = self.require(Capability::VcsRead) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
Ok(self.host.vcs_roots(&self.table.get(&project)?.root).map_err(to_wit))
|
||||
}
|
||||
|
||||
fn repository_at(&mut self, project: Resource<ProjectRes>, path: String) -> Fallible<Option<vcs::RepositoryInfo>> {
|
||||
if let Err(e) = self.require(Capability::VcsRead) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
Ok(self
|
||||
.host
|
||||
.vcs_repository_at(&self.table.get(&project)?.root, &path)
|
||||
.map(|r| {
|
||||
r.map(|r| vcs::RepositoryInfo {
|
||||
root: r.root,
|
||||
relative_path: r.relative_path,
|
||||
branch: r.branch,
|
||||
commit: r.commit,
|
||||
upstream: r.upstream,
|
||||
ahead: r.ahead,
|
||||
remotes: r.remotes,
|
||||
})
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
}
|
||||
|
||||
impl build::Host for StoreData {
|
||||
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
1bd593215a298e86d1dcbccd5431d7efd3d0e0f0d83c0a05ecf95cd597cb89b1
|
||||
68517d169bea40ca5a5426a3a05ace3389417073b9369e79157a2beb051dcfc0
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
fce80835362944cf050a430a134a8c742e3365af32ad45ae2156918bd0c74575
|
||||
6edda84fad0ee7cd56a3a28b55e6c559db7b7f6b9c8c0ca645be805b545c01e7
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
e7d65dbf92a0edce8f1a6abf5a502dfc4fb4d818599ac1c54e8f82f60e62648a
|
||||
ecc6b6c52753b11521ae033a5a66c2a289119e09e07d22742203d3a13122dd97
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
c79c1613b8ce1dd69a2889b6a80a7608c6862b115d4283a8a9bae179e0fb57b9
|
||||
4ec581c69a62bbf424983e241a79d0bfdb5d025a3e86d27eea745adcb1906253
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
cc7ff6388700b72a9c8785f7935a79d018752e86ce32407ecd7a3b51f4093f09
|
||||
5fb89ee3d07e4275433ad9ad930ad781ef4f227af11aa5eb9dfc9174c015b1b8
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
fcf00edd43ed4fc26201ccdd4d1c102e51b9e0080603204d566e437bedc28fcf
|
||||
236db5a85d3e7e9fee01c3ff0b9f5e66fad7e3d64fa618a0c1c980d9e5883839
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
3f00290d04844109a9175f91dae042d3f377f0b2badf56955c589f1c1fbe71db
|
||||
4f89bd09b571016cbb9feb0674e668aa66996997c6b53a91d1a4ffbf161083a3
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
b9812539466c03233fabd6a428a1598bed0e485841ec462f577889da2f8c1831
|
||||
c5c3bac9e2b69e4957bd5049d4f560dd04faf4dfc2d7523bb7968aa29f3bdcfb
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
4a9eaf0b5374baf7cca82553d8209b7750f34c9e6dfd923bb491b07294b564d2
|
||||
a75758a44e255b7df3adf53e5f81b8f1283270d28f78ad0d8b358d9feea98a99
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
4d9403692c7bb8698f06c6336c5d9db7934004d6dd09362f77aa361b215108ca
|
||||
7e658a971fd58b84fcadc1f4939991d5f4506936989d4c8a7302ccebc0455e9c
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
df21a4a36dbfeb99505d24da6f18011531f581327f2c5069479ad47ab03bb8b3
|
||||
6b7c0d8971cfd3ba1d80c5fc6428e5890c820350972597a11be4ea6f0324973f
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
545723b3a96ef095c60cc2e16743fcd23bb8568a023507e2f1c33cba27478717
|
||||
20e43b6ac3aaa1527874f98f4b502ef88dd4676b6096b989c7bfba7a521e723d
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
698653d9344a009b0682becb67708d8e4e49d6880bce448f865b985f2605a330
|
||||
f879df5a331ec439c7e74af4d9c7d249477239e3a0a59d5e612548623cf5e9e2
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
03da30c1e589f499ae0889af62d39cfdbdcdc9f1035f8ed1479058843ef39ebf
|
||||
de1fc37d8fd5993164e0d903a0f1b4ba15005f2a90de325d7f4b4902a363fdf1
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
f080d959792a14554e6978923d4c5461a1b3d31dead0b7ec69131acb98e47f27
|
||||
367366c14b69d8f3837e731e061768ec5cb344d86fba89ced63fb196e5ca475e
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
b48218bf3d0f76b519cce52856c5f5c577a2273eb7e0afd63c771c0222342450
|
||||
b7bccc7f93b409263293d2dff8a31dbdcfcdfba133815f3ff60bc70a073257de
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
e34aabcbc0fb1cb26d5c913a8ddece8eea205128b4985c24e89935a49c4e290d
|
||||
f28d85f2004adcdf4e43faa57b7a5b52ab5d8233579979062461b0c5b4c63e10
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
a6c412b5e9f0f5b677a0d6ec64f50e90a62a5559a25f70a2f40fa83defc35823
|
||||
23c2c5e6e208104979e1f5b8620d2279547d372f0accf893c2d7797399fe39b0
|
||||
Binary file not shown.
Loaded 100 of 475 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user