From 5d6ba2f7a995565a133b6b408cf8e49a4013c8f5 Mon Sep 17 00:00:00 2001 From: Kent Wang Date: Tue, 3 Nov 2026 16:09:06 +0800 Subject: [PATCH 1/9] feat(konnect): add debug session api integration Add the Konnect control plane debug session API client (list/start/stop sessions, traces, spans) with typed DebugApiError mapping, and export regionalApiBase for reuse. use insomnia fetch feat(konnect): add debugger hooks, trace utilities and query layer Add trace/session helpers, TanStack Query options for debug sessions, the useKonnectDebuggerSession hook, useServerQueries, the KONNECT_PAT_CHANGE event and the project konnectDebugSessionId field. remove uesless code feat(konnect): implement debugger pane, trace list and trace detail view Add the Konnect debugger response pane with trace list and detail view, wire it into the response/placeholder panes, and let the Konnect settings modal update only the PAT. remove useless code ux refine support new tab add test and refine modal add link --- packages/insomnia-data/src/models/project.ts | 16 + packages/insomnia-data/src/models/types.ts | 9 +- .../__tests__/debug-trace-helper.test.ts | 24 +- .../src/konnect/debug-trace-helper.ts | 34 +- .../src/konnect/route-request-lookup.ts | 48 ++ ...Id.project.$projectId.konnect-debugger.tsx | 39 + .../dropdowns/sidebar-project-dropdown.tsx | 13 + .../modals/konnect-settings-modal.tsx | 18 +- .../panes/konnect-debugger-pane.tsx | 679 ++++++++++++++++++ .../src/ui/components/panes/response-pane.tsx | 21 +- .../insomnia/src/ui/components/tabs/tab.tsx | 11 +- .../src/ui/components/tags/size-tag.tsx | 70 +- .../src/ui/hooks/use-insomnia-navigation.ts | 6 + .../insomnia/src/ui/hooks/use-insomnia-tab.ts | 51 ++ .../ui/hooks/use-konnect-debugger-session.ts | 1 - .../insomnia/src/ui/utils/method-colors.ts | 3 +- 16 files changed, 978 insertions(+), 65 deletions(-) create mode 100644 packages/insomnia/src/konnect/route-request-lookup.ts create mode 100644 packages/insomnia/src/routes/organization.$organizationId.project.$projectId.konnect-debugger.tsx create mode 100644 packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx diff --git a/packages/insomnia-data/src/models/project.ts b/packages/insomnia-data/src/models/project.ts index 122c6bbba208..8356b945c0aa 100644 --- a/packages/insomnia-data/src/models/project.ts +++ b/packages/insomnia-data/src/models/project.ts @@ -114,12 +114,28 @@ export interface GitProject extends BaseModel, CommonProject { remoteId: null; } +export interface KonnectProject extends LocalProject { + konnectControlPlaneId: string | null; + konnectClusterType: string | null; + konnectDeploymentType: KonnectDeploymentType | null; + konnectRegion: string | null; + // Latest Kong Debugger session id for this project (control plane) + konnectDebugSessionId?: string | null; +} + export type Project = LocalProject | RemoteProject | GitProject; export const isProject = (model: Pick): model is Project => model.type === type; export const isProjectId = (id: string | null) => id?.startsWith(`${prefix}_`); +export const isKonnectProject = (project: Project): project is KonnectProject => + isProject(project) && + 'konnectControlPlaneId' in project && + 'konnectRegion' in project && + 'konnectClusterType' in project && + 'konnectDeploymentType' in project; + export const optionalKeys: (keyof CommonProject)[] = [ 'konnectControlPlaneId', 'konnectClusterType', diff --git a/packages/insomnia-data/src/models/types.ts b/packages/insomnia-data/src/models/types.ts index 5f85692a6923..e872566e474d 100644 --- a/packages/insomnia-data/src/models/types.ts +++ b/packages/insomnia-data/src/models/types.ts @@ -81,7 +81,14 @@ export type { ResponseInfo, RunnerResultPerRequestPerIteration, } from './runner-test-result'; -export type { Project, LocalProject, RemoteProject, GitProject, KonnectDeploymentType } from './project'; +export type { + Project, + LocalProject, + RemoteProject, + GitProject, + KonnectProject, + KonnectDeploymentType, +} from './project'; export type { ProjectLintRuleset } from './project-lint-ruleset'; export type { Settings, ThemeSettings } from './settings'; export type { Stats } from './stats'; diff --git a/packages/insomnia/src/konnect/__tests__/debug-trace-helper.test.ts b/packages/insomnia/src/konnect/__tests__/debug-trace-helper.test.ts index b1550316acab..ca2bc78acbd2 100644 --- a/packages/insomnia/src/konnect/__tests__/debug-trace-helper.test.ts +++ b/packages/insomnia/src/konnect/__tests__/debug-trace-helper.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import type { DebugTraceDetail } from '../debug-session-api'; -import { findTraceIdsByRouteId, getRouteIdFromKonnectRouteKey } from '../debug-trace-helper'; +import { getRouteIdFromKonnectRouteKey, getRouteIdsFromTraceDetail } from '../debug-trace-helper'; const detail = (traceId: string, attributes: Record[]): DebugTraceDetail => ({ traceId, @@ -30,18 +30,18 @@ describe('getRouteIdFromKonnectRouteKey', () => { }); }); -describe('findTraceIdsByRouteId', () => { - const details = new Map([ - ['t1', detail('t1', [{ 'http.route': '/a' }, { 'proxy.kong.route.id': 'route-1' }])], - ['t2', detail('t2', [{ 'proxy.kong.route.id': 'route-2' }])], - ['t3', detail('t3', [{}])], - ]); - - it('matches traces having a span with the same proxy.kong.route.id', () => { - expect([...findTraceIdsByRouteId(details, 'route-1')]).toEqual(['t1']); +describe('getRouteIdsFromTraceDetail', () => { + it('collects the distinct proxy.kong.route.id values of the spans', () => { + const traceDetail = detail('t1', [ + { 'http.route': '/a' }, + { 'proxy.kong.route.id': 'route-1' }, + { 'proxy.kong.route.id': 'route-1' }, + { 'proxy.kong.route.id': 'route-2' }, + ]); + expect([...getRouteIdsFromTraceDetail(traceDetail)]).toEqual(['route-1', 'route-2']); }); - it('matches nothing without a route id', () => { - expect(findTraceIdsByRouteId(details, null).size).toBe(0); + it('returns an empty set when no span has a route id', () => { + expect(getRouteIdsFromTraceDetail(detail('t2', [{}])).size).toBe(0); }); }); diff --git a/packages/insomnia/src/konnect/debug-trace-helper.ts b/packages/insomnia/src/konnect/debug-trace-helper.ts index 942288f3abbf..97d0b8ca066e 100644 --- a/packages/insomnia/src/konnect/debug-trace-helper.ts +++ b/packages/insomnia/src/konnect/debug-trace-helper.ts @@ -1,6 +1,16 @@ import type { DebugSession, DebugSpan, DebugTraceDetail, DebugTraceSummary } from './debug-session-api'; export type DebugSessionState = 'active' | 'cancelled' | 'completed' | 'completing' | 'timed_out'; +// Attribute names used in debug traces +export const TRACE_ATTRIBUTE_NAMES = { + HTTP_REQUEST_METHOD: 'http.request.method', + URL_FULL: 'url.full', + HTTP_ROUTE: 'http.route', + HTTP_RESPONSE_STATUS_CODE: 'http.response.status_code', + HTTP_REQUEST_SIZE: 'http.request.size', + HTTP_RESPONSE_SIZE: 'http.response.size', +}; + // Derive the state of a debug session from its response export function deriveSessionState(session: DebugSession): DebugSessionState { if (session.stoppedAt) { @@ -145,6 +155,8 @@ export interface TraceSummaryBreakdown { kongPct: number; upstreamPct: number; clientPct: number; + requestSize: number; + responseSize: number; thirdPartyPct: number; } @@ -189,6 +201,8 @@ export function summarizeTrace(tree: SpanTree): TraceSummaryBreakdown | null { const thirdPartyMs = readMs(span.attributes, LATENCY_ATTRIBUTES.thirdParty) ?? 0; const sum = kongMs + upstreamMs + clientMs + thirdPartyMs; const pct = (value: number) => (sum > 0 ? (value / sum) * 100 : 0); + const requestSize = span.attributes[TRACE_ATTRIBUTE_NAMES.HTTP_REQUEST_SIZE] || 0; + const responseSize = span.attributes[TRACE_ATTRIBUTE_NAMES.HTTP_RESPONSE_SIZE] || 0; return { totalMs: readMs(span.attributes, LATENCY_ATTRIBUTES.total) ?? tree.totalMs, kongMs, @@ -199,6 +213,8 @@ export function summarizeTrace(tree: SpanTree): TraceSummaryBreakdown | null { upstreamPct: pct(upstreamMs), clientPct: pct(clientMs), thirdPartyPct: pct(thirdPartyMs), + requestSize, + responseSize, }; } @@ -230,16 +246,14 @@ export function getRouteIdFromKonnectRouteKey(konnectRouteKey: string | null | u return routeId; } -/** Ids of the traces having a span served by the Kong route `routeId`. */ -export function findTraceIdsByRouteId(details: Map, routeId: string | null): Set { - const matching = new Set(); - if (!routeId) { - return matching; - } - for (const [traceId, detail] of details) { - if (detail.spans.some(span => span.attributes[ROUTE_ID_ATTRIBUTE] === routeId)) { - matching.add(traceId); +// Ids of the Kong routes that served the spans of a trace. +export function getRouteIdsFromTraceDetail(detail: DebugTraceDetail): Set { + const routeIds = new Set(); + for (const span of detail.spans) { + const routeId = span.attributes[ROUTE_ID_ATTRIBUTE]; + if (typeof routeId === 'string') { + routeIds.add(routeId); } } - return matching; + return routeIds; } diff --git a/packages/insomnia/src/konnect/route-request-lookup.ts b/packages/insomnia/src/konnect/route-request-lookup.ts new file mode 100644 index 000000000000..c42b085e23f8 --- /dev/null +++ b/packages/insomnia/src/konnect/route-request-lookup.ts @@ -0,0 +1,48 @@ +import type { GrpcRequest, Request, WebSocketRequest, Workspace, WorkspaceChildrenForScope } from 'insomnia-data'; +import { models } from 'insomnia-data'; + +import { getRouteIdFromKonnectRouteKey } from './debug-trace-helper'; + +export interface KonnectRouteRequest { + request: Request | WebSocketRequest | GrpcRequest; + workspaceId: string; + workspaceName: string; + routeId: string; +} + +// Local requests of the given workspaces that were synced from a Konnect route. +export function listKonnectRouteRequests( + workspaces: Pick[], + childrenByWorkspaceId: ReadonlyMap>, +): KonnectRouteRequest[] { + return workspaces.flatMap(workspace => + (childrenByWorkspaceId.get(workspace._id)?.data.requestsAndGroups ?? []).flatMap(doc => { + if ( + !models.request.isRequest(doc) && + !models.webSocketRequest.isWebSocketRequest(doc) && + !models.grpcRequest.isGrpcRequest(doc) + ) { + return []; + } + const routeId = getRouteIdFromKonnectRouteKey(doc.konnectRouteKey); + return routeId ? [{ request: doc, workspaceId: workspace._id, workspaceName: workspace.name, routeId }] : []; + }), + ); +} + +// Picks the local request for a trace: same Kong route, preferring the one with the trace's HTTP method. +export function findRouteRequestForTrace( + routeRequests: KonnectRouteRequest[], + traceRouteIds: ReadonlySet, + traceMethod: string | null | undefined, +): KonnectRouteRequest | null { + const candidates = routeRequests.filter(candidate => traceRouteIds.has(candidate.routeId)); + const method = traceMethod?.toUpperCase(); + return ( + candidates.find( + candidate => models.request.isRequest(candidate.request) && candidate.request.method.toUpperCase() === method, + ) ?? + candidates[0] ?? + null + ); +} diff --git a/packages/insomnia/src/routes/organization.$organizationId.project.$projectId.konnect-debugger.tsx b/packages/insomnia/src/routes/organization.$organizationId.project.$projectId.konnect-debugger.tsx new file mode 100644 index 000000000000..097fea86f912 --- /dev/null +++ b/packages/insomnia/src/routes/organization.$organizationId.project.$projectId.konnect-debugger.tsx @@ -0,0 +1,39 @@ +import { models, services } from 'insomnia-data'; +import { href, redirect } from 'react-router'; + +import { ErrorBoundary } from '~/ui/components/error-boundary'; +import { KonnectDebuggerPane } from '~/ui/components/panes/konnect-debugger-pane'; +import { OrganizationTabList } from '~/ui/components/tabs/tab-list'; + +import type { Route } from './+types/organization.$organizationId.project.$projectId.konnect-debugger'; + +export async function clientLoader({ params }: Route.ClientLoaderArgs) { + const { organizationId, projectId } = params; + const project = await services.project.getById(projectId); + + if (!project) { + throw redirect(href('/organization/:organizationId', { organizationId })); + } + + // Redirect to the project page if the project is not connected to a Konnect control plane or region. + if (!models.project.isKonnectProject(project)) { + throw redirect(href('/organization/:organizationId/project/:projectId', { organizationId, projectId })); + } + + return { project }; +} + +const Component = ({ loaderData }: Route.ComponentProps) => { + return ( + +
+ +
+ +
+
+
+ ); +}; + +export default Component; diff --git a/packages/insomnia/src/ui/components/dropdowns/sidebar-project-dropdown.tsx b/packages/insomnia/src/ui/components/dropdowns/sidebar-project-dropdown.tsx index aa56b8d1fb2e..acd799c85c5e 100644 --- a/packages/insomnia/src/ui/components/dropdowns/sidebar-project-dropdown.tsx +++ b/packages/insomnia/src/ui/components/dropdowns/sidebar-project-dropdown.tsx @@ -26,6 +26,7 @@ import { AnalyticsEvent } from '~/ui/analytics'; import { ImportModal } from '~/ui/components/modals/import-modal/import-modal'; import { NewWorkspaceModal } from '~/ui/components/modals/new-workspace-modal'; import { exportProjectToFile } from '~/ui/components/settings/import-export'; +import { useOpenKonnectDebuggerTab } from '~/ui/hooks/use-insomnia-tab'; import { Icon } from '../icon'; import { ProjectModal } from '../modals/project-modal'; @@ -84,6 +85,8 @@ export const ProjectDropdown: FC = ({ }); const { workspaceId } = useParams() as { workspaceId?: string }; const [importModalType, setImportModalType] = useState<'file' | 'clipboard' | 'uri' | null>(null); + const openKonnectDebuggerTab = useOpenKonnectDebuggerTab(); + const isKonnectProject = models.project.isKonnectProject(project); const isRemoteProjectInconsistent = models.project.isRemoteProject(project) && !storageRules.enableCloudSync; const isLocalProjectInconsistent = @@ -156,6 +159,16 @@ export const ProjectDropdown: FC = ({ icon: 'trash', action: onDelete, }, + ...(isKonnectProject + ? [ + { + id: 'debugger', + name: 'Start Debugging', + icon: 'bug' as IconProp, + action: () => openKonnectDebuggerTab(organizationId, project._id), + }, + ] + : []), ]; const createInProjectActionList: ProjectActionItem[] = createWorkspaceActionItems({ diff --git a/packages/insomnia/src/ui/components/modals/konnect-settings-modal.tsx b/packages/insomnia/src/ui/components/modals/konnect-settings-modal.tsx index cd761ea43184..4f4931965f32 100644 --- a/packages/insomnia/src/ui/components/modals/konnect-settings-modal.tsx +++ b/packages/insomnia/src/ui/components/modals/konnect-settings-modal.tsx @@ -5,7 +5,7 @@ import { Button, Dialog, Form, Heading, Modal, ModalOverlay } from 'react-aria-c import { database } from '~/common/database'; import { fetchKonnectOrganizationId, validatePat } from '~/konnect/api'; import { AnalyticsEvent } from '~/ui/analytics'; -import uiEventBus, { KONNECT_SYNC_TRIGGER } from '~/ui/event-bus'; +import uiEventBus, { KONNECT_PAT_CHANGE, KONNECT_SYNC_TRIGGER } from '~/ui/event-bus'; import { useRootLoaderData } from '~/ui/hooks/use-root-loader-data'; import { useSettingsPatcher } from '../../hooks/use-request'; @@ -15,6 +15,7 @@ export const KonnectSettingsModal = ({ onClose, onDisconnect, konnectSyncEnabled = true, + onlyUpdateKonnectPat = false, }: { onClose: () => void; onDisconnect?: () => void; @@ -22,6 +23,8 @@ export const KonnectSettingsModal = ({ * when false, mirroring the sidebar's Sync button — connecting a PAT here would validate and * store it but syncing still could not run. */ konnectSyncEnabled?: boolean; + // Whether the modal is only for updating the Konnect PAT, without affecting sync settings. + onlyUpdateKonnectPat?: boolean; }) => { const { settings } = useRootLoaderData()!; const patchSettings = useSettingsPatcher(); @@ -79,9 +82,12 @@ export const KonnectSettingsModal = ({ return; } await window.main.secretStorage.setSecret('konnectPat', trimmed); + uiEventBus.emit(KONNECT_PAT_CHANGE, trimmed); setConnectedPat(trimmed); patchSettings({ hasKonnectPat: true, konnectOrganizationId: orgId ?? null }); - uiEventBus.emit(KONNECT_SYNC_TRIGGER, orgId ?? null); + if (!onlyUpdateKonnectPat) { + uiEventBus.emit(KONNECT_SYNC_TRIGGER, orgId ?? null); + } onClose(); }; @@ -233,7 +239,13 @@ export const KonnectSettingsModal = ({ className="rounded-xs border border-solid border-(--hl-sm) px-3 py-1.5 text-sm text-(--color-font) hover:bg-(--hl-xs) disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50" isDisabled={!pat.trim() || status === 'validating' || isPatUnchanged || !konnectSyncEnabled} > - {status === 'validating' ? : 'Connect & Sync'} + {status === 'validating' ? ( + + ) : onlyUpdateKonnectPat ? ( + 'Update PAT' + ) : ( + 'Connect & Sync' + )} {hasStoredPat && ( + + )} + + {isCapturing && ( + <> + + {hasSession && isActive && `Capturing... ${capturedSecs}s/${debugSession.durationSecs}s`} + {hasSession && isCompleting && 'Wrapping up —— waiting for Konnect to finish the session'} + + + + )} + + + + + {showEmptyState ? ( +
+ {isLoadingDebugSession + ? 'Loading data for existing debugger session…' + : 'Start a debugger session to observe live traffic on this control plane.'} +
+ ) : ( +
+ +
+ {selectedTrace ? ( + + ) : ( +
+ {isActive && traces.length === 0 && ( + <> +
Waiting for the first request...
+
+ Send any request against this control plane now —— results may take a few seconds to appear. +
+ + )} + {traces.length > 0 && 'Select a trace from the list to view its details.'} + {!isActive && traces.length === 0 && 'No traces captured.'} +
+ )} +
+
+ )} + + ); +}; + +const RetryButton = ({ onPress }: { onPress: () => void }) => ( + +); + +const StatusBanner = ({ + type, + children, + action, +}: { + type: 'info' | 'warning' | 'error'; + children: ReactNode; + action?: ReactNode; +}) => ( +
+ + {children} + {action} +
+); + +const StatusBanners = ({ debug }: { debug: ReturnType }) => { + const { debugSession, debugSessionState, hasKonnectPat, authError, retryDebugSession, mutationError } = debug; + const startedAtText = formatStartedAt(debugSession?.startedAt ?? null); + const [isKonnectSettingsModalOpen, setIsKonnectSettingsModalOpen] = useState(false); + const konnectSyncEnabled = useKonnectSyncEnabled(); + + return ( + <> + {!hasKonnectPat && ( + + No Konnect token found. Connect one from the Konnect sync bar in the sidebar. + + )} + {debugSessionState === 'active' && ( + + {startedAtText ? ( + <> + Session started {startedAtText} + + ) : ( + 'Debugger session is in progress' + )} + + )} + {authError && ( + setIsKonnectSettingsModalOpen(true)} + className="flex h-full items-center justify-center gap-2 rounded-md border border-solid border-white/40 px-4 py-2 text-sm text-white transition-colors hover:bg-white/10 aria-pressed:bg-white/10" + > + Configure + + } + > +

{authError.message}

+
+ )} + {mutationError && ( + }> + {mutationError.message} + + )} + {debug.sessionDeleted && ( + Current debug session was deleted in Konnect. + )} + {debugSessionState === 'completing' && Wait for the session to complete.} + {debugSessionState === 'cancelled' && Session cancelled.} + {debugSessionState === 'completed' && Session completed.} + {isKonnectSettingsModalOpen && ( + setIsKonnectSettingsModalOpen(false)} + konnectSyncEnabled={konnectSyncEnabled} + onlyUpdateKonnectPat + /> + )} + + ); +}; + +const TraceList = ({ + traces, + routeRequestByTraceId, + onOpenRequest, + selectedId, + onSelect, + isActive, +}: { + traces: DebugTraceSummary[]; + routeRequestByTraceId: ReadonlyMap; + onOpenRequest: (routeRequest: KonnectRouteRequest) => void; + selectedId: string | null; + onSelect: (id: string) => void; + isActive: boolean; +}) => ( +
+
+
Captured ({traces.length})
+
Whole control plane and results may take a few seconds to appear.
+
+ {traces.length === 0 && isActive &&
Listening for traffic…
} + {traces.map(trace => { + const routeRequest = routeRequestByTraceId.get(trace.traceId); + const isSelected = trace.traceId === selectedId; + const upperTraceMethod = (trace.method || '').toUpperCase(); + return ( +
+ + {routeRequest && ( + + )} + + + +
+ ); + })} +
+); + +const MetadataPane = ({ + projectName, + controlPlaneId, + region, + debugSessionId, +}: { + projectName: string; + controlPlaneId: string | null; + region: string | null; + debugSessionId: string | null; +}) => { + const items: { label: string; value?: string | null; allowCopy?: boolean; copyValue?: string | null }[] = [ + { label: 'Control Plane', value: projectName, copyValue: controlPlaneId, allowCopy: true }, + { label: 'Region', value: region?.toLocaleUpperCase() }, + { label: 'Session ID', value: debugSessionId, allowCopy: true }, + ].filter(item => !!item.value); + + return ( +
+ {items.map(({ label, value, allowCopy = false, copyValue }) => ( +
+
{label}
+
{value}
+ {allowCopy && ( + + + + )} +
+ ))} +
+ ); +}; + +const summaryParts = (summary: TraceSummaryBreakdown) => + [ + { part: 'kong', ms: summary.kongMs, pct: summary.kongPct }, + { part: 'upstream', ms: summary.upstreamMs, pct: summary.upstreamPct }, + { part: 'client', ms: summary.clientMs, pct: summary.clientPct }, + { part: 'third_party', ms: summary.thirdPartyMs, pct: summary.thirdPartyPct }, + ] as const; + +const TraceDetail = ({ + trace, + ctx, + sessionId, +}: { + trace: DebugTraceSummary; + ctx: DebugSessionApiContext; + sessionId: string; +}) => { + const { detail, errorKind, refetch: onRetry } = useKonnectDebuggerSessionTrace(ctx, sessionId, trace.traceId); + const tree = useMemo(() => (detail ? buildSpanTree(detail) : null), [detail]); + const summary = useMemo(() => (tree ? summarizeTrace(tree) : null), [tree]); + const [collapsed, setCollapsed] = useState>(new Set()); + const [expandedAttrs, setExpandedAttrs] = useState>(new Set()); + + const toggle = (set: ReadonlySet, id: string) => { + const next = new Set(set); + if (next.has(id)) { + next.delete(id); + } else { + next.add(id); + } + return next; + }; + + return ( +
+
+ {trace.statusCode !== null && } + + +
+ + {errorKind ? ( +
+ + + {errorKind === 'not_found' ? 'This trace is no longer available.' : 'Could not load this trace.'} + + {errorKind !== 'not_found' && } +
+ ) : !tree ? ( +
Loading trace…
+ ) : tree.roots.length === 0 ? ( +
This trace has no spans.
+ ) : ( + <> + {summary && ( + <> +
+ {summaryParts(summary).map(({ part, pct }) => ( +
+ ))} +
+
+ {summaryParts(summary).map(({ part, ms, pct }) => ( +
+ + {PART_LABEL[part]} + {formatSummaryMs(ms)} + ({pct.toFixed(2)}%) +
+ ))} +
+ + )} + +
+ {flattenVisible(tree.roots, collapsed).map(node => ( + setCollapsed(current => toggle(current, node.span.spanId))} + onToggleAttrs={() => setExpandedAttrs(current => toggle(current, node.span.spanId))} + /> + ))} +
+ + )} +
+ ); +}; + +const SpanRow = ({ + node, + totalMs, + isCollapsed, + isAttrsOpen, + onToggleChildren, + onToggleAttrs, +}: { + node: SpanNode; + totalMs: number; + isCollapsed: boolean; + isAttrsOpen: boolean; + onToggleChildren: () => void; + onToggleAttrs: () => void; +}) => { + const attributes = Object.entries(node.span.attributes); + const left = totalMs > 0 ? (node.startOffsetMs / totalMs) * 100 : 0; + const width = totalMs > 0 ? Math.max((node.durationMs / totalMs) * 100, 0.4) : 0; + return ( +
+
+
+ {node.children.length > 0 ? ( + + ) : ( + + )} + +
+
+
+
+ {formatMs(node.durationMs)} +
+ {isAttrsOpen && attributes.length > 0 && ( +
+ {attributes.map(([key, value]) => ( +
+ {key} + {typeof value === 'string' ? value : JSON.stringify(value)} +
+ ))} +
+ )} +
+ ); +}; diff --git a/packages/insomnia/src/ui/components/panes/response-pane.tsx b/packages/insomnia/src/ui/components/panes/response-pane.tsx index 83c749abc255..f5015f9555fa 100644 --- a/packages/insomnia/src/ui/components/panes/response-pane.tsx +++ b/packages/insomnia/src/ui/components/panes/response-pane.tsx @@ -2,11 +2,13 @@ import type { ResponseTimelineEntry } from 'insomnia-data'; import { services } from 'insomnia-data'; import { PREVIEW_MODE_SOURCE } from 'insomnia-data/common'; import { type FC, useCallback, useEffect, useMemo, useState } from 'react'; -import { Tab, TabList, TabPanel, Tabs, Toolbar } from 'react-aria-components'; -import { useFetcher } from 'react-router'; +import { Button, Tab, TabList, TabPanel, Tabs, Toolbar } from 'react-aria-components'; +import { useFetcher, useParams } from 'react-router'; import { bodyBufferToUtf8 } from '~/common/utils/utf8-bytes'; import { AnalyticsEvent } from '~/ui/analytics'; +import { KongLogo } from '~/ui/components/kong-logo'; +import { useOpenKonnectDebuggerTab } from '~/ui/hooks/use-insomnia-tab'; import { useRootLoaderData } from '~/ui/hooks/use-root-loader-data'; import { getSetCookieHeaders } from '../../../common/misc'; @@ -41,13 +43,19 @@ interface Props { } export const ResponsePane: FC = ({ activeRequestId }) => { + const { organizationId, projectId } = useParams() as { + organizationId: string; + projectId: string; + }; const { activeRequest, activeRequestMeta, activeResponse, responses, requestVersions } = useRequestLoaderData() as RequestLoaderData; const filterHistory = activeRequestMeta.responseFilterHistory || []; const filter = activeRequestMeta.responseFilter || ''; const patchRequestMeta = useRequestMetaPatcher(); const { settings } = useRootLoaderData()!; + const openKonnectDebuggerTab = useOpenKonnectDebuggerTab(); const previewMode = activeRequestMeta.previewMode || PREVIEW_MODE_SOURCE; + const isKonnectRequest = 'konnectRouteKey' in activeRequest && !!activeRequest.konnectRouteKey; const handleSetFilter = async (responseFilter: string) => { if (!activeResponse) { return; @@ -155,6 +163,15 @@ export const ResponsePane: FC = ({ activeRequestId }) => { + {isKonnectRequest && ( + + )}
; } + if (type === 'konnectDebugger') { + return ; + } + if (type === 'testSuite') { return ; } @@ -151,7 +156,11 @@ export const InsomniaTab = ({ tab, fileIssue }: { tab: BaseTab; fileIssue?: Work ref={scrollIntoView} > {({ isSelected, isHovered }) => ( - +
handleAuxClick(e, tab.id)} diff --git a/packages/insomnia/src/ui/components/tags/size-tag.tsx b/packages/insomnia/src/ui/components/tags/size-tag.tsx index 64a2f4a0f8e0..b5483e6a2428 100644 --- a/packages/insomnia/src/ui/components/tags/size-tag.tsx +++ b/packages/insomnia/src/ui/components/tags/size-tag.tsx @@ -10,44 +10,46 @@ interface Props { small?: boolean; className?: string; tooltipDelay?: number; + showTooltip?: boolean; } -export const SizeTag: FC = memo(({ bytesRead, bytesContent, small, className, tooltipDelay }) => { - const responseSizeReadStringShort = misc.describeByteSize(bytesRead); - const responseSizeReadString = misc.describeByteSize(bytesRead, true); - const responseSizeRawString = misc.describeByteSize(bytesContent, true); - const message = ( - - - - - - - {bytesContent >= 0 && ( +export const SizeTag: FC = memo( + ({ bytesRead, bytesContent, small, className, tooltipDelay, showTooltip = true }) => { + const responseSizeReadStringShort = misc.describeByteSize(bytesRead); + const responseSizeReadString = misc.describeByteSize(bytesRead, true); + const responseSizeRawString = misc.describeByteSize(bytesContent, true); + const message = ( +
Read{responseSizeReadString}
+ - - + + + {bytesContent >= 0 && ( + + + + + )} + +
Content{responseSizeRawString}Read{responseSizeReadString}
Content{responseSizeRawString}
+ ); + return ( +
- - ); - return ( -
- - {responseSizeReadStringShort} - -
- ); -}); + > + + {responseSizeReadStringShort} + +
+ ); + }, +); SizeTag.displayName = 'SizeTag'; diff --git a/packages/insomnia/src/ui/hooks/use-insomnia-navigation.ts b/packages/insomnia/src/ui/hooks/use-insomnia-navigation.ts index 9c445030c14d..10b31d3da573 100644 --- a/packages/insomnia/src/ui/hooks/use-insomnia-navigation.ts +++ b/packages/insomnia/src/ui/hooks/use-insomnia-navigation.ts @@ -102,6 +102,12 @@ const NAVIGATION_ROUTES = [ getResourceId: params => params.workspaceId, getResource: (resourceId: string) => services.workspace.getById(resourceId), }, + { + id: 'project:konnect-debugger', + path: '/organization/:organizationId/project/:projectId/konnect-debugger', + getResourceId: params => params.projectId, + getResource: (resourceId: string) => services.project.getById(resourceId), + }, { id: 'project', path: '/organization/:organizationId/project/:projectId', diff --git a/packages/insomnia/src/ui/hooks/use-insomnia-tab.ts b/packages/insomnia/src/ui/hooks/use-insomnia-tab.ts index af979a31668e..9cbe8f2638e8 100644 --- a/packages/insomnia/src/ui/hooks/use-insomnia-tab.ts +++ b/packages/insomnia/src/ui/hooks/use-insomnia-tab.ts @@ -112,6 +112,34 @@ const buildRunnerTab = ({ }; }; +export const buildKonnectDebuggerTabId = (projectId: string) => `konnect_debugger_${projectId}`; + +// The Konnect debugger tab belongs to a project (one global debug session per project), not to a workspace +const buildKonnectDebuggerTab = async ({ + organizationId, + projectId, +}: { + organizationId: string; + projectId: string; +}): Promise => { + const project = await services.project.getById(projectId); + if (!project) { + throw new Error(`Project not found: ${projectId}`); + } + + return { + type: 'konnectDebugger', + id: buildKonnectDebuggerTabId(project._id), + name: 'Debugger', + url: `/organization/${organizationId}/project/${project._id}/konnect-debugger`, + organizationId, + projectId: project._id, + workspaceId: '', + projectName: project.name, + workspaceName: '', + }; +}; + const buildTabUrlFromResource = ({ resource, organizationId, @@ -211,6 +239,12 @@ const buildTabFromNavigation = async ( ): Promise => { const { project, workspace, resource } = await getNavigationResources(); + if (routeInfo.routeId === 'project:konnect-debugger') { + return project + ? await buildKonnectDebuggerTab({ organizationId: routeInfo.organizationId, projectId: project._id }) + : null; + } + if (!project || !workspace || !resource || models.project.isProject(resource)) { return null; } @@ -237,6 +271,10 @@ const buildTabFromNavigation = async ( }; const getNavigationTabId = async (routeInfo?: InsomniaNavigationRouteInfo | null) => { + if (routeInfo?.routeId === 'project:konnect-debugger' && routeInfo.projectId) { + return buildKonnectDebuggerTabId(routeInfo.projectId); + } + if (!routeInfo || !routeInfo.workspaceId || !routeInfo.resourceId) { return null; } @@ -311,6 +349,19 @@ export const useTabNavigate = () => { return tabNavigate; }; +export const useOpenKonnectDebuggerTab = () => { + const navigate = useNavigate(); + const { addTab } = useInsomniaTabContext(); + return useCallback( + async (organizationId: string, projectId: string) => { + const tab = await buildKonnectDebuggerTab({ organizationId, projectId }); + addTab(tab); + navigate(tab.url); + }, + [addTab, navigate], + ); +}; + export const useInsomniaTab = ({ organizationId }: InsomniaTabProps) => { const { appTabsRef, changeActiveTab, closeTabById, addTemporaryTab } = useInsomniaTabContext(); const { routeInfo, getNavigationResources } = useInsomniaNavigation(); diff --git a/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts b/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts index 337cc0fc65bf..857fd58cc3c7 100644 --- a/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts +++ b/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts @@ -105,7 +105,6 @@ export function useKonnectDebuggerSession({ useEffect(() => { if (isDebugSessionMissingFromServer) { - // setDebugSessionMissing(true); setSessionId(null); services.project.update(projectId, { konnectDebugSessionId: null }); } diff --git a/packages/insomnia/src/ui/utils/method-colors.ts b/packages/insomnia/src/ui/utils/method-colors.ts index c62b37acf93d..1f1ddd594e79 100644 --- a/packages/insomnia/src/ui/utils/method-colors.ts +++ b/packages/insomnia/src/ui/utils/method-colors.ts @@ -21,7 +21,8 @@ import { // The themed methods use the existing theme colour families (so they recolour // with the active theme); in the default theme they render as the design hexes: // POST #7ECF2B, PUT #FF9A1F, PATCH #F0E137, DELETE #FF5631, OPTIONS/HEAD #46C1E6. -const METHOD_PILL_CLASSES: Record = { +export const METHOD_PILL_CLASSES: Record = { + [METHOD_GET]: 'bg-(--color-surprise) text-(--color-font-surprise)', [METHOD_POST]: 'bg-(--color-success) text-(--color-font-success)', [METHOD_PUT]: 'bg-(--color-warning) text-(--color-font-warning)', [METHOD_PATCH]: 'bg-(--color-notice) text-(--color-font-notice)', From 7a3306ad9424186e7c5164c90e13e0790bd85364 Mon Sep 17 00:00:00 2001 From: Kent Wang Date: Mon, 9 Nov 2026 17:43:07 +0800 Subject: [PATCH 2/9] add konnect debugger type --- packages/insomnia/src/ui/context/app/insomnia-tab-context.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/insomnia/src/ui/context/app/insomnia-tab-context.tsx b/packages/insomnia/src/ui/context/app/insomnia-tab-context.tsx index 5c18c2e5a8d3..8dcb12321eb0 100644 --- a/packages/insomnia/src/ui/context/app/insomnia-tab-context.tsx +++ b/packages/insomnia/src/ui/context/app/insomnia-tab-context.tsx @@ -14,6 +14,7 @@ export type TabType = | 'document' | 'collection' | 'runner' + | 'konnectDebugger' | 'test' | 'testSuite'; export interface BaseTab { From b129556e81cb208ca8c50cf61baf1ff3692f6a06 Mon Sep 17 00:00:00 2001 From: Kent Wang Date: Mon, 9 Nov 2026 22:21:25 +0800 Subject: [PATCH 3/9] ui enhance --- packages/insomnia/src/konnect/debug-trace-helper.ts | 3 +-- .../src/ui/components/panes/konnect-debugger-pane.tsx | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/insomnia/src/konnect/debug-trace-helper.ts b/packages/insomnia/src/konnect/debug-trace-helper.ts index 97d0b8ca066e..1e472bb83be5 100644 --- a/packages/insomnia/src/konnect/debug-trace-helper.ts +++ b/packages/insomnia/src/konnect/debug-trace-helper.ts @@ -120,7 +120,6 @@ export function buildSpanTree(detail: DebugTraceDetail): SpanTree { } } - // Depth, owner and self time depend on the parent, so fill them in top-down once the tree is linked. const finalize = (node: SpanNode, depth: number) => { node.depth = depth; node.children.sort((a, b) => a.startOffsetMs - b.startOffsetMs); @@ -133,7 +132,7 @@ export function buildSpanTree(detail: DebugTraceDetail): SpanTree { return { roots, totalMs }; } -/** Depth-first rows for the waterfall, skipping the children of collapsed spans. */ +// Depth-first rows for the waterfall, skipping the children of collapsed spans. export function flattenVisible(roots: SpanNode[], collapsed: ReadonlySet): SpanNode[] { const result: SpanNode[] = []; const visit = (node: SpanNode) => { diff --git a/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx b/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx index ff68479f3623..22d524356890 100644 --- a/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx +++ b/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx @@ -410,7 +410,7 @@ const TraceList = ({ isActive: boolean; }) => (
-
+
Captured ({traces.length})
Whole control plane and results may take a few seconds to appear.
@@ -423,7 +423,7 @@ const TraceList = ({
Date: Wed, 11 Nov 2026 17:30:00 +0800 Subject: [PATCH 4/9] fix debug session error display ui --- .../insomnia/src/konnect/debug-session-api.ts | 2 +- .../src/konnect/debug-trace-helper.ts | 26 ++++ .../panes/konnect-debugger-pane.tsx | 115 +++++++++++++----- .../ui/hooks/use-konnect-debugger-session.ts | 11 +- 4 files changed, 115 insertions(+), 39 deletions(-) diff --git a/packages/insomnia/src/konnect/debug-session-api.ts b/packages/insomnia/src/konnect/debug-session-api.ts index 73de0510b076..22f9f84c8000 100644 --- a/packages/insomnia/src/konnect/debug-session-api.ts +++ b/packages/insomnia/src/konnect/debug-session-api.ts @@ -85,7 +85,7 @@ export async function toDebugApiError(err: unknown): Promise { ); } const responseText = response.bodyUsed ? err.message || `HTTP ${status}` : await response.text(); - throw new DebugApiError('unknown', `Konnect error: ${responseText}`); + throw new DebugApiError('unknown', `${responseText}`); } const message = err instanceof Error ? err.message : 'Could not reach Konnect.'; return new DebugApiError('network', message); diff --git a/packages/insomnia/src/konnect/debug-trace-helper.ts b/packages/insomnia/src/konnect/debug-trace-helper.ts index 1e472bb83be5..ab1628278904 100644 --- a/packages/insomnia/src/konnect/debug-trace-helper.ts +++ b/packages/insomnia/src/konnect/debug-trace-helper.ts @@ -256,3 +256,29 @@ export function getRouteIdsFromTraceDetail(detail: DebugTraceDetail): Set { + try { + const json = JSON.parse(message); + if (!json || typeof json !== 'object' || Array.isArray(json)) { + return null; + } + const title = typeof json.title === 'string' ? json.title : ''; + const detail = typeof json.detail === 'string' ? json.detail : ''; + if (!title && !detail) { + return null; + } + const instance = typeof json.instance === 'string' ? json.instance : undefined; + return { title, detail, traceId: instance, raw: JSON.stringify(json, null, 2) }; + } catch { + return null; + } +}; diff --git a/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx b/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx index 22d524356890..4b7fb7326c47 100644 --- a/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx +++ b/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx @@ -9,6 +9,7 @@ import { flattenVisible, getRouteIdsFromTraceDetail, getTracePath, + parseKonnectError, type SpanNode, summarizeTrace, type TraceSummaryBreakdown, @@ -173,6 +174,8 @@ export const KonnectDebuggerPane = ({ project: currentProject }: { project: Konn const hasSession = !!debugSession; const showEmptyState = !hasSession && !isStartingOrStopping; + const reRunDebugSession = () => startDebugSession(durationSecs); + return (
- +
{!isCapturing && ( <> @@ -300,6 +303,35 @@ export const KonnectDebuggerPane = ({ project: currentProject }: { project: Konn ); }; +const MutationErrorMessage = ({ message }: { message: string }) => { + const parsed = useMemo(() => parseKonnectError(message), [message]); + const [expanded, setExpanded] = useState(false); + + if (!parsed) { + return `Konnect error: ${message}`; + } + + return ( +
+ {parsed.title &&

{parsed.title}

} +

{parsed.detail}

+ + {expanded && ( +
+          {parsed.raw}
+        
+ )} +
+ ); +}; + const RetryButton = ({ onPress }: { onPress: () => void }) => (
); -const StatusBanners = ({ debug }: { debug: ReturnType }) => { - const { debugSession, debugSessionState, hasKonnectPat, authError, retryDebugSession, mutationError } = debug; +const StatusBanners = ({ + debug, + onRetry, +}: { + debug: ReturnType; + onRetry: () => void; +}) => { + const { debugSession, debugSessionState, debugSessionAction, hasKonnectPat, authError, mutationError } = debug; const startedAtText = formatStartedAt(debugSession?.startedAt ?? null); const [isKonnectSettingsModalOpen, setIsKonnectSettingsModalOpen] = useState(false); const konnectSyncEnabled = useKonnectSyncEnabled(); + if (!hasKonnectPat) { + return ( + + No Konnect token found. Connect one from the Konnect sync bar in the sidebar. + + ); + } + + if (authError) { + return ( + setIsKonnectSettingsModalOpen(true)} + className="flex h-full items-center justify-center gap-2 rounded-md border border-solid border-white/40 px-4 py-2 text-sm text-white transition-colors hover:bg-white/10 aria-pressed:bg-white/10" + > + Configure + + } + > +

{authError.message}

+
+ ); + } + + if (mutationError) { + return ( + }> + + + ); + } + + if (debugSessionAction === 'starting') { + return Starting debug session…; + } return ( <> - {!hasKonnectPat && ( - - No Konnect token found. Connect one from the Konnect sync bar in the sidebar. - - )} {debugSessionState === 'active' && ( {startedAtText ? ( @@ -357,26 +427,7 @@ const StatusBanners = ({ debug }: { debug: ReturnType )} - {authError && ( - setIsKonnectSettingsModalOpen(true)} - className="flex h-full items-center justify-center gap-2 rounded-md border border-solid border-white/40 px-4 py-2 text-sm text-white transition-colors hover:bg-white/10 aria-pressed:bg-white/10" - > - Configure - - } - > -

{authError.message}

-
- )} - {mutationError && ( - }> - {mutationError.message} - - )} + {debug.sessionDeleted && ( Current debug session was deleted in Konnect. )} diff --git a/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts b/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts index 857fd58cc3c7..293d1c48dc77 100644 --- a/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts +++ b/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts @@ -65,7 +65,6 @@ export function useKonnectDebuggerSession({ ); const [sessionId, setSessionId] = useState(konnectDebugSessionId || null); - // const [isDebugSessionMissing, setDebugSessionMissing] = useState(false); const [now, setNow] = useState(() => Date.now()); // Adopt a debug session by updating the query cache, local state, and project data. @@ -148,8 +147,8 @@ export function useKonnectDebuggerSession({ queryClient, ); - const { mutateAsync: startAsync, reset: resetStart } = startMutation; - const { mutateAsync: stopAsync, reset: resetStop } = stopMutation; + const { mutateAsync: startAsync, reset: resetStart, error: startError } = startMutation; + const { mutateAsync: stopAsync, reset: resetStop, error: stopError } = stopMutation; const startDebugSession = useCallback( async (durationSecs: number) => { @@ -183,11 +182,11 @@ export function useKonnectDebuggerSession({ const errors = [ isFetchingDebugSession ? null : debugSessionError, isFetchingTraces ? null : tracesError, - asDebugError(startMutation.error), - asDebugError(stopMutation.error), + asDebugError(startError), + asDebugError(stopError), ]; const authError = errors.find(error => error && AUTH_KINDS.has(error.kind)) ?? null; - const mutationError = asDebugError(startMutation.error) || asDebugError(stopMutation.error); + const mutationError = asDebugError(startError) || asDebugError(stopError); return { ctx, From 53c762b54094e15ebd65d27926ed9e38746b8198 Mon Sep 17 00:00:00 2001 From: Kent Wang Date: Thu, 12 Nov 2026 11:07:32 +0800 Subject: [PATCH 5/9] fix help link url --- packages/insomnia/src/konnect/links.ts | 1 + .../insomnia/src/ui/components/panes/konnect-debugger-pane.tsx | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/insomnia/src/konnect/links.ts b/packages/insomnia/src/konnect/links.ts index 97128b29f170..024f7fe0ff79 100644 --- a/packages/insomnia/src/konnect/links.ts +++ b/packages/insomnia/src/konnect/links.ts @@ -3,6 +3,7 @@ import { getKongDocsOrigin, getKonnectCloudOrigin } from '../common/constants'; export const getPluginHubUrl = () => `${getKongDocsOrigin()}/plugins/`; export const getPluginPriorityDocsUrl = () => `${getKongDocsOrigin()}/gateway/entities/plugin/#plugin-priority`; export const getDeckApplyDocsUrl = () => `${getKongDocsOrigin()}/deck/gateway/apply/`; +export const getDebugSessionsUrl = () => `${getKongDocsOrigin()}/observability/debugger/`; const encodePathSegment = (value: string) => encodeURIComponent(value); diff --git a/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx b/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx index 4b7fb7326c47..11007441812e 100644 --- a/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx +++ b/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx @@ -14,6 +14,7 @@ import { summarizeTrace, type TraceSummaryBreakdown, } from '~/konnect/debug-trace-helper'; +import { getDebugSessionsUrl } from '~/konnect/links'; import { findRouteRequestForTrace, type KonnectRouteRequest, @@ -251,7 +252,7 @@ export const KonnectDebuggerPane = ({ project: currentProject }: { project: Konn - {routeRequest && ( - - )} void; }) => { const { detail, errorKind, refetch: onRetry } = useKonnectDebuggerSessionTrace(ctx, sessionId, trace.traceId); const tree = useMemo(() => (detail ? buildSpanTree(detail) : null), [detail]); const summary = useMemo(() => (tree ? summarizeTrace(tree) : null), [tree]); + const routeRequest = useMemo( + () => (summary ? findRouteRequestForTrace(routeRequests, summary) : null), + [summary, routeRequests], + ); const [collapsed, setCollapsed] = useState>(new Set()); const [expandedAttrs, setExpandedAttrs] = useState>(new Set()); @@ -599,11 +580,20 @@ const TraceDetail = ({ }; return ( -
-
+
+
{trace.statusCode !== null && } + {routeRequest && ( + + )}
{errorKind ? ( @@ -623,7 +613,7 @@ const TraceDetail = ({ {summary && ( <>
@@ -631,7 +621,7 @@ const TraceDetail = ({
))}
-
+
{summaryParts(summary).map(({ part, ms, pct }) => (
@@ -644,7 +634,7 @@ const TraceDetail = ({ )} -
+
{flattenVisible(tree.roots, collapsed).map(node => ( void; }) => { const attributes = Object.entries(node.span.attributes); + const nameRef = useRef(null); const left = totalMs > 0 ? (node.startOffsetMs / totalMs) * 100 : 0; const width = totalMs > 0 ? Math.max((node.durationMs / totalMs) * 100, 0.4) : 0; return (
-
+
{node.children.length > 0 ? ( ) : ( - + )} - + +
{attributes.map(([key, value]) => (
- {key} - {typeof value === 'string' ? value : JSON.stringify(value)} + {key} + + {typeof value === 'string' ? value : JSON.stringify(value)} +
))}
From cb5a0072209130b7c7f49b244fc15f492869e9d7 Mon Sep 17 00:00:00 2001 From: Kent Wang Date: Fri, 13 Nov 2026 11:52:48 +0800 Subject: [PATCH 8/9] Add more elegant way to handle exceptions --- .../insomnia/src/konnect/debug-session-api.ts | 17 ++++--- .../src/konnect/debug-session-query.ts | 2 +- .../panes/konnect-debugger-pane.tsx | 45 +++++++++++++------ .../ui/hooks/use-konnect-debugger-session.ts | 6 +++ 4 files changed, 48 insertions(+), 22 deletions(-) diff --git a/packages/insomnia/src/konnect/debug-session-api.ts b/packages/insomnia/src/konnect/debug-session-api.ts index 22f9f84c8000..c66518ddfa64 100644 --- a/packages/insomnia/src/konnect/debug-session-api.ts +++ b/packages/insomnia/src/konnect/debug-session-api.ts @@ -52,11 +52,13 @@ export type DebugErrorKind = 'unauthorized' | 'forbidden' | 'not_found' | 'rate_ export class DebugApiError extends Error { kind: DebugErrorKind; retryAfterMs?: number; - constructor(kind: DebugErrorKind, message: string, retryAfterMs?: number) { + responseText: string; + constructor(kind: DebugErrorKind, message: string, responseText: string, retryAfterMs?: number) { super(message); this.name = 'DebugApiError'; this.kind = kind; this.retryAfterMs = retryAfterMs; + this.responseText = responseText; } } @@ -67,28 +69,29 @@ export async function toDebugApiError(err: unknown): Promise { if (isApiError(err)) { const status = err.response.status; const response = err.response; + const responseText = response.bodyUsed ? err.message || `HTTP ${status}` : await response.text(); if (status === 401) { - return new DebugApiError('unauthorized', 'Personal access token is invalid or expired.'); + return new DebugApiError('unauthorized', 'Personal access token is invalid or expired.', responseText); } if (status === 403) { - return new DebugApiError('forbidden', 'Personal access token lacks permission for the debugger.'); + return new DebugApiError('forbidden', 'Personal access token lacks permission for the debugger.', responseText); } if (status === 404) { - return new DebugApiError('not_found', 'Not found.'); + return new DebugApiError('not_found', 'Not found.', responseText); } if (status === 429) { const retryAfter = Number.parseInt(err.response.headers.get('Retry-After') ?? '', 10); return new DebugApiError( 'rate_limited', 'Konnect rate limit reached.', + responseText, Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : undefined, ); } - const responseText = response.bodyUsed ? err.message || `HTTP ${status}` : await response.text(); - throw new DebugApiError('unknown', `${responseText}`); + throw new DebugApiError('unknown', `${responseText}`, responseText); } const message = err instanceof Error ? err.message : 'Could not reach Konnect.'; - return new DebugApiError('network', message); + return new DebugApiError('network', message, ''); } async function request( diff --git a/packages/insomnia/src/konnect/debug-session-query.ts b/packages/insomnia/src/konnect/debug-session-query.ts index 6440989477e4..2f37df74e518 100644 --- a/packages/insomnia/src/konnect/debug-session-query.ts +++ b/packages/insomnia/src/konnect/debug-session-query.ts @@ -194,7 +194,7 @@ export async function startOrAdoptDebugSession( ): Promise { const nodeIds = await listNodeIds(ctx); if (nodeIds.length === 0) { - throw new DebugApiError('unknown', 'No data plane nodes are connected to this control plane.'); + throw new DebugApiError('unknown', 'No data plane nodes are connected to this control plane.', ''); } return createDebugSession(ctx, durationSecs, nodeIds); } diff --git a/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx b/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx index e76dc8df0d6e..7b6b5b8f5499 100644 --- a/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx +++ b/packages/insomnia/src/ui/components/panes/konnect-debugger-pane.tsx @@ -3,7 +3,7 @@ import type { KonnectProject, WorkspaceChildrenForScope } from 'insomnia-data'; import { type ReactNode, useMemo, useRef, useState } from 'react'; import { Button, ListBox, ListBoxItem, Popover, Select, SelectValue } from 'react-aria-components'; -import type { DebugSessionApiContext, DebugTraceSummary } from '~/konnect/debug-session-api'; +import type { DebugApiError, DebugSessionApiContext, DebugTraceSummary } from '~/konnect/debug-session-api'; import { buildSpanTree, flattenVisible, @@ -122,6 +122,7 @@ export const KonnectDebuggerPane = ({ project: currentProject }: { project: Konn } = konnectDebuggerSession; const isStartingOrStopping = debugSessionAction !== 'idle'; const isActive = debugSessionState === 'active'; + const isCompleting = debugSessionState === 'completing' || debugSessionState === 'timed_out'; const isCapturing = isActive || isCompleting; @@ -291,8 +292,9 @@ export const KonnectDebuggerPane = ({ project: currentProject }: { project: Konn ); }; -const MutationErrorMessage = ({ message }: { message: string }) => { - const parsed = useMemo(() => parseKonnectError(message), [message]); +const MutationErrorMessage = ({ error }: { error: DebugApiError }) => { + const { responseText, message } = error; + const parsed = useMemo(() => parseKonnectError(responseText), [responseText]); const [expanded, setExpanded] = useState(false); if (!parsed) { @@ -379,14 +381,21 @@ const StatusBanners = ({ type="error" action={ } > -

{authError.message}

+ + {isKonnectSettingsModalOpen && ( + setIsKonnectSettingsModalOpen(false)} + konnectSyncEnabled={konnectSyncEnabled} + onlyUpdateKonnectPat + /> + )} ); } @@ -394,7 +403,7 @@ const StatusBanners = ({ if (mutationError) { return ( }> - + ); } @@ -420,15 +429,23 @@ const StatusBanners = ({ Current debug session was deleted in Konnect. )} {debugSessionState === 'completing' && Wait for the session to complete.} - {debugSessionState === 'cancelled' && Session cancelled.} - {debugSessionState === 'completed' && Session completed.} - {isKonnectSettingsModalOpen && ( - setIsKonnectSettingsModalOpen(false)} - konnectSyncEnabled={konnectSyncEnabled} - onlyUpdateKonnectPat - /> + {debugSessionState === 'cancelled' && ( + + {debug.isRefreshingTraces ? 'Refreshing…' : 'Refresh traces'} + + } + > + Session cancelled. Traces captured before cancelling may still arrive. + )} + {debugSessionState === 'completed' && Session completed.} ); }; diff --git a/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts b/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts index 293d1c48dc77..d70faecf7543 100644 --- a/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts +++ b/packages/insomnia/src/ui/hooks/use-konnect-debugger-session.ts @@ -169,6 +169,10 @@ export function useKonnectDebuggerSession({ await stopAsync().catch(() => {}); }, [ctx, sessionId, stopAsync, resetStart]); + const refreshTraces = useCallback(() => { + refetchTraces(); + }, [refetchTraces]); + const retryDebugSession = useCallback(() => { resetStart(); resetStop(); @@ -204,6 +208,8 @@ export function useKonnectDebuggerSession({ startDebugSession, stopDebugSession, retryDebugSession, + refreshTraces, + isRefreshingTraces: isFetchingTraces, }; } From c0bca981ff798dec7342d11c9d8dc8738e4ac097 Mon Sep 17 00:00:00 2001 From: Kent Wang Date: Fri, 13 Nov 2026 11:56:53 +0800 Subject: [PATCH 9/9] fix from comment --- packages/insomnia/src/konnect/debug-trace-helper.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/insomnia/src/konnect/debug-trace-helper.ts b/packages/insomnia/src/konnect/debug-trace-helper.ts index efd9539ae578..5e529fc2cff7 100644 --- a/packages/insomnia/src/konnect/debug-trace-helper.ts +++ b/packages/insomnia/src/konnect/debug-trace-helper.ts @@ -10,7 +10,6 @@ export const TRACE_ATTRIBUTE_NAMES = { HTTP_REQUEST_SIZE: 'http.request.size', HTTP_RESPONSE_SIZE: 'http.response.size', PROTOCOL: 'network.protocol.name', - METHOD: 'http.request.method', ROUTE_ID: 'proxy.kong.route.id', URL_SCHEME: 'url.scheme', }; @@ -212,7 +211,7 @@ export function summarizeTrace(tree: SpanTree): TraceSummaryBreakdown | null { const requestSize = span.attributes[TRACE_ATTRIBUTE_NAMES.HTTP_REQUEST_SIZE] || 0; const responseSize = span.attributes[TRACE_ATTRIBUTE_NAMES.HTTP_RESPONSE_SIZE] || 0; const protocol = span.attributes[TRACE_ATTRIBUTE_NAMES.PROTOCOL] || ''; - const method = span.attributes[TRACE_ATTRIBUTE_NAMES.METHOD] || ''; + const method = span.attributes[TRACE_ATTRIBUTE_NAMES.HTTP_REQUEST_METHOD] || ''; const routeId = span.attributes[TRACE_ATTRIBUTE_NAMES.ROUTE_ID] || ''; const urlScheme = span.attributes[TRACE_ATTRIBUTE_NAMES.URL_SCHEME] || ''; return {