-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathroute.tsx
More file actions
1912 lines (1802 loc) · 65.5 KB
/
route.tsx
File metadata and controls
1912 lines (1802 loc) · 65.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
ArrowUturnLeftIcon,
BoltSlashIcon,
BookOpenIcon,
ChevronDownIcon,
ChevronRightIcon,
InformationCircleIcon,
LockOpenIcon,
MagnifyingGlassIcon,
MagnifyingGlassMinusIcon,
MagnifyingGlassPlusIcon,
StopCircleIcon,
} from "@heroicons/react/20/solid";
import { useLoaderData, useRevalidator } from "@remix-run/react";
import { type LoaderFunctionArgs, type SerializeFrom, json } from "@remix-run/server-runtime";
import { type Virtualizer } from "@tanstack/react-virtual";
import {
formatDurationMilliseconds,
millisecondsToNanoseconds,
nanosecondsToMilliseconds,
tryCatch,
} from "@trigger.dev/core/v3";
import type { RuntimeEnvironmentType } from "@trigger.dev/database";
import { motion } from "framer-motion";
import { useCallback, useEffect, useRef, useState } from "react";
import { useHotkeys } from "react-hotkeys-hook";
import { redirect } from "remix-typedjson";
import { ChevronExtraSmallDown } from "~/assets/icons/ChevronExtraSmallDown";
import { ChevronExtraSmallUp } from "~/assets/icons/ChevronExtraSmallUp";
import { MoveToTopIcon } from "~/assets/icons/MoveToTopIcon";
import { MoveUpIcon } from "~/assets/icons/MoveUpIcon";
import tileBgPath from "~/assets/images/error-banner-tile@2x.png";
import { DevDisconnectedBanner, useCrossEngineIsConnected } from "~/components/DevPresence";
import { WarmStartIconWithTooltip } from "~/components/WarmStarts";
import { AdminDebugTooltip } from "~/components/admin/debugTooltip";
import { PageBody } from "~/components/layout/AppLayout";
import { Badge } from "~/components/primitives/Badge";
import { Button, LinkButton } from "~/components/primitives/Buttons";
import { CopyableText } from "~/components/primitives/CopyableText";
import { DateTimeShort } from "~/components/primitives/DateTime";
import { Dialog, DialogTrigger } from "~/components/primitives/Dialog";
import { Header3 } from "~/components/primitives/Headers";
import { InfoPanel } from "~/components/primitives/InfoPanel";
import { Input } from "~/components/primitives/Input";
import { NavBar, PageAccessories, PageTitle } from "~/components/primitives/PageHeader";
import { Paragraph } from "~/components/primitives/Paragraph";
import { Popover, PopoverArrowTrigger, PopoverContent } from "~/components/primitives/Popover";
import * as Property from "~/components/primitives/PropertyTable";
import {
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
} from "~/components/primitives/Resizable";
import { ShortcutKey, variants } from "~/components/primitives/ShortcutKey";
import { Slider } from "~/components/primitives/Slider";
import { Switch } from "~/components/primitives/Switch";
import * as Timeline from "~/components/primitives/Timeline";
import { SimpleTooltip } from "~/components/primitives/Tooltip";
import {
TreeView,
type UseTreeStateOutput,
useTree,
} from "~/components/primitives/TreeView/TreeView";
import { type NodesState } from "~/components/primitives/TreeView/reducer";
import { CancelRunDialog } from "~/components/runs/v3/CancelRunDialog";
import { ReplayRunDialog } from "~/components/runs/v3/ReplayRunDialog";
import { getRunFiltersFromSearchParams } from "~/components/runs/v3/RunFilters";
import { RunIcon } from "~/components/runs/v3/RunIcon";
import {
SpanTitle,
eventBackgroundClassName,
eventBorderClassName,
} from "~/components/runs/v3/SpanTitle";
import { TaskRunStatusIcon, runStatusClassNameColor } from "~/components/runs/v3/TaskRunStatus";
import { $replica } from "~/db.server";
import { useDebounce } from "~/hooks/useDebounce";
import { useEnvironment } from "~/hooks/useEnvironment";
import { useEventSource } from "~/hooks/useEventSource";
import { useInitialDimensions } from "~/hooks/useInitialDimensions";
import { useOrganization } from "~/hooks/useOrganizations";
import { useProject } from "~/hooks/useProject";
import { useReplaceSearchParams } from "~/hooks/useReplaceSearchParams";
import { useSearchParams } from "~/hooks/useSearchParam";
import { type Shortcut, useShortcutKeys } from "~/hooks/useShortcutKeys";
import { useHasAdminAccess } from "~/hooks/useUser";
import { findProjectBySlug } from "~/models/project.server";
import { findEnvironmentBySlug } from "~/models/runtimeEnvironment.server";
import { NextRunListPresenter } from "~/presenters/v3/NextRunListPresenter.server";
import { RunEnvironmentMismatchError, RunPresenter } from "~/presenters/v3/RunPresenter.server";
import { clickhouseClient } from "~/services/clickhouseInstance.server";
import { getImpersonationId } from "~/services/impersonation.server";
import { logger } from "~/services/logger.server";
import { getResizableSnapshot } from "~/services/resizablePanel.server";
import { requireUserId } from "~/services/session.server";
import { cn } from "~/utils/cn";
import { lerp } from "~/utils/lerp";
import {
docsPath,
v3BillingPath,
v3RunParamsSchema,
v3RunPath,
v3RunRedirectPath,
v3RunSpanPath,
v3RunStreamingPath,
v3RunsPath,
} from "~/utils/pathBuilder";
import type { SpanOverride } from "~/v3/eventRepository/eventRepository.types";
import { useCurrentPlan } from "../_app.orgs.$organizationSlug/route";
import { SpanView } from "../resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.runs.$runParam.spans.$spanParam/route";
const resizableSettings = {
parent: {
autosaveId: "panel-run-parent",
handleId: "parent-handle",
main: {
id: "run",
min: "100px" as const,
},
inspector: {
id: "inspector",
default: "430px" as const,
min: "50px" as const,
},
},
tree: {
autosaveId: "panel-run-tree",
handleId: "tree-handle",
tree: {
id: "tree",
default: "50%" as const,
min: "50px" as const,
},
timeline: {
id: "timeline",
default: "50%" as const,
min: "50px" as const,
},
},
};
type TraceEvent = NonNullable<SerializeFrom<typeof loader>["trace"]>["events"][0];
type RunsListNavigation = {
runs: Array<{ friendlyId: string; spanId: string }>;
pagination: { next?: string; previous?: string };
prevPageLastRun?: { friendlyId: string; spanId: string; cursor: string };
nextPageFirstRun?: { friendlyId: string; spanId: string; cursor: string };
};
async function getRunsListFromTableState({
tableStateParam,
organizationSlug,
projectParam,
envParam,
runParam,
userId,
}: {
tableStateParam: string | null;
organizationSlug: string;
projectParam: string;
envParam: string;
runParam: string;
userId: string;
}): Promise<RunsListNavigation | null> {
if (!tableStateParam) {
return null;
}
try {
const tableStateSearchParams = new URLSearchParams(decodeURIComponent(tableStateParam));
const filters = getRunFiltersFromSearchParams(tableStateSearchParams);
const project = await findProjectBySlug(organizationSlug, projectParam, userId);
const environment = await findEnvironmentBySlug(project?.id ?? "", envParam, userId);
if (!project || !environment) {
return null;
}
const runsListPresenter = new NextRunListPresenter($replica, clickhouseClient);
const currentPageResult = await runsListPresenter.call(project.organizationId, environment.id, {
userId,
projectId: project.id,
...filters,
pageSize: 25, // Load enough runs to provide navigation context
});
const runsList: RunsListNavigation = {
runs: currentPageResult.runs,
pagination: currentPageResult.pagination,
};
const currentRunIndex = currentPageResult.runs.findIndex((r) => r.friendlyId === runParam);
if (currentRunIndex === 0 && currentPageResult.pagination.previous) {
const prevPageResult = await runsListPresenter.call(project.organizationId, environment.id, {
userId,
projectId: project.id,
...filters,
cursor: currentPageResult.pagination.previous,
direction: "backward",
pageSize: 1, // We only need the last run from the previous page
});
if (prevPageResult.runs.length > 0) {
runsList.prevPageLastRun = {
friendlyId: prevPageResult.runs[0].friendlyId,
spanId: prevPageResult.runs[0].spanId,
cursor: currentPageResult.pagination.previous,
};
}
}
if (
currentRunIndex === currentPageResult.runs.length - 1 &&
currentPageResult.pagination.next
) {
const nextPageResult = await runsListPresenter.call(project.organizationId, environment.id, {
userId,
projectId: project.id,
...filters,
cursor: currentPageResult.pagination.next,
direction: "forward",
pageSize: 1, // We only need the first run from the next page
});
if (nextPageResult.runs.length > 0) {
runsList.nextPageFirstRun = {
friendlyId: nextPageResult.runs[0].friendlyId,
spanId: nextPageResult.runs[0].spanId,
cursor: currentPageResult.pagination.next,
};
}
}
return runsList;
} catch (error) {
logger.error("Error loading runs list from tableState:", { error });
return null;
}
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const userId = await requireUserId(request);
const impersonationId = await getImpersonationId(request);
const { projectParam, organizationSlug, envParam, runParam } = v3RunParamsSchema.parse(params);
const url = new URL(request.url);
const showDebug = url.searchParams.get("showDebug") === "true";
const presenter = new RunPresenter();
const [error, result] = await tryCatch(
presenter.call({
userId,
showDeletedLogs: !!impersonationId,
projectSlug: projectParam,
runFriendlyId: runParam,
environmentSlug: envParam,
showDebug,
})
);
if (error) {
if (error instanceof RunEnvironmentMismatchError) {
throw redirect(
v3RunRedirectPath(
{ slug: organizationSlug },
{ slug: projectParam },
{ friendlyId: runParam }
)
);
}
throw error;
}
//resizable settings
const parent = await getResizableSnapshot(request, resizableSettings.parent.autosaveId);
const tree = await getResizableSnapshot(request, resizableSettings.tree.autosaveId);
const runsList = await getRunsListFromTableState({
tableStateParam: url.searchParams.get("tableState"),
organizationSlug,
projectParam,
envParam,
runParam,
userId,
});
return json({
run: result.run,
trace: result.trace,
maximumLiveReloadingSetting: result.maximumLiveReloadingSetting,
resizable: {
parent,
tree,
},
runsList,
});
};
type LoaderData = SerializeFrom<typeof loader>;
export default function Page() {
const { run, trace, maximumLiveReloadingSetting, runsList } = useLoaderData<typeof loader>();
const organization = useOrganization();
const project = useProject();
const environment = useEnvironment();
const isConnected = useCrossEngineIsConnected({
logCount: trace?.events.length ?? 0,
isCompleted: run.completedAt !== null,
});
const { value } = useSearchParams();
const tableState = decodeURIComponent(value("tableState") ?? "");
const tableStateSearchParams = new URLSearchParams(tableState);
const filters = getRunFiltersFromSearchParams(tableStateSearchParams);
const tabParam = value("tab") ?? undefined;
const spanParam = value("span") ?? undefined;
const [previousRunPath, nextRunPath] = useAdjacentRunPaths({
organization,
project,
environment,
tableState,
run,
runsList,
tabParam,
useSpan: !!spanParam,
});
return (
<>
<NavBar>
<PageTitle
backButton={{
to: v3RunsPath(organization, project, environment, filters),
text: "Runs",
}}
title={
<div className="flex items-center gap-x-0">
<CopyableText
value={run.friendlyId}
variant="text-below"
className="-ml-[0.4375rem] h-6 px-1.5 font-mono text-xs hover:text-text-bright"
/>
{tableState && (
<div className="flex">
<PreviousRunButton to={previousRunPath} />
<NextRunButton to={nextRunPath} />
</div>
)}
</div>
}
/>
{environment.type === "DEVELOPMENT" && <DevDisconnectedBanner isConnected={isConnected} />}
<PageAccessories>
<AdminDebugTooltip>
<Property.Table>
<Property.Item>
<Property.Label>ID</Property.Label>
<Property.Value>{run.id}</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Trace ID</Property.Label>
<Property.Value>{run.traceId}</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Env ID</Property.Label>
<Property.Value>{run.environment.id}</Property.Value>
</Property.Item>
<Property.Item>
<Property.Label>Org ID</Property.Label>
<Property.Value>{run.environment.organizationId}</Property.Value>
</Property.Item>
</Property.Table>
</AdminDebugTooltip>
<LinkButton variant={"docs/small"} LeadingIcon={BookOpenIcon} to={docsPath("/runs")}>
Run docs
</LinkButton>
<Dialog key={`replay-${run.friendlyId}`}>
<DialogTrigger asChild>
<Button
variant="secondary/small"
LeadingIcon={ArrowUturnLeftIcon}
shortcut={{ key: "R" }}
className="pr-2"
>
Replay run
</Button>
</DialogTrigger>
<ReplayRunDialog
runFriendlyId={run.friendlyId}
failedRedirect={v3RunSpanPath(
organization,
project,
environment,
{ friendlyId: run.friendlyId },
{ spanId: run.spanId }
)}
/>
</Dialog>
{run.isFinished ? null : (
<Dialog key={`cancel-${run.friendlyId}`}>
<DialogTrigger asChild>
<Button variant="danger/small" LeadingIcon={StopCircleIcon} shortcut={{ key: "C" }}>
Cancel run…
</Button>
</DialogTrigger>
<CancelRunDialog
runFriendlyId={run.friendlyId}
redirectPath={v3RunSpanPath(
organization,
project,
environment,
{ friendlyId: run.friendlyId },
{ spanId: run.spanId }
)}
/>
</Dialog>
)}
</PageAccessories>
</NavBar>
<PageBody scrollable={false}>
{trace ? (
<TraceView
run={run}
trace={trace}
maximumLiveReloadingSetting={maximumLiveReloadingSetting}
/>
) : (
<NoLogsView run={run} />
)}
</PageBody>
</>
);
}
function shouldLiveReload({
events,
maximumLiveReloadingSetting,
run,
}: {
events: TraceEvent[];
maximumLiveReloadingSetting: number;
run: { completedAt: string | null };
}): boolean {
// We don't live reload if there are a ton of spans/logs
if (events.length > maximumLiveReloadingSetting) return false;
// If the run was completed a while ago, we don't need to live reload anymore
if (run.completedAt && new Date(run.completedAt).getTime() < Date.now() - 30_000) return false;
return true;
}
function TraceView({
run,
trace,
maximumLiveReloadingSetting,
}: Pick<LoaderData, "run" | "trace" | "maximumLiveReloadingSetting">) {
const organization = useOrganization();
const project = useProject();
const environment = useEnvironment();
const { searchParams, replaceSearchParam } = useReplaceSearchParams();
const selectedSpanId = searchParams.get("span") ?? undefined;
if (!trace) {
return <></>;
}
const { events, duration, rootSpanStatus, rootStartedAt, queuedDuration, overridesBySpanId } =
trace;
const changeToSpan = useDebounce((selectedSpan: string) => {
replaceSearchParam("span", selectedSpan, { replace: true });
}, 250);
const isLiveReloading = shouldLiveReload({ events, maximumLiveReloadingSetting, run });
const revalidator = useRevalidator();
const streamedEvents = useEventSource(
v3RunStreamingPath(organization, project, environment, run),
{
event: "message",
disabled: !isLiveReloading,
}
);
useEffect(() => {
if (streamedEvents !== null) {
revalidator.revalidate();
}
// WARNING Don't put the revalidator in the useEffect deps array or bad things will happen
}, [streamedEvents]); // eslint-disable-line react-hooks/exhaustive-deps
const spanOverrides = selectedSpanId ? overridesBySpanId?.[selectedSpanId] : undefined;
// Get the linked run ID for cached spans (map built during RunPresenter walk)
const { linkedRunIdBySpanId } = trace;
const selectedSpanLinkedRunId = selectedSpanId
? linkedRunIdBySpanId?.[selectedSpanId]
: undefined;
return (
<div className={cn("grid h-full max-h-full grid-cols-1 overflow-hidden")}>
<ResizablePanelGroup
autosaveId={resizableSettings.parent.autosaveId}
// snapshot={resizable.parent}
className="h-full max-h-full"
>
<ResizablePanel
id={resizableSettings.parent.main.id}
min={resizableSettings.parent.main.min}
>
<TasksTreeView
selectedId={selectedSpanId}
key={events[0]?.id ?? "-"}
events={events}
onSelectedIdChanged={(selectedSpan) => {
//instantly close the panel if no span is selected
if (!selectedSpan) {
replaceSearchParam("span");
return;
}
changeToSpan(selectedSpan);
}}
totalDuration={duration}
rootSpanStatus={rootSpanStatus}
rootStartedAt={rootStartedAt ? new Date(rootStartedAt) : undefined}
queuedDuration={queuedDuration}
environmentType={run.environment.type}
shouldLiveReload={isLiveReloading}
maximumLiveReloadingSetting={maximumLiveReloadingSetting}
rootRun={run.rootTaskRun}
parentRun={run.parentTaskRun}
isCompleted={run.completedAt !== null}
/>
</ResizablePanel>
<ResizableHandle id={resizableSettings.parent.handleId} />
{selectedSpanId && (
<ResizablePanel
id={resizableSettings.parent.inspector.id}
default={resizableSettings.parent.inspector.default}
min={resizableSettings.parent.inspector.min}
isStaticAtRest
>
{" "}
<SpanView
runParam={run.friendlyId}
spanId={selectedSpanId}
spanOverrides={spanOverrides as SpanOverride | undefined}
closePanel={() => replaceSearchParam("span")}
linkedRunId={selectedSpanLinkedRunId}
/>
</ResizablePanel>
)}
</ResizablePanelGroup>
</div>
);
}
function NoLogsView({ run }: Pick<LoaderData, "run">) {
const plan = useCurrentPlan();
const organization = useOrganization();
const logRetention = plan?.v3Subscription?.plan?.limits.logRetentionDays.number ?? 30;
const completedAt = run.completedAt ? new Date(run.completedAt) : undefined;
const now = new Date();
const daysSinceCompleted = completedAt
? Math.floor((now.getTime() - completedAt.getTime()) / (1000 * 60 * 60 * 24))
: undefined;
const isWithinLogRetention =
daysSinceCompleted !== undefined && daysSinceCompleted <= logRetention;
return (
<div className={cn("grid h-full max-h-full grid-cols-1 overflow-hidden")}>
<ResizablePanelGroup
autosaveId={resizableSettings.parent.autosaveId}
// snapshot={resizable.parent}
className="h-full max-h-full"
>
<ResizablePanel
id={resizableSettings.parent.main.id}
min={resizableSettings.parent.main.min}
>
<div className="grid h-full place-items-center">
{daysSinceCompleted === undefined ? (
<InfoPanel variant="info" icon={InformationCircleIcon} title="We delete old logs">
<Paragraph variant="small">
We tidy up older logs to keep things running smoothly.
</Paragraph>
</InfoPanel>
) : isWithinLogRetention ? (
<InfoPanel
variant="info"
icon={InformationCircleIcon}
title="These logs have been deleted"
>
<Paragraph variant="small">
Your log retention is {logRetention} days but these logs had already been deleted.
From now on only logs from runs that completed {logRetention} days ago will be
deleted.
</Paragraph>
</InfoPanel>
) : daysSinceCompleted <= 30 ? (
<InfoPanel
variant="upgrade"
icon={LockOpenIcon}
iconClassName="text-indigo-500"
title="Unlock longer log retention"
accessory={
<LinkButton to={v3BillingPath(organization)} variant="secondary/small">
Upgrade
</LinkButton>
}
>
<Paragraph variant="small">
The logs for this run have been deleted because the run completed{" "}
{daysSinceCompleted} days ago.
</Paragraph>
<Paragraph variant="small">Upgrade your plan to keep logs for longer.</Paragraph>
</InfoPanel>
) : (
<InfoPanel
variant="info"
icon={InformationCircleIcon}
title="These logs are more than 30 days old"
>
<Paragraph variant="small">
We tidy up older logs to keep things running smoothly.
</Paragraph>
</InfoPanel>
)}
</div>
</ResizablePanel>
<ResizableHandle id={resizableSettings.parent.handleId} />
<ResizablePanel
id={resizableSettings.parent.inspector.id}
default={resizableSettings.parent.inspector.default}
min={resizableSettings.parent.inspector.min}
isStaticAtRest
>
<SpanView runParam={run.friendlyId} spanId={run.spanId} />
</ResizablePanel>
</ResizablePanelGroup>
</div>
);
}
type TasksTreeViewProps = {
events: TraceEvent[];
selectedId?: string;
onSelectedIdChanged: (selectedId: string | undefined) => void;
totalDuration: number;
rootSpanStatus: "executing" | "completed" | "failed";
rootStartedAt: Date | undefined;
queuedDuration: number | undefined;
environmentType: RuntimeEnvironmentType;
shouldLiveReload: boolean;
maximumLiveReloadingSetting: number;
rootRun: {
friendlyId: string;
spanId: string;
} | null;
parentRun: {
friendlyId: string;
spanId: string;
} | null;
isCompleted: boolean;
};
function TasksTreeView({
events,
selectedId,
onSelectedIdChanged,
totalDuration,
rootSpanStatus,
rootStartedAt,
queuedDuration,
environmentType,
shouldLiveReload,
maximumLiveReloadingSetting,
rootRun,
parentRun,
isCompleted,
}: TasksTreeViewProps) {
const isAdmin = useHasAdminAccess();
const [filterText, setFilterText] = useState("");
const [errorsOnly, setErrorsOnly] = useState(false);
const [showDurations, setShowDurations] = useState(true);
const [showQueueTime, setShowQueueTime] = useState(false);
const [scale, setScale] = useState(0);
const [hoveredNodeId, setHoveredNodeId] = useState<string | null>(null);
const [isScrolling, setIsScrolling] = useState(false);
const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const pendingHoverIdRef = useRef<string | null>(null);
useEffect(() => {
return () => {
if (scrollTimeoutRef.current) {
clearTimeout(scrollTimeoutRef.current);
scrollTimeoutRef.current = null;
}
};
}, []);
const parentRef = useRef<HTMLDivElement>(null);
const treeScrollRef = useRef<HTMLDivElement>(null);
const timelineScrollRef = useRef<HTMLDivElement>(null);
const { value, replace } = useSearchParams();
const searchValue = value("showDebug");
const showDebug = searchValue !== undefined ? searchValue === "true" : false;
const displayEvents = events;
const queuedTime = showQueueTime ? undefined : queuedDuration;
const handleHoverChange = useCallback((nodeId: string | null) => {
pendingHoverIdRef.current = nodeId;
if (!isScrolling) {
setHoveredNodeId(nodeId);
}
}, [isScrolling]);
const handleScroll = useCallback((scrollTop: number) => {
setIsScrolling(true);
if (scrollTimeoutRef.current) {
clearTimeout(scrollTimeoutRef.current);
}
scrollTimeoutRef.current = setTimeout(() => {
setIsScrolling(false);
setHoveredNodeId(pendingHoverIdRef.current);
}, 150);
}, []);
const {
nodes,
getTreeProps,
getNodeProps,
toggleNodeSelection,
toggleExpandNode,
expandAllBelowDepth,
toggleExpandLevel,
collapseAllBelowDepth,
selectNode,
scrollToNode,
virtualizer,
} = useTree({
tree: displayEvents,
selectedId,
// collapsedIds,
onSelectedIdChanged,
estimatedRowHeight: () => 32,
parentRef,
filter: {
value: { text: filterText, errorsOnly },
fn: (value, node) => {
const nodePassesErrorTest = (value.errorsOnly && node.data.isError) || !value.errorsOnly;
if (!nodePassesErrorTest) return false;
if (value.text === "") return true;
if (node.data.message.toLowerCase().includes(value.text.toLowerCase())) {
return true;
}
return false;
},
},
});
return (
<div className="grid h-full grid-rows-[2.5rem_1fr_3.25rem] overflow-hidden">
<div className="flex items-center justify-between gap-2 border-b border-grid-dimmed px-2">
<SearchField onChange={setFilterText} />
{isAdmin && (
<Switch
variant="small"
label="Debug"
shortcut={{ modifiers: ["shift"], key: "D" }}
checked={showDebug}
onCheckedChange={(checked) => {
replace({
showDebug: checked ? "true" : "false",
});
}}
/>
)}
<Switch
variant="small"
label="Queue time"
checked={showQueueTime}
onCheckedChange={(e) => setShowQueueTime(e.valueOf())}
shortcut={{ key: "Q" }}
/>
<Switch
variant="small"
label="Errors only"
checked={errorsOnly}
onCheckedChange={(e) => setErrorsOnly(e.valueOf())}
/>
</div>
<ResizablePanelGroup autosaveId={resizableSettings.tree.autosaveId}>
{/* Tree list */}
<ResizablePanel
id={resizableSettings.tree.tree.id}
default={resizableSettings.tree.tree.default}
min={resizableSettings.tree.tree.min}
>
<div className="grid h-full grid-rows-[2rem_1fr] overflow-hidden">
<div className="flex items-center justify-between pl-1 pr-2">
{rootRun || parentRun ? (
<ShowParentOrRootLinks
relationships={{
root: rootRun
? {
friendlyId: rootRun.friendlyId,
spanId: rootRun.spanId,
isParent: parentRun ? rootRun.friendlyId === parentRun.friendlyId : true,
}
: undefined,
parent:
parentRun && rootRun?.friendlyId !== parentRun.friendlyId
? {
friendlyId: parentRun.friendlyId,
spanId: "",
}
: undefined,
}}
/>
) : (
<Paragraph variant="extra-small" className="flex-1 pl-3 text-charcoal-500">
This is the root task
</Paragraph>
)}
<LiveReloadingStatus
rootSpanCompleted={rootSpanStatus !== "executing"}
isLiveReloading={shouldLiveReload}
settingValue={maximumLiveReloadingSetting}
/>
</div>
<TreeView
parentRef={parentRef}
scrollRef={treeScrollRef}
virtualizer={virtualizer}
autoFocus
tree={events}
nodes={nodes}
getNodeProps={getNodeProps}
getTreeProps={getTreeProps}
parentClassName="pl-3"
renderNode={({ node, state, index }) => {
const isHovered = hoveredNodeId === node.id;
return (
<>
<div
className={cn(
"flex h-8 cursor-pointer items-center overflow-hidden rounded-l-sm pr-2",
state.selected
? isHovered
? "bg-grid-bright"
: "bg-grid-dimmed"
: isHovered
? "bg-grid-dimmed"
: "bg-transparent"
)}
onClick={() => {
selectNode(node.id);
}}
onMouseEnter={() => handleHoverChange(node.id)}
onMouseLeave={() => handleHoverChange(null)}
>
<div className="flex h-8 items-center">
{Array.from({ length: node.level }).map((_, index) => (
<TaskLine
key={index}
isError={node.data.isError}
isSelected={state.selected}
/>
))}
<div
className={cn(
"flex h-8 w-4 items-center",
node.hasChildren && "hover:bg-charcoal-600"
)}
onClick={(e) => {
e.stopPropagation();
if (e.altKey) {
if (state.expanded) {
collapseAllBelowDepth(node.level);
} else {
expandAllBelowDepth(node.level);
}
} else {
toggleExpandNode(node.id);
}
scrollToNode(node.id);
}}
>
{node.hasChildren ? (
state.expanded ? (
<ChevronDownIcon className="h-4 w-4 text-charcoal-400" />
) : (
<ChevronRightIcon className="h-4 w-4 text-charcoal-400" />
)
) : (
<div className="h-8 w-4" />
)}
</div>
</div>
<div className="flex w-full items-center justify-between gap-2 pl-1">
<div className="flex items-center gap-1.5 overflow-x-hidden">
<RunIcon
name={node.data.style?.icon}
spanName={node.data.message}
className="size-5 min-h-5 min-w-5"
/>
<NodeText node={node} />
{node.data.isRoot && !rootRun && <Badge variant="extra-small">Root</Badge>}
</div>
<div className="flex items-center gap-1">
<NodeStatusIcon node={node} />
</div>
</div>
</div>
</>
);
}}
onScroll={(scrollTop) => {
handleScroll(scrollTop);
//sync the scroll to the tree
if (timelineScrollRef.current) {
timelineScrollRef.current.scrollTop = scrollTop;
}
}}
/>
</div>
</ResizablePanel>
<ResizableHandle id={resizableSettings.tree.handleId} />
{/* Timeline */}
<ResizablePanel
id={resizableSettings.tree.timeline.id}
default={resizableSettings.tree.timeline.default}
min={resizableSettings.tree.timeline.min}
>
<TimelineView
totalDuration={totalDuration}
scale={scale}
events={events}
rootSpanStatus={rootSpanStatus}
rootStartedAt={rootStartedAt}
queuedDuration={queuedTime}
parentRef={parentRef}
timelineScrollRef={timelineScrollRef}
nodes={nodes}
getNodeProps={getNodeProps}
getTreeProps={getTreeProps}
showDurations={showDurations}
treeScrollRef={treeScrollRef}
virtualizer={virtualizer}
toggleNodeSelection={toggleNodeSelection}
hoveredNodeId={hoveredNodeId}
setHoveredNodeId={setHoveredNodeId}
handleHoverChange={handleHoverChange}
handleScroll={handleScroll}
/>
</ResizablePanel>
</ResizablePanelGroup>
<div className="flex items-center justify-between gap-2 border-t border-grid-dimmed px-4">
<div className="grow @container">
<div className="hidden items-center gap-4 @[48rem]:flex">
<KeyboardShortcuts
expandAllBelowDepth={expandAllBelowDepth}
collapseAllBelowDepth={collapseAllBelowDepth}
toggleExpandLevel={toggleExpandLevel}
setShowDurations={setShowDurations}
/>
</div>
<div className="@[48rem]:hidden">
<Popover>
<PopoverArrowTrigger>Shortcuts</PopoverArrowTrigger>
<PopoverContent
className="min-w-[20rem] overflow-y-auto p-2 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-charcoal-600"
align="start"
>
<Header3 spacing>Keyboard shortcuts</Header3>
<div className="flex flex-col gap-2">
<KeyboardShortcuts
expandAllBelowDepth={expandAllBelowDepth}
collapseAllBelowDepth={collapseAllBelowDepth}
toggleExpandLevel={toggleExpandLevel}
setShowDurations={setShowDurations}
/>
</div>
</PopoverContent>
</Popover>
</div>