Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 灵动岛计数徽标两位数不再折行 (#698)
Dash3587e5001208
diff --git a/apps/desktop/native/agent-island/macos-agent-island-helper.swift b/apps/desktop/native/agent-island/macos-agent-island-helper.swiftindex 9d2c767b0a..91d6aea691 100644--- a/apps/desktop/native/agent-island/macos-agent-island-helper.swift+++ b/apps/desktop/native/agent-island/macos-agent-island-helper.swift@@ -1552,6 +1552,12 @@ private let expandedIslandCenterSnapDistance: CGFloat = 30private let expandedIslandLayoutEmitInterval: TimeInterval = 0.033private let hardwareNotchTextRevealStartSideWidth: CGFloat = 44private let hardwareNotchTextRevealDistance: CGFloat = 38+// Upper bound of `hardwareNotchSideInset`, i.e. the trailing gap the notch layout keeps+// beside the count badge. Reserving this much guarantees the badge is never clipped at+// the default compact width.+private let hardwareNotchBadgeReservedInset: CGFloat = 9+// How close a compact width must be to a snap point to count as sitting on it.+private let compactWidthSnapTolerance: CGFloat = 1.5private let agentIslandTopDragHitSlop: CGFloat = 2private let agentIslandClickDragTolerance: CGFloat = 4private let hardwareNotchCenterTolerance: CGFloat = 2@@ -1951,12 +1957,18 @@ struct AgentIslandLayout: Equatable {let layoutScreenMetrics = hardwareNotchLayoutEnabled? screenMetrics: screenMetrics.disablingHardwareNotchLayout()+ // Only the compact hardware-notch layout reserves room for the badge; skip the font+ // measurement on every other layout tick.+ let compactBadgeWidth = !expanded && layoutScreenMetrics.hasNotch && hasSession+ ? PillBadge.intrinsicWidth(pillSnapshot: state.pillSnapshot, compact: true)+ : 0let width = computeWidth(expanded: expanded,hasSession: hasSession,availableFrameWidth: availableFrameWidth,screenMetrics: layoutScreenMetrics,- preferredContentWidth: preferredContentWidth+ preferredContentWidth: preferredContentWidth,+ compactBadgeWidth: compactBadgeWidth)let height = computeHeight(state: state, expanded: expanded, notchBaselineHeight: notchBaselineHeight)let shape = shapeForStatus(notchStatus)@@ -1983,7 +1995,8 @@ struct AgentIslandLayout: Equatable {hasSession: Bool,availableFrameWidth: CGFloat,screenMetrics: AgentIslandScreenMetrics,- preferredContentWidth: CGFloat?+ preferredContentWidth: CGFloat?,+ compactBadgeWidth: CGFloat) -> CGFloat {let idleExpandedWidth: CGFloat = 340let carrierInset = expanded ? expandedIslandCarrierExpandedInset : compactIslandCarrierInset@@ -2003,10 +2016,15 @@ struct AgentIslandLayout: Equatable {clampedWidth: clampedWidth,maxWidth: maxWidth,hasSession: hasSession,- screenMetrics: screenMetrics+ screenMetrics: screenMetrics,+ compactBadgeWidth: compactBadgeWidth)}- let defaultWidth = defaultCompactWidth(hasSession: hasSession, screenMetrics: screenMetrics)+ let defaultWidth = defaultCompactWidth(+ hasSession: hasSession,+ screenMetrics: screenMetrics,+ compactBadgeWidth: compactBadgeWidth+ )return min(preferred ?? defaultWidth, availableWidth)}@@ -2028,12 +2046,29 @@ struct AgentIslandLayout: Equatable {return compactIslandMinContentWidth}- static func defaultCompactWidth(hasSession: Bool, screenMetrics: AgentIslandScreenMetrics) -> CGFloat {+ /// Side width the trailing notch content needs so `compactBadgeWidth` survives+ /// `hardwareNotchTrailingContent`'s `.clipped()` frame. Mirrors the largest inset+ /// `hardwareNotchSideInset` can return, so a two-digit count stays readable.+ static func hardwareNotchBadgeSideWidth(compactBadgeWidth: CGFloat) -> CGFloat {+ compactBadgeWidth + hardwareNotchBadgeReservedInset+ }++ static func defaultCompactWidth(+ hasSession: Bool,+ screenMetrics: AgentIslandScreenMetrics,+ compactBadgeWidth: CGFloat = 0+ ) -> CGFloat {let notchWidth = CGFloat(screenMetrics.notchWidth)if screenMetrics.hasNotch {- let extra = hasSession+ let baseExtra = hasSession? AgentIslandScreenMetricsConfig.compactHardwareActiveExtraWidth: AgentIslandScreenMetricsConfig.compactHardwareIdleExtraWidth+ // A wide badge (multi-digit counts) must widen the island rather than get+ // clipped: both notch sides are symmetric, hence the doubling.+ let badgeExtra = hasSession+ ? hardwareNotchBadgeSideWidth(compactBadgeWidth: compactBadgeWidth) * 2+ : 0+ let extra = max(baseExtra, badgeExtra)return max(compactIslandBaseWidth, notchWidth + extra)}let extra = hasSession ? AgentIslandScreenMetricsConfig.compactSimulatedActiveExtraWidth : 0@@ -2045,21 +2080,36 @@ struct AgentIslandLayout: Equatable {clampedWidth: CGFloat,maxWidth: CGFloat,hasSession: Bool,- screenMetrics: AgentIslandScreenMetrics+ screenMetrics: AgentIslandScreenMetrics,+ compactBadgeWidth: CGFloat = 0) -> CGFloat {guard screenMetrics.hasNotch else {return clampedWidth}let hiddenWidth = min(maxWidth, max(1, CGFloat(screenMetrics.notchWidth)))- let basicWidth = min(+ // The hidden/basic classification stays anchored to the badge-independent basic+ // width. Otherwise a persisted basic width silently falls below the hidden+ // threshold once a wider badge enlarges `basicWidth`, collapsing the whole island.+ let baseBasicWidth = min(maxWidth,max(hiddenWidth, defaultCompactWidth(hasSession: hasSession, screenMetrics: screenMetrics)))- let gap = basicWidth - hiddenWidth+ let basicWidth = min(+ maxWidth,+ max(+ hiddenWidth,+ defaultCompactWidth(+ hasSession: hasSession,+ screenMetrics: screenMetrics,+ compactBadgeWidth: compactBadgeWidth+ )+ )+ )+ let gap = baseBasicWidth - hiddenWidthguard gap > 8 else {return hiddenWidth}- let hiddenThreshold = basicWidth - min(+ let hiddenThreshold = baseBasicWidth - min(AgentIslandScreenMetricsConfig.compactHardwareHiddenPullDistance,max(24, gap * 0.5))@@ -2416,11 +2466,13 @@ struct CompactSessionView: View {).lineLimit(1).truncationMode(.tail)- .fixedSize(horizontal: true, vertical: false)+ // No fixedSize here: the subtitle must yield width (and truncate) so the+ // count badge keeps its full intrinsic width instead of being clipped..opacity(textOpacity)}PillBadge(pillSnapshot: pillSnapshot, compact: true)+ .layoutPriority(1)}.padding(.trailing, hardwareNotchSideInset(sideWidth: sideWidth, compactWidth: 22)).frame(width: sideWidth, alignment: .trailing)@@ -2864,6 +2916,60 @@ struct PillBadge: View {let pillSnapshot: AgentIslandPillSnapshotvar compact: Bool = false+ /// Text runs and minimum capsule width for the badge variant a snapshot renders.+ /// Shared by `body` and `intrinsicWidth` so reserved layout width can never+ /// drift away from what actually gets drawn.+ struct Metrics {+ /// One entry per rendered `Text`; each is laid out (and rounded) separately.+ let segments: [String]+ let minWidth: CGFloat+ let fontSize: CGFloat+ }++ static func metrics(pillSnapshot: AgentIslandPillSnapshot, compact: Bool) -> Metrics {+ let fontSize: CGFloat = compact ? 10 : 11+ if pillSnapshot.activeSessionCount > 0 && pillSnapshot.sessionCount > 1 {+ return Metrics(+ segments: ["\(pillSnapshot.activeSessionCount)", "/", "\(pillSnapshot.sessionCount)"],+ minWidth: compact ? 30 : 34,+ fontSize: fontSize+ )+ }+ return Metrics(+ segments: ["\(max(1, pillSnapshot.sessionCount))"],+ minWidth: compact ? 22 : 24,+ fontSize: fontSize+ )+ }++ /// Width the hardware-notch layout reserves for the capsule so a multi-digit count is+ /// never clipped.+ ///+ /// This is deliberately a *nominal* width computed from digit counts, not an `NSFont`+ /// measurement: main computes the carrier width from the very same formula in+ /// `getAgentIslandCompactBadgeWidth` (`shared/agentIsland.ts`), and the two must agree+ /// exactly. A measured value here would sit a few points below the TS estimate, and+ /// every snap comparison against the delivered width would silently miss.+ /// `nominalCharWidth` is an upper bound on the real advance, so the reserved width is+ /// always at least what SwiftUI draws — `badge-probe` harness asserts that.+ static func intrinsicWidth(pillSnapshot: AgentIslandPillSnapshot, compact: Bool) -> CGFloat {+ let metrics = metrics(pillSnapshot: pillSnapshot, compact: compact)+ let segmentsWidth = metrics.segments.reduce(CGFloat(0)) { total, segment in+ total + CGFloat(segment.count) * nominalCharWidth + segmentRoundingSlack+ }+ let spacing = activeTotalSpacing * CGFloat(max(0, metrics.segments.count - 1))+ return max(metrics.minWidth, segmentsWidth + spacing + contentInset * 2)+ }++ private static let activeTotalSpacing: CGFloat = 1+ private static let contentInset: CGFloat = 2+ /// Upper bound for one monospaced 10pt digit (real advance is ~6pt). Mirrors+ /// `AGENT_ISLAND_COMPACT_BADGE_CHAR_WIDTH_BOUND` on the TS side.+ private static let nominalCharWidth: CGFloat = 7+ /// Per-segment rounding slack; SwiftUI lays out and rounds every `Text` run+ /// separately. Mirrors `AGENT_ISLAND_COMPACT_BADGE_SEGMENT_ROUNDING_SLACK`.+ private static let segmentRoundingSlack: CGFloat = 1+var body: some View {if pillSnapshot.activeSessionCount > 0 && pillSnapshot.sessionCount > 1 {activeTotalBadge(@@ -2878,15 +2984,19 @@ struct PillBadge: View {private func badge(_ text: String, emphasized: Bool) -> some View {Text(text)- .font(.system(size: compact ? 10 : 11, weight: .semibold, design: .monospaced))+ .font(badgeFont).foregroundColor(Color.white.opacity(0.92))- .frame(minWidth: compact ? 22 : 24, minHeight: compact ? 18 : 20)+ // Multi-digit counts must widen the capsule instead of wrapping into two lines.+ .lineLimit(1)+ .fixedSize(horizontal: true, vertical: false)+ .padding(.horizontal, Self.contentInset)+ .frame(minWidth: metrics.minWidth, minHeight: compact ? 18 : 20).background(Color.white.opacity(emphasized ? 0.11 : 0.065)).clipShape(Capsule())}private func activeTotalBadge(active: Int, total: Int, emphasized: Bool) -> some View {- HStack(spacing: 1) {+ HStack(spacing: Self.activeTotalSpacing) {Text("\(active)").foregroundColor(emphasized ? agentIslandBlue : agentIslandOrange)Text("/")@@ -2894,12 +3004,24 @@ struct PillBadge: View {Text("\(total)").foregroundColor(Color.white.opacity(0.92))}- .font(.system(size: compact ? 10 : 11, weight: .semibold, design: .monospaced))- .frame(minWidth: compact ? 30 : 34, minHeight: compact ? 18 : 20)+ .font(badgeFont)+ // Multi-digit counts must widen the capsule instead of wrapping into two lines.+ .lineLimit(1)+ .fixedSize(horizontal: true, vertical: false)+ .padding(.horizontal, Self.contentInset)+ .frame(minWidth: metrics.minWidth, minHeight: compact ? 18 : 20).background(Color.white.opacity(emphasized ? 0.11 : 0.065)).clipShape(Capsule())}+ private var metrics: Metrics {+ Self.metrics(pillSnapshot: pillSnapshot, compact: compact)+ }++ private var badgeFont: Font {+ .system(size: metrics.fontSize, weight: .semibold, design: .monospaced)+ }+private var isEmphasized: Bool {pillSnapshot.pendingInteractionCount > 0 || pillSnapshot.attentionCount > 0}@@ -5342,18 +5464,18 @@ final class AgentIslandController {hiddenWidth,AgentIslandLayout.defaultCompactWidth(hasSession: model.state.totalCount > 0,- screenMetrics: model.screenMetrics+ screenMetrics: model.screenMetrics,+ compactBadgeWidth: compactBadgeWidth)))guard basicWidth - hiddenWidth > 8 else {return .hidden}- let tolerance: CGFloat = 1.5- if abs(contentWidth - hiddenWidth) <= tolerance {+ if abs(contentWidth - hiddenWidth) <= compactWidthSnapTolerance {return .hidden}- if abs(contentWidth - basicWidth) <= tolerance {+ if abs(contentWidth - basicWidth) <= compactWidthSnapTolerance {return .basic}return .free@@ -5423,6 +5545,50 @@ final class AgentIslandController {clampedWidth: clampedWidth,maxWidth: maxWidth,hasSession: model.state.totalCount > 0,+ screenMetrics: model.screenMetrics,+ compactBadgeWidth: compactBadgeWidth+ )+ }++ /// Width reserved for the compact count badge in the current snapshot, used to keep+ /// drag snapping aligned with the reserved default width. Only the centered hardware+ /// notch layout reserves room for the badge.+ private var compactBadgeWidth: CGFloat {+ guard model.hardwareNotchLayoutEnabled,+ model.screenMetrics.hasNotch,+ model.state.totalCount > 0+ else {+ return 0+ }+ return PillBadge.intrinsicWidth(pillSnapshot: model.state.pillSnapshot, compact: true)+ }++ /// Width persisted as the user's compact preference. At the badge-aware basic snap we+ /// store the badge-independent basic width instead: the stored scalar must not encode+ /// the current count, otherwise the island keeps a wide preference after the count+ /// drops (and the snap can no longer contract).+ ///+ /// Gated on `hardwareNotchLayoutEnabled` as well as `hasNotch`: once the island is+ /// moved off the notch, the emitted frame uses the plain compact layout and its width+ /// must be persisted verbatim — rewriting it there would shrink the island mid-move.+ private func persistedCompactContentWidth(_ contentWidth: CGFloat) -> CGFloat {+ guard !lastLayout.expanded,+ model.hardwareNotchLayoutEnabled,+ model.screenMetrics.hasNotch+ else {+ return contentWidth+ }+ let hasSession = model.state.totalCount > 0+ let badgeAwareBasicWidth = AgentIslandLayout.defaultCompactWidth(+ hasSession: hasSession,+ screenMetrics: model.screenMetrics,+ compactBadgeWidth: compactBadgeWidth+ )+ guard abs(contentWidth - badgeAwareBasicWidth) <= compactWidthSnapTolerance else {+ return contentWidth+ }+ return AgentIslandLayout.defaultCompactWidth(+ hasSession: hasSession,screenMetrics: model.screenMetrics)}@@ -5480,7 +5646,9 @@ final class AgentIslandController {"type": "layout","displayId": AgentIslandScreenMetricsProvider.displayId(for: screen),"centerXRatio": Double(min(1, max(0, ratio))),- "contentWidth": Double(constrainedContentWidth(contentWidth, expanded: lastLayout.expanded)),+ "contentWidth": Double(persistedCompactContentWidth(+ constrainedContentWidth(contentWidth, expanded: lastLayout.expanded)+ )),"expanded": lastLayout.expanded,])}diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex 950381a96b..46b7660c58 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -40,6 +40,7 @@ import {AGENT_ISLAND_SESSION_SNAPSHOTS_CHANNEL,type AgentIslandDisplayOption,type AgentIslandDisplayState,+ type AgentIslandPillSnapshot,type AgentIslandSessionActivity,type AgentIslandDisplayTarget,type AgentIslandMascotSkin,@@ -1606,6 +1607,9 @@ export class AgentIslandService {hasSession,displayWidth: display.bounds.width,screenMetrics,+ // Keep the carrier wide enough for the native count badge; without this the+ // native side's own reservation gets clamped away and the badge is clipped.+ pillSnapshot: displayState.pillSnapshot,});const minimumContentWidth = getAgentIslandMinimumContentWidth({expanded,@@ -1619,6 +1623,7 @@ export class AgentIslandService {display,screenMetrics,minimumContentWidth,+ pillSnapshot: displayState.pillSnapshot,}): null;const contentWidth = preferredContentWidth !== null@@ -1751,6 +1756,7 @@ export class AgentIslandService {display: Display;screenMetrics: AgentIslandScreenLayoutMetrics | null;minimumContentWidth: number;+ pillSnapshot?: AgentIslandPillSnapshot | null;}): number {if (input.expanded) {return input.desiredWidth;@@ -1767,6 +1773,7 @@ export class AgentIslandService {maxWidth,hasSession: input.hasSession,screenMetrics: input.screenMetrics,+ pillSnapshot: input.pillSnapshot,});}diff --git a/apps/desktop/src/shared/__tests__/agentIslandCompactBadgeWidth.test.ts b/apps/desktop/src/shared/__tests__/agentIslandCompactBadgeWidth.test.tsnew file mode 100644index 0000000000..bf6ecf47de--- /dev/null+++ b/apps/desktop/src/shared/__tests__/agentIslandCompactBadgeWidth.test.ts@@ -0,0 +1,401 @@+import { describe, expect, it } from 'vitest';++import {+ AGENT_ISLAND_CARRIER_COMPACT_INSET,+ AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH,+ AGENT_ISLAND_COMPACT_HARDWARE_BADGE_RESERVED_INSET,+ AGENT_ISLAND_COMPACT_HARDWARE_HIDDEN_PULL_DISTANCE,+ AGENT_ISLAND_COMPACT_HARDWARE_IDLE_EXTRA_WIDTH,+ AGENT_ISLAND_COMPACT_IDLE_WIDTH,+ AGENT_ISLAND_MAX_RESIZABLE_WIDTH,+ getAgentIslandCompactBadgeWidth,+ getAgentIslandDefaultContentWidth,+ snapAgentIslandCompactHardwareContentWidth,+} from '../agentIsland';++/**+ * 灵动岛计数徽标由 native helper(macos-agent-island-helper.swift)绘制,但 carrier+ * 窗口宽度由这里的 TS 计算决定,两侧必须算出**完全相同**的徽标宽度:+ *+ * - TS 估小 → native 的预留被 carrier 宽度 clamp 掉,徽标被 `.clipped()` 切掉+ * - 两侧不等 → native 的吸附/持久化归一化拿 main 交付的宽度去比自己的值时永远对不上+ * (PR #698 review 里两次踩到)+ *+ * 所以 Swift 的 `PillBadge.intrinsicWidth` 不做 NSFont 测量,而是与这里同一套按位数算的+ * 标称公式。下表的 layoutWidth 就是两侧都应算出的值;renderedWidth 是 SwiftUI 实际绘制+ * 宽度(NSHostingView 实测),标称值必须能覆盖它。+ */+const NATIVE_COMPACT_BADGE_WIDTH: Array<{+ label: string;+ pillSnapshot: { activeSessionCount: number; sessionCount: number };+ /** Swift `PillBadge.intrinsicWidth(compact: true)` 应算出的值,必须与 TS 完全一致。 */+ layoutWidth: number;+ /** SwiftUI 实绘宽度,标称宽度必须 >= 它,否则仍会被裁。 */+ renderedWidth: number;+}> = [+ { label: '单会话', pillSnapshot: { activeSessionCount: 0, sessionCount: 1 }, layoutWidth: 22, renderedWidth: 22 },+ { label: '12 个会话', pillSnapshot: { activeSessionCount: 0, sessionCount: 12 }, layoutWidth: 22, renderedWidth: 22 },+ { label: '1/2', pillSnapshot: { activeSessionCount: 1, sessionCount: 2 }, layoutWidth: 30, renderedWidth: 30 },+ { label: '9/9', pillSnapshot: { activeSessionCount: 9, sessionCount: 9 }, layoutWidth: 30, renderedWidth: 30 },+ { label: '1/12', pillSnapshot: { activeSessionCount: 1, sessionCount: 12 }, layoutWidth: 37, renderedWidth: 33 },+ { label: '11/12', pillSnapshot: { activeSessionCount: 11, sessionCount: 12 }, layoutWidth: 44, renderedWidth: 39 },+ { label: '10/100', pillSnapshot: { activeSessionCount: 10, sessionCount: 100 }, layoutWidth: 51, renderedWidth: 45 },+ { label: '99/99', pillSnapshot: { activeSessionCount: 99, sessionCount: 99 }, layoutWidth: 44, renderedWidth: 39 },+ { label: '123/456', pillSnapshot: { activeSessionCount: 123, sessionCount: 456 }, layoutWidth: 58, renderedWidth: 51 },+];++const NOTCH_WIDTHS = [180, 200, 210, 215];++/** native `CompactSessionView.hardwareNotchBody` 的侧宽公式。 */+function sideWidth(contentWidth: number, notchWidth: number): number {+ return Math.max(32, (contentWidth - notchWidth) / 2);+}++/** native `hardwareNotchSideInset(sideWidth:compactWidth:)`,compactWidth 固定 22。 */+function trailingInset(side: number): number {+ return Math.max(7, (Math.min(side, 40) - 22) / 2);+}++describe('getAgentIslandCompactBadgeWidth', () => {+ it('与 Swift PillBadge.intrinsicWidth 逐值一致(两侧公式必须同步)', () => {+ for (const { label, pillSnapshot, layoutWidth } of NATIVE_COMPACT_BADGE_WIDTH) {+ expect(getAgentIslandCompactBadgeWidth(pillSnapshot), `${label} 与 Swift 侧不一致`)+ .toBe(layoutWidth);+ }+ });++ it('标称宽度覆盖 SwiftUI 实绘宽度(否则徽标仍会被裁)', () => {+ for (const { label, pillSnapshot, renderedWidth } of NATIVE_COMPACT_BADGE_WIDTH) {+ const nominal = getAgentIslandCompactBadgeWidth(pillSnapshot);+ expect(nominal, `${label} 标称 ${nominal} < 实绘 ${renderedWidth}`)+ .toBeGreaterThanOrEqual(renderedWidth);+ }+ });++ it('单个计数走 22pt 最小宽度,active/total 才随位数变宽', () => {+ expect(getAgentIslandCompactBadgeWidth({ activeSessionCount: 0, sessionCount: 1 })).toBe(22);+ expect(getAgentIslandCompactBadgeWidth({ activeSessionCount: 0, sessionCount: 12 })).toBe(22);+ const oneDigit = getAgentIslandCompactBadgeWidth({ activeSessionCount: 1, sessionCount: 2 });+ const twoDigits = getAgentIslandCompactBadgeWidth({ activeSessionCount: 11, sessionCount: 12 });+ expect(twoDigits).toBeGreaterThan(oneDigit);+ });++ it('sessionCount 为 0 时按 1 处理,不产出小于最小宽度的值', () => {+ expect(getAgentIslandCompactBadgeWidth({ activeSessionCount: 0, sessionCount: 0 })).toBe(22);+ });+});++describe('getAgentIslandDefaultContentWidth: 刻痕机为计数徽标预留宽度', () => {+ it('预留后的侧宽足够容纳 native 徽标(扣掉 trailing inset 仍装得下)', () => {+ for (const notchWidth of NOTCH_WIDTHS) {+ for (const { label, pillSnapshot, layoutWidth } of NATIVE_COMPACT_BADGE_WIDTH) {+ const contentWidth = getAgentIslandDefaultContentWidth({+ expanded: false,+ hasSession: true,+ screenMetrics: { hasNotch: true, notchWidth },+ pillSnapshot,+ });+ const side = sideWidth(contentWidth, notchWidth);+ const available = side - trailingInset(side);+ expect(+ available,+ `notch ${notchWidth} ${label}: 可用 ${available} < 徽标 ${layoutWidth}`,+ ).toBeGreaterThanOrEqual(layoutWidth);+ }+ }+ });++ it('无会话与单会话时宽度与旧实现完全一致', () => {+ for (const notchWidth of NOTCH_WIDTHS) {+ const legacyActive = Math.max(+ AGENT_ISLAND_COMPACT_IDLE_WIDTH,+ notchWidth + AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH,+ );+ const legacyIdle = Math.max(+ AGENT_ISLAND_COMPACT_IDLE_WIDTH,+ notchWidth + AGENT_ISLAND_COMPACT_HARDWARE_IDLE_EXTRA_WIDTH,+ );+ expect(getAgentIslandDefaultContentWidth({+ expanded: false,+ hasSession: true,+ screenMetrics: { hasNotch: true, notchWidth },+ pillSnapshot: { activeSessionCount: 0, sessionCount: 1 },+ })).toBe(legacyActive);+ expect(getAgentIslandDefaultContentWidth({+ expanded: false,+ hasSession: false,+ screenMetrics: { hasNotch: true, notchWidth },+ pillSnapshot: { activeSessionCount: 11, sessionCount: 12 },+ })).toBe(legacyIdle);+ }+ });++ it('不传 pillSnapshot 时退回旧行为,不会意外加宽', () => {+ for (const notchWidth of NOTCH_WIDTHS) {+ expect(getAgentIslandDefaultContentWidth({+ expanded: false,+ hasSession: true,+ screenMetrics: { hasNotch: true, notchWidth },+ })).toBe(Math.max(+ AGENT_ISLAND_COMPACT_IDLE_WIDTH,+ notchWidth + AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH,+ ));+ }+ });++ it('预留量等于 (徽标宽 + inset 上界) * 2', () => {+ const notchWidth = 200;+ const pillSnapshot = { activeSessionCount: 11, sessionCount: 12 };+ const badgeWidth = getAgentIslandCompactBadgeWidth(pillSnapshot);+ expect(getAgentIslandDefaultContentWidth({+ expanded: false,+ hasSession: true,+ screenMetrics: { hasNotch: true, notchWidth },+ pillSnapshot,+ })).toBe(+ notchWidth + (badgeWidth + AGENT_ISLAND_COMPACT_HARDWARE_BADGE_RESERVED_INSET) * 2,+ );+ });++ it('非刻痕机与 expanded 形态不受影响', () => {+ const pillSnapshot = { activeSessionCount: 11, sessionCount: 12 };+ const simulated = getAgentIslandDefaultContentWidth({+ expanded: false,+ hasSession: true,+ displayWidth: 1512,+ screenMetrics: { hasNotch: false, notchWidth: 210 },+ pillSnapshot,+ });+ expect(simulated).toBe(getAgentIslandDefaultContentWidth({+ expanded: false,+ hasSession: true,+ displayWidth: 1512,+ screenMetrics: { hasNotch: false, notchWidth: 210 },+ }));+ expect(getAgentIslandDefaultContentWidth({+ expanded: true,+ hasSession: true,+ screenMetrics: { hasNotch: true, notchWidth: 200 },+ pillSnapshot,+ })).toBe(getAgentIslandDefaultContentWidth({+ expanded: true,+ hasSession: true,+ screenMetrics: { hasNotch: true, notchWidth: 200 },+ }));+ });+});++/**+ * 跨语言契约:carrier 窗口宽度由 TS 算,native 只能在 `availableFrameWidth` 之内再 clamp。+ * 下面复刻 native `AgentIslandLayout.computeWidth` 的 preferred 分支(常量与+ * macos-agent-island-helper.swift 一一对应),确认 TS 交付的 carrier 不会把 native 自己的+ * 徽标预留 clamp 掉 —— 这正是 PR #698 第二轮 review 指出的失效环节。native 侧改动这段+ * 逻辑时,这里需要一起更新。+ */+function nativeCompactContentWidth(input: {+ tsContentWidth: number;+ notchWidth: number;+ nativeBadgeWidth: number;+}): number {+ const carrierWidth = Math.round(input.tsContentWidth + AGENT_ISLAND_CARRIER_COMPACT_INSET * 2);+ const availableWidth = Math.max(1, carrierWidth - AGENT_ISLAND_CARRIER_COMPACT_INSET * 2);+ const maxWidth = Math.min(AGENT_ISLAND_MAX_RESIZABLE_WIDTH, availableWidth);+ const minWidth = Math.min(Math.max(1, input.notchWidth), maxWidth);+ const clampedWidth = Math.min(maxWidth, Math.max(minWidth, input.tsContentWidth));+ const hiddenWidth = Math.min(maxWidth, Math.max(1, input.notchWidth));+ const nativeDefault = Math.max(+ AGENT_ISLAND_COMPACT_IDLE_WIDTH,+ input.notchWidth + Math.max(+ AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH,+ (input.nativeBadgeWidth + AGENT_ISLAND_COMPACT_HARDWARE_BADGE_RESERVED_INSET) * 2,+ ),+ );+ const basicWidth = Math.min(maxWidth, Math.max(hiddenWidth, nativeDefault));+ const gap = basicWidth - hiddenWidth;+ if (gap <= 8) return hiddenWidth;+ const hiddenThreshold = basicWidth - Math.min(+ AGENT_ISLAND_COMPACT_HARDWARE_HIDDEN_PULL_DISTANCE,+ Math.max(24, gap * 0.5),+ );+ if (input.tsContentWidth <= hiddenThreshold) return hiddenWidth;+ if (input.tsContentWidth <= basicWidth) return basicWidth;+ return clampedWidth;+}++describe('TS carrier 宽度 → native 宽度链路', () => {+ it('native 拿到的宽度足以完整绘制徽标(carrier 不再 clamp 掉预留)', () => {+ for (const notchWidth of NOTCH_WIDTHS) {+ for (const { label, pillSnapshot, layoutWidth } of NATIVE_COMPACT_BADGE_WIDTH) {+ const tsContentWidth = getAgentIslandDefaultContentWidth({+ expanded: false,+ hasSession: true,+ screenMetrics: { hasNotch: true, notchWidth },+ pillSnapshot,+ });+ const resolved = nativeCompactContentWidth({+ tsContentWidth,+ notchWidth,+ nativeBadgeWidth: layoutWidth,+ });+ const side = sideWidth(resolved, notchWidth);+ const available = side - trailingInset(side);+ expect(+ available,+ `notch ${notchWidth} ${label}: native 解析出 ${resolved},可用 ${available} < 徽标 ${layoutWidth}`,+ ).toBeGreaterThanOrEqual(layoutWidth);+ }+ }+ });++ it('回归:旧的 TS 宽度(notch + 64)会让 native 预留被 clamp 掉', () => {+ const notchWidth = 200;+ const nativeBadgeWidth = 44; // 11/12+ const legacyTsWidth = notchWidth + AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH;+ const resolved = nativeCompactContentWidth({+ tsContentWidth: legacyTsWidth,+ notchWidth,+ nativeBadgeWidth,+ });+ const side = sideWidth(resolved, notchWidth);+ expect(side - trailingInset(side)).toBeLessThan(nativeBadgeWidth);+ });+});++describe('snapAgentIslandCompactHardwareContentWidth', () => {+ it('吸附点跟随预留后的默认宽度', () => {+ const notchWidth = 200;+ const pillSnapshot = { activeSessionCount: 11, sessionCount: 12 };+ const screenMetrics = { hasNotch: true, notchWidth };+ const basicWidth = getAgentIslandDefaultContentWidth({+ expanded: false,+ hasSession: true,+ screenMetrics,+ pillSnapshot,+ });+ // 旧的默认宽度(notch + 64)现在落在吸附区间内,应被吸附到更宽的 basicWidth。+ expect(snapAgentIslandCompactHardwareContentWidth({+ desiredWidth: notchWidth + AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH,+ clampedWidth: notchWidth + AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH,+ maxWidth: 920,+ hasSession: true,+ screenMetrics,+ pillSnapshot,+ })).toBe(basicWidth);+ });++ it('用户拖到很窄时仍吸附回隐藏宽度(拖窄是显式意图)', () => {+ const notchWidth = 200;+ expect(snapAgentIslandCompactHardwareContentWidth({+ desiredWidth: notchWidth,+ clampedWidth: notchWidth,+ maxWidth: 920,+ hasSession: true,+ screenMetrics: { hasNotch: true, notchWidth },+ pillSnapshot: { activeSessionCount: 11, sessionCount: 12 },+ })).toBe(notchWidth);+ });++ it('计数变多不会把此前停在 basic 的持久化宽度判成 hidden(灵动岛不塌缩)', () => {+ // 回归:三位数徽标把 basicWidth 撑到 320,若 hidden 阈值也跟着抬到 272,+ // 用户此前存下的 basic 宽度 264 会被判成 hidden,整个 compact 岛被收起。+ const notchWidth = 200;+ const persistedBasicWidth = notchWidth + AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH;+ const screenMetrics = { hasNotch: true, notchWidth };+ for (const pillSnapshot of [+ { activeSessionCount: 10, sessionCount: 100 },+ { activeSessionCount: 11, sessionCount: 12 },+ { activeSessionCount: 123, sessionCount: 456 },+ ]) {+ const widened = getAgentIslandDefaultContentWidth({+ expanded: false,+ hasSession: true,+ screenMetrics,+ pillSnapshot,+ });+ const resolved = snapAgentIslandCompactHardwareContentWidth({+ desiredWidth: persistedBasicWidth,+ clampedWidth: persistedBasicWidth,+ maxWidth: 920,+ hasSession: true,+ screenMetrics,+ pillSnapshot,+ });+ expect(resolved, `${pillSnapshot.activeSessionCount}/${pillSnapshot.sessionCount} 塌缩到了 ${resolved}`)+ .not.toBe(notchWidth);+ expect(resolved).toBe(widened);+ }+ });++ it('hidden 阈值与旧实现一致:略窄于旧 basic 仍吸附到 basic,更窄才隐藏', () => {+ const notchWidth = 200;+ const screenMetrics = { hasNotch: true, notchWidth };+ const pillSnapshot = { activeSessionCount: 11, sessionCount: 12 };+ const widened = getAgentIslandDefaultContentWidth({+ expanded: false,+ hasSession: true,+ screenMetrics,+ pillSnapshot,+ });+ // 旧 basic 264、hidden 200、gap 64 → 阈值 264 - 32 = 232。+ expect(snapAgentIslandCompactHardwareContentWidth({+ desiredWidth: 240,+ clampedWidth: 240,+ maxWidth: 920,+ hasSession: true,+ screenMetrics,+ pillSnapshot,+ })).toBe(widened);+ expect(snapAgentIslandCompactHardwareContentWidth({+ desiredWidth: 230,+ clampedWidth: 230,+ maxWidth: 920,+ hasSession: true,+ screenMetrics,+ pillSnapshot,+ })).toBe(notchWidth);+ });++ it('持久化的是与徽标无关的 basic 宽度时,计数升降都能正确跟随', () => {+ // native 侧 `persistedCompactContentWidth` 保证停在 basic 吸附位时存下的是+ // 与计数无关的 baseBasicWidth,这里验证存下该标量后两个方向都归一到当前 basic。+ const notchWidth = 200;+ const screenMetrics = { hasNotch: true, notchWidth };+ const persisted = notchWidth + AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH;+ const resolveFor = (pillSnapshot: { activeSessionCount: number; sessionCount: number }) =>+ snapAgentIslandCompactHardwareContentWidth({+ desiredWidth: persisted,+ clampedWidth: persisted,+ maxWidth: 920,+ hasSession: true,+ screenMetrics,+ pillSnapshot,+ });++ const wide = resolveFor({ activeSessionCount: 11, sessionCount: 12 });+ const narrow = resolveFor({ activeSessionCount: 0, sessionCount: 1 });+ expect(wide).toBeGreaterThan(persisted);+ // 计数回落后必须收缩回旧的 basic 宽度,不能停在为宽徽标撑开的宽度上。+ expect(narrow).toBe(persisted);+ expect(narrow).toBeLessThan(wide);+ });++ it('不传 pillSnapshot 时吸附行为与旧实现完全一致', () => {+ const notchWidth = 200;+ const screenMetrics = { hasNotch: true, notchWidth };+ const legacyBasic = notchWidth + AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH;+ for (const [desiredWidth, expected] of [+ [legacyBasic, legacyBasic],+ [240, legacyBasic],+ [230, notchWidth],+ [notchWidth, notchWidth],+ ] as Array<[number, number]>) {+ expect(snapAgentIslandCompactHardwareContentWidth({+ desiredWidth,+ clampedWidth: desiredWidth,+ maxWidth: 920,+ hasSession: true,+ screenMetrics,+ })).toBe(expected);+ }+ });+});diff --git a/apps/desktop/src/shared/agentIsland.ts b/apps/desktop/src/shared/agentIsland.tsindex 73a5c016a5..64c4cc8652 100644--- a/apps/desktop/src/shared/agentIsland.ts+++ b/apps/desktop/src/shared/agentIsland.ts@@ -454,6 +454,25 @@ export const AGENT_ISLAND_COMPACT_SIMULATED_ACTIVE_EXTRA_WIDTH = 88;export const AGENT_ISLAND_COMPACT_HARDWARE_IDLE_EXTRA_WIDTH = 64;export const AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH = 64;export const AGENT_ISLAND_COMPACT_HARDWARE_HIDDEN_PULL_DISTANCE = 48;+// Compact count-badge metrics, kept in sync with `PillBadge` in+// `native/agent-island/macos-agent-island-helper.swift`. Only used to reserve carrier+// width; the native helper still measures the real font for what it draws.+export const AGENT_ISLAND_COMPACT_BADGE_MIN_WIDTH = 22;+export const AGENT_ISLAND_COMPACT_BADGE_ACTIVE_TOTAL_MIN_WIDTH = 30;+export const AGENT_ISLAND_COMPACT_BADGE_CONTENT_INSET = 2;+export const AGENT_ISLAND_COMPACT_BADGE_TEXT_SPACING = 1;+/** Generous upper bound for one monospaced 10pt digit (real advance is ~6pt). */+export const AGENT_ISLAND_COMPACT_BADGE_CHAR_WIDTH_BOUND = 7;+/**+ * Per-segment rounding slack, mirroring `PillBadge.segmentRoundingSlack` in the Swift+ * helper (`ceil(measured + 1)` per `Text`). SwiftUI lays out and rounds every `Text`+ * run separately, so the slack is added once per segment — not once per badge. Dropping+ * it would make this estimate fall below the native width and let the badge get clipped+ * again; `agentIslandCompactBadgeWidth.test.ts` guards that.+ */+export const AGENT_ISLAND_COMPACT_BADGE_SEGMENT_ROUNDING_SLACK = 1;+/** Upper bound of the native `hardwareNotchSideInset` beside the badge. */+export const AGENT_ISLAND_COMPACT_HARDWARE_BADGE_RESERVED_INSET = 9;export const AGENT_ISLAND_MAX_EXPANDED_HEIGHT = 560;export const AGENT_ISLAND_SCREEN_EDGE_GUTTER = 112;export const AGENT_ISLAND_CARRIER_COMPACT_INSET = 20;@@ -482,11 +501,46 @@ export function computeAgentIslandSimulatedNotchWidth(displayWidth: number): num);}+/**+ * Upper-bound width of the compact count badge the native helper draws, mirroring+ * `PillBadge.intrinsicWidth` in `macos-agent-island-helper.swift`.+ *+ * The carrier window sizes itself from this, so the native side can only ever clamp+ * the island *down* to its own exact measurement — never get clipped for lack of room.+ * That is why the per-character advance below is deliberately generous: the real+ * monospaced 10pt advance is ~6pt, and overestimating only leaves invisible slack+ * inside the carrier's transparent inset.+ */+export function getAgentIslandCompactBadgeWidth(input: {+ activeSessionCount: number;+ sessionCount: number;+}): number {+ const isActiveTotal = input.activeSessionCount > 0 && input.sessionCount > 1;+ const segments = isActiveTotal+ ? [`${input.activeSessionCount}`, '/', `${input.sessionCount}`]+ : [`${Math.max(1, input.sessionCount)}`];+ const segmentsWidth = segments.reduce(+ (total, segment) => total+ + segment.length * AGENT_ISLAND_COMPACT_BADGE_CHAR_WIDTH_BOUND+ + AGENT_ISLAND_COMPACT_BADGE_SEGMENT_ROUNDING_SLACK,+ 0,+ );+ const spacing = AGENT_ISLAND_COMPACT_BADGE_TEXT_SPACING * Math.max(0, segments.length - 1);+ const minWidth = isActiveTotal+ ? AGENT_ISLAND_COMPACT_BADGE_ACTIVE_TOTAL_MIN_WIDTH+ : AGENT_ISLAND_COMPACT_BADGE_MIN_WIDTH;+ return Math.max(+ minWidth,+ segmentsWidth + spacing + AGENT_ISLAND_COMPACT_BADGE_CONTENT_INSET * 2,+ );+}+export function getAgentIslandDefaultContentWidth(input: {expanded: boolean;hasSession: boolean;displayWidth?: number;screenMetrics?: AgentIslandScreenLayoutMetrics | null;+ pillSnapshot?: Pick<AgentIslandPillSnapshot, 'activeSessionCount' | 'sessionCount'> | null;}): number {if (input.expanded) {return input.hasSession ? AGENT_ISLAND_MAX_EXPANDED_WIDTH : AGENT_ISLAND_IDLE_EXPANDED_WIDTH;@@ -497,11 +551,17 @@ export function getAgentIslandDefaultContentWidth(input: {? computeAgentIslandSimulatedNotchWidth(input.displayWidth): AGENT_ISLAND_COMPACT_IDLE_WIDTH);if (input.screenMetrics?.hasNotch) {+ const baseExtra = input.hasSession+ ? AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH+ : AGENT_ISLAND_COMPACT_HARDWARE_IDLE_EXTRA_WIDTH;+ // Both notch sides are symmetric, so a wide badge costs twice its side width.+ const badgeExtra = input.hasSession && input.pillSnapshot+ ? (getAgentIslandCompactBadgeWidth(input.pillSnapshot)+ + AGENT_ISLAND_COMPACT_HARDWARE_BADGE_RESERVED_INSET) * 2+ : 0;return Math.max(AGENT_ISLAND_COMPACT_IDLE_WIDTH,- notchWidth + (input.hasSession- ? AGENT_ISLAND_COMPACT_HARDWARE_ACTIVE_EXTRA_WIDTH- : AGENT_ISLAND_COMPACT_HARDWARE_IDLE_EXTRA_WIDTH),+ notchWidth + Math.max(baseExtra, badgeExtra),);}if (typeof input.displayWidth === 'number' || input.screenMetrics) {@@ -540,24 +600,36 @@ export function snapAgentIslandCompactHardwareContentWidth(input: {maxWidth: number;hasSession: boolean;screenMetrics?: AgentIslandScreenLayoutMetrics | null;+ pillSnapshot?: Pick<AgentIslandPillSnapshot, 'activeSessionCount' | 'sessionCount'> | null;}): number {if (!input.screenMetrics?.hasNotch) {return input.clampedWidth;}const hiddenWidth = Math.min(input.maxWidth, Math.max(1, input.screenMetrics.notchWidth));+ // hidden/basic 的分类必须锚在与徽标无关的 basic 宽度上。否则计数一变多、basic 宽度被撑大后,+ // 用户此前停在 basic 的持久化宽度会突然落到 hidden 阈值以下,整个 compact 岛被收起。+ const baseBasicWidth = Math.min(+ input.maxWidth,+ Math.max(hiddenWidth, getAgentIslandDefaultContentWidth({+ expanded: false,+ hasSession: input.hasSession,+ screenMetrics: input.screenMetrics,+ })),+ );const basicWidth = Math.min(input.maxWidth,Math.max(hiddenWidth, getAgentIslandDefaultContentWidth({expanded: false,hasSession: input.hasSession,screenMetrics: input.screenMetrics,+ pillSnapshot: input.pillSnapshot,})),);- const gap = basicWidth - hiddenWidth;+ const gap = baseBasicWidth - hiddenWidth;if (gap <= 8) {return hiddenWidth;}- const hiddenThreshold = basicWidth - Math.min(+ const hiddenThreshold = baseBasicWidth - Math.min(AGENT_ISLAND_COMPACT_HARDWARE_HIDDEN_PULL_DISTANCE,Math.max(24, gap * 0.5),);