Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2af107f91 | ||
|
|
38f46e6971 | ||
|
|
ed0b6119c2 | ||
|
|
b01bf05c50 | ||
|
|
344fca1edc | ||
|
|
c09f491b37 | ||
|
|
c55ae239ff | ||
|
|
ca35205f43 | ||
|
|
2b9cf7d18a | ||
|
|
a2ed9bbb4f | ||
|
|
841bbd9a17 | ||
|
|
55228d4119 | ||
|
|
ebda0b6d28 | ||
|
|
bd079220f8 | ||
|
|
c1281076e6 | ||
|
|
449d7993d1 | ||
|
|
2eaface4b1 |
No files matched your search
@@ -300,7 +300,11 @@ export const layer = Layer.effect(
|
||||
return yield* migrateLegacyCatalog;
|
||||
}
|
||||
if (!(yield* safeStorage.isEncryptionAvailable)) {
|
||||
return Option.none<string>();
|
||||
return yield* new ElectronSafeStorage.ElectronSafeStorageAvailabilityError({
|
||||
cause: new Error(
|
||||
"Safe storage encryption is unavailable; cannot decrypt the existing connection catalog",
|
||||
),
|
||||
});
|
||||
}
|
||||
const decrypted = yield* decodeSecretBytes(document.value.encryptedCatalog).pipe(
|
||||
Effect.flatMap(safeStorage.decryptString),
|
||||
|
||||
@@ -128,58 +128,6 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("queues navigation until the webview registers", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const loadURL = vi.fn(async () => undefined);
|
||||
const listeners = new Map<string, (...args: never[]) => void>();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "about:blank",
|
||||
getTitle: () => "",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
loadURL,
|
||||
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.navigate("tab_pending", "localhost:3200");
|
||||
|
||||
expect(yield* manager.automationStatus("tab_pending")).toEqual({
|
||||
available: false,
|
||||
visible: true,
|
||||
tabId: "tab_pending",
|
||||
url: "http://localhost:3200/",
|
||||
title: "",
|
||||
loading: true,
|
||||
});
|
||||
|
||||
yield* manager.registerWebview("tab_pending", 42);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(loadURL).toHaveBeenCalledOnce();
|
||||
expect(loadURL).toHaveBeenCalledWith("http://localhost:3200/");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -1195,103 +1195,26 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
yield* attachListeners(tabId, wc);
|
||||
runFork(ensureControlSession(wc).pipe(Effect.ignore));
|
||||
const registeredAt = yield* currentIso;
|
||||
const registration = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (!current) {
|
||||
return [
|
||||
Option.none<{ readonly state: PreviewTabState; readonly pendingUrl: string | null }>(),
|
||||
tabs,
|
||||
] as const;
|
||||
}
|
||||
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
|
||||
const next: PreviewTabState = {
|
||||
...current,
|
||||
webContentsId,
|
||||
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
updatedAt: registeredAt,
|
||||
};
|
||||
return [
|
||||
Option.some({
|
||||
state: next,
|
||||
pendingUrl,
|
||||
}),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, next);
|
||||
}),
|
||||
] as const;
|
||||
if (Math.abs(tab.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
|
||||
yield* attempt("registerWebview.restoreZoom", () => wc.setZoomFactor(tab.zoomFactor)).pipe(
|
||||
Effect.ignore,
|
||||
);
|
||||
}
|
||||
yield* update(tabId, {
|
||||
webContentsId,
|
||||
navStatus: computeNavStatus(wc),
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
zoomFactor: tab.zoomFactor,
|
||||
});
|
||||
if (Option.isNone(registration)) {
|
||||
return yield* fail("registerWebview", new PreviewTabNotFoundError(tabId));
|
||||
}
|
||||
const { state: registered, pendingUrl } = registration.value;
|
||||
yield* emit(tabId, registered);
|
||||
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
|
||||
yield* attempt("registerWebview.restoreZoom", () =>
|
||||
wc.setZoomFactor(registered.zoomFactor),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
yield* attempt("registerWebview.sendTheme", () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
const latestNavStatus = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.navStatus;
|
||||
if (
|
||||
pendingUrl &&
|
||||
latestNavStatus?.kind === "Loading" &&
|
||||
latestNavStatus.url === pendingUrl &&
|
||||
wc.getURL() !== pendingUrl
|
||||
) {
|
||||
runFork(
|
||||
attemptPromise("registerWebview.loadPendingUrl", () => wc.loadURL(pendingUrl)).pipe(
|
||||
Effect.ignore,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const navigate = Effect.fn("PreviewManager.navigate")(function* (tabId: string, rawUrl: string) {
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
const url = yield* attempt("navigate.normalizeUrl", () => normalizePreviewUrl(rawUrl));
|
||||
const updatedAt = yield* currentIso;
|
||||
const pending = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
const next: PreviewTabState = {
|
||||
tabId,
|
||||
webContentsId: current?.webContentsId ?? null,
|
||||
navStatus: {
|
||||
kind: "Loading",
|
||||
url,
|
||||
title: current?.navStatus.kind === "Idle" || !current ? "" : current.navStatus.title,
|
||||
},
|
||||
canGoBack: current?.canGoBack ?? false,
|
||||
canGoForward: current?.canGoForward ?? false,
|
||||
zoomFactor: current?.zoomFactor ?? DEFAULT_ZOOM_FACTOR,
|
||||
controller: current?.controller ?? "none",
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
next,
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, next);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
yield* emit(tabId, pending);
|
||||
if (pending.webContentsId == null) return;
|
||||
const wc = webContents.fromId(pending.webContentsId);
|
||||
if (!wc) {
|
||||
const detached = { ...pending, webContentsId: null };
|
||||
yield* SynchronizedRef.update(tabsRef, (tabs) =>
|
||||
tabs.get(tabId)?.webContentsId !== pending.webContentsId
|
||||
? tabs
|
||||
: replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, detached);
|
||||
}),
|
||||
);
|
||||
yield* emit(tabId, detached);
|
||||
return;
|
||||
}
|
||||
if (wc.getURL() === url) {
|
||||
yield* attempt("navigate.reload", () => wc.reload());
|
||||
return;
|
||||
|
||||
@@ -272,26 +272,6 @@ describe("DesktopSavedEnvironments", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("removes saved environment metadata and its embedded secret atomically", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
|
||||
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
|
||||
yield* savedEnvironments.setSecret({
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
});
|
||||
|
||||
yield* savedEnvironments.removeEnvironment(savedRegistryRecord.environmentId);
|
||||
|
||||
assert.deepEqual(yield* savedEnvironments.getRegistry, []);
|
||||
assert.isTrue(
|
||||
Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("treats empty saved environment documents as empty", () =>
|
||||
withSavedEnvironments(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -121,9 +121,6 @@ export interface DesktopSavedEnvironmentsShape {
|
||||
readonly setRegistry: (
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
readonly removeEnvironment: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<void, DesktopSavedEnvironmentsWriteError>;
|
||||
readonly getSecret: (
|
||||
environmentId: string,
|
||||
) => Effect.Effect<Option.Option<string>, DesktopSavedEnvironmentsGetSecretError>;
|
||||
@@ -296,23 +293,6 @@ export const layer = Layer.effect(
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
yield* writeDocument(preserveExistingSecrets(currentDocument, records));
|
||||
}),
|
||||
removeEnvironment: Effect.fn("desktop.savedEnvironments.removeEnvironment")(
|
||||
function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
fileSystem,
|
||||
environment.savedEnvironmentRegistryPath,
|
||||
).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
if (!document.records.some((record) => record.environmentId === environmentId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writeDocument({
|
||||
version: document.version,
|
||||
records: document.records.filter((record) => record.environmentId !== environmentId),
|
||||
});
|
||||
},
|
||||
),
|
||||
getSecret: Effect.fn("desktop.savedEnvironments.getSecret")(function* (environmentId) {
|
||||
yield* Effect.annotateCurrentSpan({ environmentId });
|
||||
const document = yield* readRegistryDocument(
|
||||
@@ -405,18 +385,6 @@ export const layerTest = (input?: {
|
||||
return DesktopSavedEnvironments.of({
|
||||
getRegistry: Ref.get(recordsRef),
|
||||
setRegistry: (records) => Ref.set(recordsRef, records),
|
||||
removeEnvironment: (environmentId) =>
|
||||
Ref.update(recordsRef, (records) =>
|
||||
records.filter((record) => record.environmentId !== environmentId),
|
||||
).pipe(
|
||||
Effect.andThen(
|
||||
Ref.update(secretsRef, (secrets) => {
|
||||
const nextSecrets = new Map(secrets);
|
||||
nextSecrets.delete(environmentId);
|
||||
return nextSecrets;
|
||||
}),
|
||||
),
|
||||
),
|
||||
getSecret: (environmentId) =>
|
||||
Ref.get(secretsRef).pipe(
|
||||
Effect.map((secrets) => Option.fromNullishOr(secrets.get(environmentId))),
|
||||
|
||||
@@ -70,12 +70,7 @@ static void T3MarkdownTextApplyAttachments(
|
||||
renderingMode:UIImageRenderingModeAlwaysOriginal];
|
||||
}
|
||||
attachment.image = image ?: [[UIImage alloc] init];
|
||||
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
|
||||
attachment.bounds = CGRectMake(
|
||||
0,
|
||||
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
|
||||
attachmentSize,
|
||||
attachmentSize);
|
||||
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
|
||||
const NSRange range = NSMakeRange(
|
||||
attachmentRange.location,
|
||||
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
|
||||
@@ -85,6 +80,104 @@ static void T3MarkdownTextApplyAttachments(
|
||||
}
|
||||
}
|
||||
|
||||
static NSArray<NSDictionary<NSString *, id> *> *T3MarkdownTextExtractChipBackgrounds(
|
||||
NSMutableAttributedString *attributedString,
|
||||
const std::vector<T3MarkdownTextChipRange> &chipRanges)
|
||||
{
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *backgrounds = [NSMutableArray array];
|
||||
for (const auto &chipRange : chipRanges) {
|
||||
if (chipRange.length == 0 || chipRange.location >= attributedString.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const NSRange range = NSMakeRange(
|
||||
chipRange.location,
|
||||
MIN(chipRange.length, attributedString.length - chipRange.location));
|
||||
UIColor *color = [attributedString attribute:NSBackgroundColorAttributeName
|
||||
atIndex:range.location
|
||||
effectiveRange:nil];
|
||||
UIColor *foregroundColor = [attributedString attribute:NSForegroundColorAttributeName
|
||||
atIndex:range.location
|
||||
effectiveRange:nil];
|
||||
if (color == nil) {
|
||||
continue;
|
||||
}
|
||||
[backgrounds addObject:@{
|
||||
@"range": [NSValue valueWithRange:range],
|
||||
@"color": color,
|
||||
@"strokeColor": [foregroundColor
|
||||
colorWithAlphaComponent:chipRange.isSkill ? 0.25 : 0.1] ?: UIColor.clearColor,
|
||||
}];
|
||||
[attributedString removeAttribute:NSBackgroundColorAttributeName range:range];
|
||||
}
|
||||
return backgrounds;
|
||||
}
|
||||
|
||||
@interface T3MarkdownTextBackingView : UITextView
|
||||
@property(nonatomic, copy) NSArray<NSDictionary<NSString *, id> *> *chipBackgrounds;
|
||||
@end
|
||||
|
||||
@implementation T3MarkdownTextBackingView
|
||||
|
||||
- (void)drawRect:(CGRect)rect
|
||||
{
|
||||
[self.layoutManager ensureLayoutForTextContainer:self.textContainer];
|
||||
CGContextRef context = UIGraphicsGetCurrentContext();
|
||||
if (context != nil) {
|
||||
CGContextSaveGState(context);
|
||||
CGContextResetClip(context);
|
||||
CGContextClipToRect(context, self.bounds);
|
||||
}
|
||||
for (NSDictionary<NSString *, id> *background in self.chipBackgrounds) {
|
||||
const NSRange characterRange = [background[@"range"] rangeValue];
|
||||
UIColor *color = background[@"color"];
|
||||
UIColor *strokeColor = background[@"strokeColor"];
|
||||
if (characterRange.length == 0 || NSMaxRange(characterRange) > self.textStorage.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const NSRange glyphRange =
|
||||
[self.layoutManager glyphRangeForCharacterRange:characterRange actualCharacterRange:nil];
|
||||
[color setFill];
|
||||
[self.layoutManager
|
||||
enumerateEnclosingRectsForGlyphRange:glyphRange
|
||||
withinSelectedGlyphRange:NSMakeRange(NSNotFound, 0)
|
||||
inTextContainer:self.textContainer
|
||||
usingBlock:^(CGRect glyphRect, BOOL *stop) {
|
||||
const CGFloat chipHeight = 22;
|
||||
CGRect chipRect = CGRectMake(
|
||||
glyphRect.origin.x - 4,
|
||||
CGRectGetMidY(glyphRect) - chipHeight / 2,
|
||||
glyphRect.size.width + 8,
|
||||
chipHeight);
|
||||
chipRect.origin.x += self.textContainerInset.left;
|
||||
chipRect.origin.y += self.textContainerInset.top;
|
||||
const CGFloat minimumX = self.textContainerInset.left + 0.5;
|
||||
const CGFloat maximumX =
|
||||
CGRectGetWidth(self.bounds) - self.textContainerInset.right - 0.5;
|
||||
if (chipRect.origin.x < minimumX) {
|
||||
chipRect.size.width -= minimumX - chipRect.origin.x;
|
||||
chipRect.origin.x = minimumX;
|
||||
}
|
||||
if (CGRectGetMaxX(chipRect) > maximumX) {
|
||||
chipRect.size.width = MAX(0, maximumX - chipRect.origin.x);
|
||||
}
|
||||
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:chipRect cornerRadius:6];
|
||||
[path fill];
|
||||
[strokeColor setStroke];
|
||||
path.lineWidth = 1;
|
||||
[path stroke];
|
||||
}];
|
||||
}
|
||||
if (context != nil) {
|
||||
CGContextRestoreGState(context);
|
||||
}
|
||||
|
||||
[super drawRect:rect];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@protocol T3MarkdownOutsideTapTarget <NSObject>
|
||||
- (void)clearSelectionForOutsideTapWithHitView:(UIView *)hitView;
|
||||
@end
|
||||
@@ -192,7 +285,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
|
||||
|
||||
@implementation T3MarkdownText {
|
||||
UIView * _view;
|
||||
UITextView * _textView;
|
||||
T3MarkdownTextBackingView * _textView;
|
||||
T3MarkdownTextShadowNode::ConcreteState::Shared _state;
|
||||
__weak UIWindow * _outsideTapWindow;
|
||||
BOOL _suppressSelectionChange;
|
||||
@@ -215,7 +308,7 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
|
||||
self.contentView = _view;
|
||||
self.clipsToBounds = true;
|
||||
|
||||
_textView = [[UITextView alloc] init];
|
||||
_textView = [[T3MarkdownTextBackingView alloc] init];
|
||||
_attachmentImages = [[NSMutableDictionary alloc] init];
|
||||
_pendingAttachmentUris = [[NSMutableSet alloc] init];
|
||||
_textView.scrollEnabled = false;
|
||||
@@ -312,6 +405,9 @@ T3MarkdownOutsideTapCoordinatorForWindow(UIWindow *window)
|
||||
convertedAttrString,
|
||||
_state->getData().attachmentRanges,
|
||||
_attachmentImages);
|
||||
_textView.chipBackgrounds = T3MarkdownTextExtractChipBackgrounds(
|
||||
convertedAttrString,
|
||||
_state->getData().chipRanges);
|
||||
[self loadAttachmentImages:_state->getData().attachmentRanges];
|
||||
|
||||
// Setting attributedText clears any active text selection, and re-assigning
|
||||
|
||||
@@ -28,20 +28,18 @@ struct T3MarkdownTextAttachmentRange {
|
||||
std::string imageUri;
|
||||
};
|
||||
|
||||
inline Float T3MarkdownTextAttachmentSize(const T3MarkdownTextAttachmentRange &) {
|
||||
return 14;
|
||||
}
|
||||
|
||||
inline Float T3MarkdownTextAttachmentBaselineOffset(
|
||||
const T3MarkdownTextAttachmentRange &) {
|
||||
return -2;
|
||||
}
|
||||
struct T3MarkdownTextChipRange {
|
||||
size_t location;
|
||||
size_t length;
|
||||
bool isSkill;
|
||||
};
|
||||
|
||||
class T3MarkdownTextStateReal final {
|
||||
public:
|
||||
AttributedString attributedString;
|
||||
std::vector<T3MarkdownTextParagraphStyleRange> paragraphStyleRanges;
|
||||
std::vector<T3MarkdownTextAttachmentRange> attachmentRanges;
|
||||
std::vector<T3MarkdownTextChipRange> chipRanges;
|
||||
};
|
||||
|
||||
class T3MarkdownTextShadowNode final : public ConcreteViewShadowNode<
|
||||
@@ -74,5 +72,6 @@ private:
|
||||
mutable AttributedString _attributedString;
|
||||
mutable std::vector<T3MarkdownTextParagraphStyleRange> _paragraphStyleRanges;
|
||||
mutable std::vector<T3MarkdownTextAttachmentRange> _attachmentRanges;
|
||||
mutable std::vector<T3MarkdownTextChipRange> _chipRanges;
|
||||
};
|
||||
} // namespace facebook::React
|
||||
@@ -9,8 +9,9 @@
|
||||
namespace facebook::react {
|
||||
|
||||
static constexpr Float ParagraphStyleEncodingOffset = 1000;
|
||||
static constexpr auto FileAttachmentNativeIdPrefix = "t3-file:";
|
||||
static constexpr auto SkillAttachmentNativeIdPrefix = "t3-skill:";
|
||||
static constexpr auto ChipNativeIdPrefix = "t3-chip-";
|
||||
static constexpr auto FileChipNativeIdPrefix = "t3-chip-file:";
|
||||
static constexpr auto SkillChipNativeIdPrefix = "t3-chip-skill:";
|
||||
|
||||
static void applyParagraphStyles(
|
||||
NSMutableAttributedString *attributedString,
|
||||
@@ -57,12 +58,7 @@ static void applyAttachments(
|
||||
|
||||
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
|
||||
attachment.image = [[UIImage alloc] init];
|
||||
const CGFloat attachmentSize = T3MarkdownTextAttachmentSize(attachmentRange);
|
||||
attachment.bounds = CGRectMake(
|
||||
0,
|
||||
T3MarkdownTextAttachmentBaselineOffset(attachmentRange),
|
||||
attachmentSize,
|
||||
attachmentSize);
|
||||
attachment.bounds = CGRectMake(0, -0.5, 10, 10);
|
||||
const NSRange range = NSMakeRange(
|
||||
attachmentRange.location,
|
||||
MIN(attachmentRange.length, attributedString.length - attachmentRange.location));
|
||||
@@ -95,6 +91,7 @@ Size T3MarkdownTextShadowNode::measureContent(
|
||||
auto baseAttributedString = AttributedString{};
|
||||
auto paragraphStyleRanges = std::vector<T3MarkdownTextParagraphStyleRange>{};
|
||||
auto attachmentRanges = std::vector<T3MarkdownTextAttachmentRange>{};
|
||||
auto chipRanges = std::vector<T3MarkdownTextChipRange>{};
|
||||
size_t utf16Offset = 0;
|
||||
const auto &children = getChildren();
|
||||
for (size_t i = 0; i < children.size(); i++) {
|
||||
@@ -187,19 +184,25 @@ Size T3MarkdownTextShadowNode::measureContent(
|
||||
props.shadowRadius - ParagraphStyleEncodingOffset,
|
||||
});
|
||||
}
|
||||
if (props.nativeId.rfind(FileAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
|
||||
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
|
||||
if (props.nativeId.rfind(ChipNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
|
||||
chipRanges.push_back(T3MarkdownTextChipRange{
|
||||
utf16Offset,
|
||||
fragmentLength,
|
||||
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0,
|
||||
});
|
||||
}
|
||||
if (props.nativeId.rfind(FileChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
|
||||
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
|
||||
utf16Offset + 1,
|
||||
1,
|
||||
props.nativeId.substr(std::char_traits<char>::length(FileAttachmentNativeIdPrefix)),
|
||||
props.nativeId.substr(std::char_traits<char>::length(FileChipNativeIdPrefix)),
|
||||
});
|
||||
} else if (
|
||||
props.nativeId.rfind(SkillAttachmentNativeIdPrefix, 0) == 0 && fragmentLength > 0) {
|
||||
props.nativeId.rfind(SkillChipNativeIdPrefix, 0) == 0 && fragmentLength > 1) {
|
||||
attachmentRanges.push_back(T3MarkdownTextAttachmentRange{
|
||||
utf16Offset,
|
||||
utf16Offset + 1,
|
||||
1,
|
||||
props.nativeId.substr(
|
||||
std::char_traits<char>::length(SkillAttachmentNativeIdPrefix)),
|
||||
props.nativeId.substr(std::char_traits<char>::length(SkillChipNativeIdPrefix)),
|
||||
});
|
||||
}
|
||||
utf16Offset += fragmentLength;
|
||||
@@ -210,6 +213,7 @@ Size T3MarkdownTextShadowNode::measureContent(
|
||||
_attributedString = baseAttributedString;
|
||||
_paragraphStyleRanges = paragraphStyleRanges;
|
||||
_attachmentRanges = attachmentRanges;
|
||||
_chipRanges = chipRanges;
|
||||
|
||||
NSMutableAttributedString *convertedAttributedString =
|
||||
[RCTNSAttributedStringFromAttributedString(baseAttributedString) mutableCopy];
|
||||
@@ -259,6 +263,7 @@ void T3MarkdownTextShadowNode::layout(LayoutContext layoutContext) {
|
||||
_attributedString,
|
||||
_paragraphStyleRanges,
|
||||
_attachmentRanges,
|
||||
_chipRanges,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -40,13 +40,11 @@ function documentFor(node: MarkdownNode): MarkdownNode {
|
||||
function SelectableNode(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -314,7 +312,6 @@ function collectTableRows(node: MarkdownNode): MarkdownNode[] {
|
||||
function NativeTable(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
const rows = collectTableRows(props.node);
|
||||
return (
|
||||
@@ -354,7 +351,6 @@ function NativeTable(props: {
|
||||
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
|
||||
)}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
</View>
|
||||
))}
|
||||
@@ -368,17 +364,10 @@ function NativeTable(props: {
|
||||
function NativeMarkdownImage(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
const href = props.node.href;
|
||||
if (!href) {
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -437,7 +426,6 @@ function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
|
||||
function NativeMixedParagraph(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<View style={{ gap: 8 }}>
|
||||
@@ -447,15 +435,9 @@ function NativeMixedParagraph(props: {
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<SelectableNode
|
||||
key={nodeKey(child, index)}
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
<SelectableNode key={nodeKey(child, index)} node={child} textStyle={props.textStyle} />
|
||||
),
|
||||
)}
|
||||
</View>
|
||||
@@ -466,7 +448,6 @@ function NativeList(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
readonly depth: number;
|
||||
}) {
|
||||
const ordered = props.node.ordered ?? false;
|
||||
@@ -527,7 +508,6 @@ function NativeList(props: {
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={props.depth + 1}
|
||||
compact
|
||||
/>
|
||||
@@ -544,7 +524,6 @@ export function NativeMarkdownBlock(props: {
|
||||
readonly node: MarkdownNode;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
readonly depth?: number;
|
||||
readonly compact?: boolean;
|
||||
}) {
|
||||
@@ -559,7 +538,6 @@ export function NativeMarkdownBlock(props: {
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={depth}
|
||||
/>
|
||||
))}
|
||||
@@ -575,21 +553,9 @@ export function NativeMarkdownBlock(props: {
|
||||
/>
|
||||
);
|
||||
case "table":
|
||||
return (
|
||||
<NativeTable
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
return <NativeTable node={props.node} textStyle={props.textStyle} />;
|
||||
case "image":
|
||||
return (
|
||||
<NativeMarkdownImage
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
return <NativeMarkdownImage node={props.node} textStyle={props.textStyle} />;
|
||||
case "horizontal_rule":
|
||||
return (
|
||||
<View
|
||||
@@ -617,7 +583,6 @@ export function NativeMarkdownBlock(props: {
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={depth}
|
||||
compact
|
||||
/>
|
||||
@@ -630,23 +595,14 @@ export function NativeMarkdownBlock(props: {
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={depth}
|
||||
/>
|
||||
);
|
||||
case "paragraph":
|
||||
return (props.node.children ?? []).some((child) => child.type === "image") ? (
|
||||
<NativeMixedParagraph
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
<NativeMixedParagraph node={props.node} textStyle={props.textStyle} />
|
||||
) : (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
<SelectableNode node={props.node} textStyle={props.textStyle} />
|
||||
);
|
||||
case "html_block":
|
||||
case "math_block":
|
||||
@@ -662,11 +618,7 @@ export function NativeMarkdownBlock(props: {
|
||||
: "transparent",
|
||||
}}
|
||||
>
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
<SelectableNode node={props.node} textStyle={props.textStyle} />
|
||||
</View>
|
||||
);
|
||||
case "table_head":
|
||||
@@ -683,7 +635,6 @@ export function NativeMarkdownBlock(props: {
|
||||
node={child}
|
||||
textStyle={props.textStyle}
|
||||
highlightCode={props.highlightCode}
|
||||
onLinkPress={props.onLinkPress}
|
||||
depth={depth}
|
||||
compact
|
||||
/>
|
||||
@@ -691,12 +642,6 @@ export function NativeMarkdownBlock(props: {
|
||||
</View>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<SelectableNode
|
||||
node={props.node}
|
||||
textStyle={props.textStyle}
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
return <SelectableNode node={props.node} textStyle={props.textStyle} />;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,61 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Asset } from "expo-asset";
|
||||
import { Image, Linking, type TextStyle, useColorScheme } from "react-native";
|
||||
|
||||
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
|
||||
import { markdownFileIconSource } from "./markdownFileIcons";
|
||||
import type { MarkdownFileIcon } from "./markdownLinks";
|
||||
import type { NativeMarkdownTextRun } from "./nativeMarkdownText";
|
||||
import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
|
||||
|
||||
const EXTERNAL_LINK_PREFIX = "◉ ";
|
||||
const INLINE_ATTACHMENT_PREFIX = "\uFFFC\u00A0";
|
||||
const FILE_LINK_PREFIX = "\u00A0\uFFFC\u00A0";
|
||||
const CHIP_SUFFIX = "\u00A0";
|
||||
const SKILL_ICON_PLACEHOLDER = "\uFFFC";
|
||||
const PARAGRAPH_STYLE_ENCODING_OFFSET = 1000;
|
||||
|
||||
function useFileIconUris(runs: ReadonlyArray<NativeMarkdownTextRun>) {
|
||||
const iconSignature = JSON.stringify(
|
||||
[...new Set(runs.flatMap((run) => (run.fileIcon ? [run.fileIcon] : [])))].sort(),
|
||||
);
|
||||
const icons = useMemo(
|
||||
() => JSON.parse(iconSignature) as ReadonlyArray<MarkdownFileIcon>,
|
||||
[iconSignature],
|
||||
);
|
||||
const [uris, setUris] = useState<ReadonlyMap<string, string>>(() => new Map());
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
void Promise.all(
|
||||
icons.map(async (icon) => {
|
||||
const source = markdownFileIconSource(icon);
|
||||
const fallbackUri = Image.resolveAssetSource(source).uri;
|
||||
if (typeof source !== "number" && typeof source !== "string") {
|
||||
return [icon, fallbackUri] as const;
|
||||
}
|
||||
try {
|
||||
const asset = Asset.fromModule(source);
|
||||
await asset.downloadAsync();
|
||||
return [icon, asset.localUri ?? fallbackUri] as const;
|
||||
} catch {
|
||||
return [icon, fallbackUri] as const;
|
||||
}
|
||||
}),
|
||||
).then((entries) => {
|
||||
if (!cancelled) {
|
||||
setUris(new Map(entries));
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [icons]);
|
||||
|
||||
return uris;
|
||||
}
|
||||
|
||||
function runKeySignature(run: NativeMarkdownTextRun): string {
|
||||
return [
|
||||
run.text,
|
||||
@@ -35,16 +81,13 @@ function runKeySignature(run: NativeMarkdownTextRun): string {
|
||||
function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle): TextStyle {
|
||||
const isFile = run.fileIcon != null;
|
||||
const isSkill = run.skillName != null;
|
||||
const isChip = isFile || isSkill;
|
||||
const headingLevel = Math.max(1, Math.min(6, run.headingLevel ?? 1));
|
||||
const headingFontSize = [22, 19, 17, 16, 15, 15][headingLevel - 1] ?? 15;
|
||||
const isHeading = run.role === "heading";
|
||||
const isCodeBlock = run.role === "code-block" || run.role === "code-language";
|
||||
const hasParagraphStyle = run.headIndent !== undefined;
|
||||
const textDecorationLine = run.strikethrough
|
||||
? "line-through"
|
||||
: run.href && !isFile
|
||||
? "underline"
|
||||
: "none";
|
||||
const textDecorationLine = run.strikethrough ? "line-through" : run.href ? "underline" : "none";
|
||||
|
||||
return {
|
||||
color: isFile
|
||||
@@ -63,23 +106,20 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
? textStyle.mutedColor
|
||||
: run.role === "list-marker"
|
||||
? textStyle.mutedColor
|
||||
: isCodeBlock
|
||||
: run.code || isFile
|
||||
? textStyle.codeColor
|
||||
: run.code
|
||||
? textStyle.inlineCodeColor
|
||||
: run.bold
|
||||
? textStyle.strongColor
|
||||
: textStyle.color,
|
||||
fontFamily:
|
||||
isFile || isSkill
|
||||
? textStyle.boldFontFamily
|
||||
: run.code || isCodeBlock
|
||||
? "ui-monospace"
|
||||
: isHeading
|
||||
? textStyle.headingFontFamily
|
||||
: run.bold
|
||||
? textStyle.boldFontFamily
|
||||
: textStyle.fontFamily,
|
||||
: run.bold
|
||||
? textStyle.strongColor
|
||||
: textStyle.color,
|
||||
fontFamily: isChip
|
||||
? "DMSans_500Medium"
|
||||
: run.code || isCodeBlock
|
||||
? "ui-monospace"
|
||||
: isHeading
|
||||
? textStyle.headingFontFamily
|
||||
: run.bold
|
||||
? textStyle.boldFontFamily
|
||||
: textStyle.fontFamily,
|
||||
fontSize:
|
||||
run.role === "spacer"
|
||||
? (run.spacing ?? 10)
|
||||
@@ -89,7 +129,7 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
? headingFontSize
|
||||
: run.role === "code-language"
|
||||
? 11
|
||||
: run.code || isCodeBlock
|
||||
: run.code || isChip || isCodeBlock
|
||||
? Math.max(12, textStyle.fontSize - 2)
|
||||
: textStyle.fontSize,
|
||||
lineHeight:
|
||||
@@ -103,9 +143,17 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
? 18
|
||||
: textStyle.lineHeight,
|
||||
fontStyle: run.italic ? "italic" : "normal",
|
||||
fontWeight: isHeading || run.bold || isFile || isSkill ? "700" : "400",
|
||||
fontWeight: isHeading || run.bold ? "700" : isChip ? "500" : "400",
|
||||
textDecorationLine,
|
||||
backgroundColor: isCodeBlock ? textStyle.codeBlockBackgroundColor : undefined,
|
||||
backgroundColor: isCodeBlock
|
||||
? textStyle.codeBlockBackgroundColor
|
||||
: isSkill
|
||||
? textStyle.skillBackgroundColor
|
||||
: run.code
|
||||
? textStyle.codeBackgroundColor
|
||||
: isFile
|
||||
? textStyle.fileBackgroundColor
|
||||
: undefined,
|
||||
...(hasParagraphStyle
|
||||
? {
|
||||
shadowColor: "transparent",
|
||||
@@ -122,9 +170,9 @@ function runStyle(run: NativeMarkdownTextRun, textStyle: NativeMarkdownTextStyle
|
||||
export function NativeMarkdownSelectableText(props: {
|
||||
readonly runs: ReadonlyArray<NativeMarkdownTextRun>;
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const fileIconUris = useFileIconUris(props.runs);
|
||||
const occurrences = new Map<string, number>();
|
||||
const prefixedExternalLinks = new Set<string>();
|
||||
const keyedRuns = props.runs.map((run) => {
|
||||
@@ -134,9 +182,9 @@ export function NativeMarkdownSelectableText(props: {
|
||||
|
||||
let text = run.text;
|
||||
if (run.fileIcon) {
|
||||
text = `${INLINE_ATTACHMENT_PREFIX}${text}`;
|
||||
text = `${FILE_LINK_PREFIX}${text}${CHIP_SUFFIX}`;
|
||||
} else if (run.skillName && run.skillLabel) {
|
||||
text = `${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}`;
|
||||
text = `\u00A0${SKILL_ICON_PLACEHOLDER}\u00A0${run.skillLabel}${CHIP_SUFFIX}`;
|
||||
} else if (run.externalHost && run.href && !prefixedExternalLinks.has(run.href)) {
|
||||
prefixedExternalLinks.add(run.href);
|
||||
text = `${EXTERNAL_LINK_PREFIX}${text}`;
|
||||
@@ -152,11 +200,12 @@ export function NativeMarkdownSelectableText(props: {
|
||||
props.textStyle.strongColor,
|
||||
props.textStyle.mutedColor,
|
||||
props.textStyle.linkColor,
|
||||
props.textStyle.inlineCodeColor,
|
||||
props.textStyle.codeColor,
|
||||
props.textStyle.codeBackgroundColor,
|
||||
props.textStyle.codeBlockBackgroundColor,
|
||||
props.textStyle.fileBackgroundColor,
|
||||
props.textStyle.fileTextColor,
|
||||
props.textStyle.skillBackgroundColor,
|
||||
props.textStyle.skillTextColor,
|
||||
props.textStyle.quoteMarkerColor,
|
||||
props.textStyle.dividerColor,
|
||||
@@ -168,8 +217,7 @@ export function NativeMarkdownSelectableText(props: {
|
||||
uiTextView
|
||||
selectable
|
||||
style={{
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
width: "100%",
|
||||
color: props.textStyle.color,
|
||||
fontFamily: props.textStyle.fontFamily,
|
||||
fontSize: props.textStyle.fontSize,
|
||||
@@ -183,20 +231,19 @@ export function NativeMarkdownSelectableText(props: {
|
||||
key={key}
|
||||
nativeID={
|
||||
run.fileIcon
|
||||
? `t3-file:${Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri}`
|
||||
? `t3-chip-file:${
|
||||
fileIconUris.get(run.fileIcon) ??
|
||||
Image.resolveAssetSource(markdownFileIconSource(run.fileIcon)).uri
|
||||
}`
|
||||
: run.skillName
|
||||
? "t3-skill:sf:cube"
|
||||
? "t3-chip-skill:sf:cube"
|
||||
: undefined
|
||||
}
|
||||
style={runStyle(run, props.textStyle)}
|
||||
onPress={
|
||||
href
|
||||
? () => {
|
||||
if (props.onLinkPress) {
|
||||
props.onLinkPress(href);
|
||||
} else {
|
||||
void Linking.openURL(href);
|
||||
}
|
||||
void Linking.openURL(href);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
nativeMarkdownChunkSpacing,
|
||||
nativeMarkdownDocumentChunks,
|
||||
nativeMarkdownDocumentRuns,
|
||||
nativeMarkdownWithPreservedSoftBreaks,
|
||||
} from "./nativeMarkdownText";
|
||||
import { NativeMarkdownBlock } from "./NativeMarkdownBlock.ios";
|
||||
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
|
||||
@@ -34,20 +33,15 @@ export function SelectableMarkdownText({
|
||||
skills = EMPTY_SKILLS,
|
||||
textStyle,
|
||||
highlightCode,
|
||||
preserveSoftBreaks = false,
|
||||
onLinkPress,
|
||||
marginTop = 0,
|
||||
marginBottom = 0,
|
||||
}: SelectableMarkdownTextProps) {
|
||||
const chunks = useMemo(() => {
|
||||
const parsedDocument = parseMarkdownWithOptions(markdown, {
|
||||
const document = parseMarkdownWithOptions(markdown, {
|
||||
gfm: true,
|
||||
html: true,
|
||||
math: false,
|
||||
});
|
||||
const document = preserveSoftBreaks
|
||||
? nativeMarkdownWithPreservedSoftBreaks(parsedDocument)
|
||||
: parsedDocument;
|
||||
return nativeMarkdownDocumentChunks(document).map((chunk) =>
|
||||
chunk.kind === "selectable"
|
||||
? {
|
||||
@@ -56,14 +50,10 @@ export function SelectableMarkdownText({
|
||||
}
|
||||
: chunk,
|
||||
);
|
||||
}, [markdown, preserveSoftBreaks, skills]);
|
||||
}, [markdown, skills]);
|
||||
|
||||
return (
|
||||
// A percentage width here creates a cyclic intrinsic measurement inside
|
||||
// shrink-to-fit containers such as user-message bubbles. Yoga then gives
|
||||
// the native text node an unbounded second pass and the parent only clips
|
||||
// the resulting single-line width instead of reflowing it.
|
||||
<View style={{ flexShrink: 1, minWidth: 0, marginTop, marginBottom }}>
|
||||
<View style={{ width: "100%", marginTop, marginBottom }}>
|
||||
{chunks.map((chunk, index) => {
|
||||
const content =
|
||||
chunk.kind === "rich" ? (
|
||||
@@ -71,14 +61,9 @@ export function SelectableMarkdownText({
|
||||
node={chunk.node}
|
||||
textStyle={textStyle}
|
||||
highlightCode={highlightCode}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<NativeMarkdownSelectableText
|
||||
runs={chunk.runs}
|
||||
textStyle={textStyle}
|
||||
onLinkPress={onLinkPress}
|
||||
/>
|
||||
<NativeMarkdownSelectableText runs={chunk.runs} textStyle={textStyle} />
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,11 +3,12 @@ export interface NativeMarkdownTextStyle {
|
||||
readonly strongColor: string;
|
||||
readonly mutedColor: string;
|
||||
readonly linkColor: string;
|
||||
readonly inlineCodeColor: string;
|
||||
readonly codeColor: string;
|
||||
readonly codeBackgroundColor: string;
|
||||
readonly codeBlockBackgroundColor: string;
|
||||
readonly fileBackgroundColor: string;
|
||||
readonly fileTextColor: string;
|
||||
readonly skillBackgroundColor: string;
|
||||
readonly skillTextColor: string;
|
||||
readonly quoteMarkerColor: string;
|
||||
readonly dividerColor: string;
|
||||
@@ -40,8 +41,6 @@ export interface SelectableMarkdownTextProps {
|
||||
readonly textStyle: NativeMarkdownTextStyle;
|
||||
readonly highlightCode: MarkdownCodeHighlighter;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly preserveSoftBreaks?: boolean;
|
||||
readonly onLinkPress?: (href: string) => void;
|
||||
readonly marginTop?: number;
|
||||
readonly marginBottom?: number;
|
||||
}
|
||||
@@ -27,12 +27,8 @@ export type MarkdownLinkPresentation =
|
||||
}
|
||||
| {
|
||||
readonly kind: "file";
|
||||
readonly href: string;
|
||||
readonly icon: MarkdownFileIcon;
|
||||
readonly label: string;
|
||||
readonly path: string;
|
||||
readonly line?: number;
|
||||
readonly column?: number;
|
||||
}
|
||||
| {
|
||||
readonly kind: "link";
|
||||
@@ -251,7 +247,7 @@ function normalizeDestination(value: string): string {
|
||||
return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
|
||||
}
|
||||
|
||||
function fileUrlTarget(href: string): { readonly path: string; readonly hash: string } | null {
|
||||
function fileUrlPath(href: string): string | null {
|
||||
try {
|
||||
const parsed = new URL(href);
|
||||
if (parsed.protocol.toLowerCase() !== "file:") {
|
||||
@@ -260,44 +256,15 @@ function fileUrlTarget(href: string): { readonly path: string; readonly hash: st
|
||||
const path = /^\/[A-Za-z]:[\\/]/.test(parsed.pathname)
|
||||
? parsed.pathname.slice(1)
|
||||
: parsed.pathname;
|
||||
return { path, hash: parsed.hash };
|
||||
const lineMatch = parsed.hash.match(/^#L(\d+)(?:C(\d+))?$/i);
|
||||
return `${safeDecode(path)}${
|
||||
lineMatch?.[1] ? `:${lineMatch[1]}${lineMatch[2] ? `:${lineMatch[2]}` : ""}` : ""
|
||||
}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function stripSearchAndHash(value: string): { readonly path: string; readonly hash: string } {
|
||||
const hashIndex = value.indexOf("#");
|
||||
const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
|
||||
const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
|
||||
const queryIndex = pathWithSearch.indexOf("?");
|
||||
return {
|
||||
path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
|
||||
hash,
|
||||
};
|
||||
}
|
||||
|
||||
function splitFilePosition(
|
||||
path: string,
|
||||
hash: string,
|
||||
): { readonly path: string; readonly line?: number; readonly column?: number } {
|
||||
const suffixMatch = path.match(/:(\d+)(?::(\d+))?$/);
|
||||
const hashMatch = suffixMatch ? null : hash.match(/^#L(\d+)(?:C(\d+))?$/i);
|
||||
const match = suffixMatch ?? hashMatch;
|
||||
if (!match?.[1]) {
|
||||
return { path };
|
||||
}
|
||||
|
||||
const line = Number.parseInt(match[1], 10);
|
||||
const column = match[2] ? Number.parseInt(match[2], 10) : undefined;
|
||||
const pathWithoutPosition = suffixMatch ? path.slice(0, -suffixMatch[0].length) : path;
|
||||
return {
|
||||
path: pathWithoutPosition,
|
||||
...(line > 0 ? { line } : {}),
|
||||
...(column !== undefined && column > 0 ? { column } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function looksLikePosixFilesystemPath(path: string): boolean {
|
||||
if (!path.startsWith("/")) {
|
||||
return false;
|
||||
@@ -364,31 +331,14 @@ export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPrese
|
||||
// Relative paths and non-URL link destinations are handled below.
|
||||
}
|
||||
|
||||
const source = normalized.toLowerCase().startsWith("file:")
|
||||
? fileUrlTarget(normalized)
|
||||
: stripSearchAndHash(normalized);
|
||||
const decodedSource = source
|
||||
? { path: safeDecode(source.path.trim()), hash: safeDecode(source.hash.trim()) }
|
||||
: null;
|
||||
const fileTarget = decodedSource
|
||||
? splitFilePosition(decodedSource.path, decodedSource.hash)
|
||||
: null;
|
||||
const targetWithPosition = fileTarget
|
||||
? `${fileTarget.path}${
|
||||
fileTarget.line
|
||||
? `:${fileTarget.line}${fileTarget.column ? `:${fileTarget.column}` : ""}`
|
||||
: ""
|
||||
}`
|
||||
: null;
|
||||
if (fileTarget && targetWithPosition && looksLikeFilePath(targetWithPosition)) {
|
||||
const fileTarget = normalized.toLowerCase().startsWith("file:")
|
||||
? fileUrlPath(normalized)
|
||||
: safeDecode(normalized.split(/[?#]/, 1)[0] ?? normalized);
|
||||
if (fileTarget && looksLikeFilePath(fileTarget)) {
|
||||
return {
|
||||
kind: "file",
|
||||
href: normalized,
|
||||
icon: resolveMarkdownFileIcon(fileTarget.path),
|
||||
label: fileLabel(targetWithPosition),
|
||||
path: fileTarget.path,
|
||||
...(fileTarget.line ? { line: fileTarget.line } : {}),
|
||||
...(fileTarget.column ? { column: fileTarget.column } : {}),
|
||||
icon: resolveMarkdownFileIcon(fileTarget),
|
||||
label: fileLabel(fileTarget),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -293,7 +293,6 @@ function appendNode(
|
||||
if (presentation.kind === "file") {
|
||||
return appendRun(runs, presentation.label, {
|
||||
...context,
|
||||
href: presentation.href,
|
||||
fileIcon: presentation.icon,
|
||||
});
|
||||
}
|
||||
@@ -320,15 +319,6 @@ export function nativeMarkdownTextRuns(node: MarkdownNode): ReadonlyArray<Native
|
||||
return appendChildren([], node, EMPTY_CONTEXT);
|
||||
}
|
||||
|
||||
export function nativeMarkdownWithPreservedSoftBreaks(node: MarkdownNode): MarkdownNode {
|
||||
const children = node.children?.map(nativeMarkdownWithPreservedSoftBreaks);
|
||||
return {
|
||||
...node,
|
||||
...(node.type === "soft_break" ? { type: "line_break" as const } : {}),
|
||||
...(children ? { children } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function appendBlockTerminator(
|
||||
runs: NativeMarkdownTextRun[],
|
||||
context: RunContext,
|
||||
|
||||
@@ -57,10 +57,6 @@ public class T3ReviewDiffModule: Module {
|
||||
view.setContentWidth(CGFloat(contentWidth))
|
||||
}
|
||||
|
||||
Prop("initialRowIndex") { (view: T3ReviewDiffView, initialRowIndex: Double) in
|
||||
view.setInitialRowIndex(initialRowIndex)
|
||||
}
|
||||
|
||||
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,7 +205,7 @@ private struct ReviewDiffNativeStyle {
|
||||
ReviewDiffNativeStyle(
|
||||
rowHeight: metric(payload?.rowHeight, fallback: 24),
|
||||
contentWidth: metric(payload?.contentWidth, fallback: 2800),
|
||||
changeBarWidth: nonNegativeMetric(payload?.changeBarWidth, fallback: 4),
|
||||
changeBarWidth: metric(payload?.changeBarWidth, fallback: 4),
|
||||
gutterWidth: metric(payload?.gutterWidth, fallback: 50),
|
||||
codePadding: metric(payload?.codePadding, fallback: 8),
|
||||
textVerticalInset: metric(payload?.textVerticalInset, fallback: 3),
|
||||
@@ -243,13 +243,6 @@ private struct ReviewDiffNativeStyle {
|
||||
return CGFloat(value)
|
||||
}
|
||||
|
||||
private static func nonNegativeMetric(_ value: Double?, fallback: CGFloat) -> CGFloat {
|
||||
guard let value, value.isFinite, value >= 0 else {
|
||||
return fallback
|
||||
}
|
||||
return CGFloat(value)
|
||||
}
|
||||
|
||||
private static func fontWeight(_ value: String?, fallback: UIFont.Weight) -> UIFont.Weight {
|
||||
switch value?.lowercased() {
|
||||
case "ultralight", "ultra-light":
|
||||
@@ -323,8 +316,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
private var lastMetricsDebugKey = ""
|
||||
private var lastVisibleRangeDebugKey = ""
|
||||
private var tokensResetKey = ""
|
||||
private var initialRowIndex: Int?
|
||||
private var hasAppliedInitialRowIndex = false
|
||||
|
||||
let onDebug = EventDispatcher()
|
||||
let onToggleFile = EventDispatcher()
|
||||
@@ -403,7 +394,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
do {
|
||||
rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
|
||||
contentView.rows = rows
|
||||
hasAppliedInitialRowIndex = false
|
||||
emitDebug("rows-decoded", [
|
||||
"rows": rows.count,
|
||||
"firstKind": rows.first?.kind ?? "none",
|
||||
@@ -412,7 +402,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
} catch {
|
||||
rows = []
|
||||
contentView.rows = []
|
||||
hasAppliedInitialRowIndex = false
|
||||
updateContentMetrics()
|
||||
emitDebug("rows-decode-failed", [
|
||||
"error": error.localizedDescription,
|
||||
@@ -572,7 +561,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
contentView.verticalOffset = scrollView.contentOffset.y
|
||||
contentView.invalidateVisibleViewport()
|
||||
contentView.setNeedsDisplay()
|
||||
applyInitialRowIndexIfNeeded()
|
||||
|
||||
let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))"
|
||||
if debugKey != lastMetricsDebugKey {
|
||||
@@ -657,19 +645,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
applyStyle()
|
||||
}
|
||||
|
||||
func setInitialRowIndex(_ initialRowIndex: Double) {
|
||||
let nextIndex: Int? = initialRowIndex.isFinite && initialRowIndex >= 0
|
||||
? Int(initialRowIndex.rounded(.down))
|
||||
: nil
|
||||
guard nextIndex != self.initialRowIndex else {
|
||||
return
|
||||
}
|
||||
|
||||
self.initialRowIndex = nextIndex
|
||||
hasAppliedInitialRowIndex = false
|
||||
applyInitialRowIndexIfNeeded()
|
||||
}
|
||||
|
||||
private func applyStyle() {
|
||||
contentView.style = ReviewDiffNativeStyle
|
||||
.resolve(stylePayload)
|
||||
@@ -687,22 +662,6 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
|
||||
contentView.verticalOffset = scrollView.contentOffset.y
|
||||
contentView.invalidateVisibleViewport()
|
||||
}
|
||||
|
||||
private func applyInitialRowIndexIfNeeded() {
|
||||
guard !hasAppliedInitialRowIndex,
|
||||
let initialRowIndex,
|
||||
bounds.height > 0,
|
||||
let rowFrame = contentView.frameForRow(at: initialRowIndex) else {
|
||||
return
|
||||
}
|
||||
|
||||
let targetScreenY = max(0, (bounds.height - rowFrame.height) * 0.3)
|
||||
let maxOffset = max(scrollView.contentSize.height - scrollView.bounds.height, 0)
|
||||
let targetOffset = min(max(rowFrame.minY - targetScreenY, 0), maxOffset)
|
||||
hasAppliedInitialRowIndex = true
|
||||
scrollView.setContentOffset(CGPoint(x: 0, y: targetOffset), animated: false)
|
||||
updateViewportFrame()
|
||||
}
|
||||
}
|
||||
|
||||
private enum ReviewDiffHorizontalPanKind {
|
||||
@@ -861,19 +820,6 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
|
||||
return style.rowHeight
|
||||
}
|
||||
|
||||
func frameForRow(at index: Int) -> CGRect? {
|
||||
guard rows.indices.contains(index), rowOffsets.indices.contains(index) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return CGRect(
|
||||
x: 0,
|
||||
y: rowOffsets[index],
|
||||
width: max(viewportWidth, 1),
|
||||
height: height(for: rows[index])
|
||||
)
|
||||
}
|
||||
|
||||
private func rebuildRowLayout() {
|
||||
var nextOffsets: [CGFloat] = []
|
||||
var nextFileHeaderRowIndices: [Int] = []
|
||||
|
||||
@@ -101,7 +101,6 @@
|
||||
"react-native-screens": "4.25.2",
|
||||
"react-native-shiki-engine": "^0.3.12",
|
||||
"react-native-svg": "15.15.4",
|
||||
"react-native-webview": "^13.16.1",
|
||||
"react-native-worklets": "0.8.3",
|
||||
"shiki": "4.2.0",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
|
||||
@@ -30,11 +30,10 @@ import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
function AppNavigator() {
|
||||
const pathname = usePathname();
|
||||
const expandedSettingsRouteIsActive =
|
||||
pathname === "/settings/archive" || pathname === "/settings/auth";
|
||||
const clerkRouteIsActive = pathname === "/settings/auth";
|
||||
|
||||
return (
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={expandedSettingsRouteIsActive}>
|
||||
<ClerkSettingsSheetDetentProvider initiallyExpanded={clerkRouteIsActive}>
|
||||
<AppNavigatorContent />
|
||||
</ClerkSettingsSheetDetentProvider>
|
||||
);
|
||||
|
||||
@@ -1,33 +1,13 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { Stack, useRouter } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import { Text as RNText, View } from "react-native";
|
||||
|
||||
import { useProjects, useThreadShells } from "../state/entities";
|
||||
import { useWorkspaceState } from "../state/workspace";
|
||||
import { buildThreadRoutePath } from "../lib/routes";
|
||||
import { useSavedRemoteConnections } from "../state/use-remote-environment-registry";
|
||||
import { HomeScreen } from "../features/home/HomeScreen";
|
||||
import { HomeHeader } from "../features/home/HomeHeader";
|
||||
import type { HomeProjectSortOrder } from "../features/home/homeThreadList";
|
||||
import { useThreadListActions } from "../features/home/useThreadListActions";
|
||||
|
||||
interface HomeListOptions {
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
|
||||
@@ -38,82 +18,103 @@ export default function HomeRouteScreen() {
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const router = useRouter();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [listOptions, setListOptions] = useState<HomeListOptions>({
|
||||
selectedEnvironmentId: null,
|
||||
projectSortOrder:
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER === "manual"
|
||||
? "updated_at"
|
||||
: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
threadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
projectGroupingMode: DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
});
|
||||
const { archiveThread, confirmDeleteThread } = useThreadListActions();
|
||||
const environments = useMemo(
|
||||
() =>
|
||||
Arr.sort(
|
||||
Object.values(savedConnectionsById).map((connection) => ({
|
||||
environmentId: connection.environmentId,
|
||||
label: connection.environmentLabel,
|
||||
})),
|
||||
Order.mapInput(
|
||||
Order.String,
|
||||
(environment: { readonly label: string }) => environment.label,
|
||||
),
|
||||
),
|
||||
[savedConnectionsById],
|
||||
);
|
||||
const selectedEnvironmentId = environments.some(
|
||||
(environment) => environment.environmentId === listOptions.selectedEnvironmentId,
|
||||
)
|
||||
? listOptions.selectedEnvironmentId
|
||||
: null;
|
||||
const setSelectedEnvironmentId = useCallback((environmentId: EnvironmentId | null) => {
|
||||
setListOptions((current) => ({ ...current, selectedEnvironmentId: environmentId }));
|
||||
}, []);
|
||||
const setProjectSortOrder = useCallback((projectSortOrder: HomeProjectSortOrder) => {
|
||||
setListOptions((current) => ({ ...current, projectSortOrder }));
|
||||
}, []);
|
||||
const setThreadSortOrder = useCallback((threadSortOrder: SidebarThreadSortOrder) => {
|
||||
setListOptions((current) => ({ ...current, threadSortOrder }));
|
||||
}, []);
|
||||
const setProjectGroupingMode = useCallback((projectGroupingMode: SidebarProjectGroupingMode) => {
|
||||
setListOptions((current) => ({ ...current, projectGroupingMode }));
|
||||
}, []);
|
||||
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
|
||||
return (
|
||||
<>
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onOpenSettings={() => router.push("/settings")}
|
||||
onProjectGroupingModeChange={setProjectGroupingMode}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => router.push("/new")}
|
||||
onThreadSortOrderChange={setThreadSortOrder}
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerShown: true,
|
||||
headerTransparent: true,
|
||||
headerStyle: { backgroundColor: "transparent" },
|
||||
headerShadowVisible: false,
|
||||
headerTintColor: iconColor,
|
||||
headerTitle: "",
|
||||
headerSearchBarOptions: {
|
||||
placeholder: "Search threads",
|
||||
hideNavigationBar: false,
|
||||
onChangeText: (event) => {
|
||||
setSearchQuery(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
setSearchQuery("");
|
||||
},
|
||||
allowToolbarIntegration: true,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Header left: plain text, no Liquid Glass button chrome */}
|
||||
<Stack.Toolbar placement="left">
|
||||
<Stack.Toolbar.View hidesSharedBackground>
|
||||
<View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
|
||||
<RNText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 17,
|
||||
color: iconColor,
|
||||
letterSpacing: -0.4,
|
||||
}}
|
||||
>
|
||||
T3 Code
|
||||
</RNText>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: subtleColor,
|
||||
borderRadius: 99,
|
||||
paddingHorizontal: 8,
|
||||
paddingVertical: 3,
|
||||
}}
|
||||
>
|
||||
<RNText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 10,
|
||||
color: mutedColor,
|
||||
letterSpacing: 1.1,
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
Alpha
|
||||
</RNText>
|
||||
</View>
|
||||
</View>
|
||||
</Stack.Toolbar.View>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Button
|
||||
icon="gearshape"
|
||||
onPress={() => router.push("/settings")}
|
||||
separateBackground
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
|
||||
{/* Bottom toolbar: search + compose, visually split like iMessage */}
|
||||
<Stack.Toolbar placement="bottom">
|
||||
<Stack.Toolbar.SearchBarSlot />
|
||||
<Stack.Toolbar.Spacer width={8} sharesBackground={false} />
|
||||
<Stack.Toolbar.Button
|
||||
icon="square.and.pencil"
|
||||
onPress={() => router.push("/new")}
|
||||
separateBackground
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<HomeScreen
|
||||
projects={projects}
|
||||
threads={threads}
|
||||
catalogState={catalogState}
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
onAddConnection={() => router.push("/connections/new")}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onOpenEnvironments={() => router.push("/settings/environments")}
|
||||
onSelectThread={(thread) => {
|
||||
router.push(buildThreadRoutePath(thread));
|
||||
}}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
projects={projects}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
threads={threads}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -14,7 +14,7 @@ export default function SettingsLayout() {
|
||||
const contentStyle = useResolveClassNames("bg-sheet");
|
||||
const sheetBg = useThemeColor("--color-sheet");
|
||||
const headerTint = useThemeColor("--color-foreground");
|
||||
const handleExpandedRouteTransitionEnd = useCallback(
|
||||
const handleClerkRouteTransitionEnd = useCallback(
|
||||
(event: { data: { closing: boolean } }) => {
|
||||
if (event.data.closing) {
|
||||
collapse();
|
||||
@@ -47,14 +47,9 @@ export default function SettingsLayout() {
|
||||
name="waitlist"
|
||||
options={{ animation: "slide_from_right", title: "Join the waitlist" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="archive"
|
||||
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
|
||||
options={{ animation: "slide_from_right", title: "Archived Threads" }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="auth"
|
||||
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
|
||||
listeners={{ transitionEnd: handleClerkRouteTransitionEnd }}
|
||||
options={{ animation: "slide_from_right", title: "Sign in" }}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
import { ArchivedThreadsRouteScreen } from "../../features/archive/ArchivedThreadsRouteScreen";
|
||||
|
||||
export default ArchivedThreadsRouteScreen;
|
||||
@@ -255,7 +255,11 @@ function ConnectedCloudEnvironmentRow(props: {
|
||||
props.onDisconnect();
|
||||
}}
|
||||
onToggleError={props.onToggleError}
|
||||
value={props.environment.connectionState !== "available"}
|
||||
value={
|
||||
props.environment.connectionState === "connected" ||
|
||||
props.environment.connectionState === "connecting" ||
|
||||
props.environment.connectionState === "reconnecting"
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -65,8 +65,6 @@ function LocalSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
</ScrollView>
|
||||
</View>
|
||||
@@ -376,8 +374,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
<AppSettingsSection />
|
||||
</ScrollView>
|
||||
</View>
|
||||
@@ -420,20 +416,12 @@ function AppSettingsSection() {
|
||||
);
|
||||
}
|
||||
|
||||
function ArchivedThreadsSettingsSection() {
|
||||
return (
|
||||
<SettingsSection title="Threads">
|
||||
<SettingsRow icon="archivebox" label="Archived Threads" href="/settings/archive" />
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
function SettingsRow(props: {
|
||||
readonly disabled?: boolean;
|
||||
readonly icon: SymbolName;
|
||||
readonly label: string;
|
||||
readonly value?: string;
|
||||
readonly href?: "/settings/archive" | "/settings/environments";
|
||||
readonly href?: "/settings/environments";
|
||||
readonly onPress?: () => void;
|
||||
}) {
|
||||
const icon = useThemeColor("--color-icon");
|
||||
@@ -471,9 +459,7 @@ function SettingsRow(props: {
|
||||
if (props.href) {
|
||||
return (
|
||||
<Link href={props.href} asChild>
|
||||
<Pressable accessibilityLabel={props.label} accessibilityRole="button">
|
||||
{content}
|
||||
</Pressable>
|
||||
<Pressable>{content}</Pressable>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -55,32 +55,6 @@ export default function ThreadLayout() {
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="files/index"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: sheetStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerTitle: "Files",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="files/[...path]"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: sheetStyle,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerTitle: "File",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: headerBg,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="review-comment"
|
||||
options={{
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ThreadFileScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
|
||||
|
||||
export default function ThreadFileRoute() {
|
||||
return <ThreadFileScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ThreadFilesTreeScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
|
||||
|
||||
export default function ThreadFilesIndexRoute() {
|
||||
return <ThreadFilesTreeScreen />;
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import Animated, {
|
||||
cancelAnimation,
|
||||
Easing,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withRepeat,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
|
||||
const INDICATOR_WIDTH_FRACTION = 0.3;
|
||||
const MIN_INDICATOR_WIDTH = 48;
|
||||
|
||||
function LoadingStripFrame(props: {
|
||||
readonly children: React.ReactNode;
|
||||
readonly onLayout?: (width: number) => void;
|
||||
}) {
|
||||
return (
|
||||
<View
|
||||
pointerEvents="none"
|
||||
accessibilityElementsHidden
|
||||
importantForAccessibility="no-hide-descendants"
|
||||
className="absolute inset-x-0 top-0 z-10 h-0.5 overflow-hidden"
|
||||
onLayout={
|
||||
props.onLayout
|
||||
? (event) => {
|
||||
props.onLayout?.(event.nativeEvent.layout.width);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{props.children}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function IndeterminateLoadingStrip() {
|
||||
const [containerWidth, setContainerWidth] = useState(0);
|
||||
const travelProgress = useSharedValue(0);
|
||||
const indicatorWidth = Math.max(MIN_INDICATOR_WIDTH, containerWidth * INDICATOR_WIDTH_FRACTION);
|
||||
|
||||
useEffect(() => {
|
||||
travelProgress.value = 0;
|
||||
travelProgress.value = withRepeat(
|
||||
withTiming(1, {
|
||||
duration: 1100,
|
||||
easing: Easing.inOut(Easing.quad),
|
||||
}),
|
||||
-1,
|
||||
false,
|
||||
);
|
||||
|
||||
return () => {
|
||||
cancelAnimation(travelProgress);
|
||||
};
|
||||
}, [travelProgress]);
|
||||
|
||||
const indicatorStyle = useAnimatedStyle(
|
||||
() => ({
|
||||
transform: [
|
||||
{
|
||||
translateX: (containerWidth + indicatorWidth) * travelProgress.value - indicatorWidth,
|
||||
},
|
||||
],
|
||||
width: indicatorWidth,
|
||||
}),
|
||||
[containerWidth, indicatorWidth],
|
||||
);
|
||||
|
||||
return (
|
||||
<LoadingStripFrame onLayout={setContainerWidth}>
|
||||
<Animated.View className="h-full rounded-full bg-primary" style={indicatorStyle} />
|
||||
</LoadingStripFrame>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoadingStrip(props: { readonly progress?: number }) {
|
||||
if (props.progress === undefined) {
|
||||
return <IndeterminateLoadingStrip />;
|
||||
}
|
||||
|
||||
const clampedProgress = Math.min(1, Math.max(0, props.progress));
|
||||
|
||||
return (
|
||||
<LoadingStripFrame>
|
||||
<View
|
||||
className="h-full rounded-r-full bg-primary"
|
||||
style={{ width: `${clampedProgress * 100}%` }}
|
||||
/>
|
||||
</LoadingStripFrame>
|
||||
);
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useFocusEffect } from "expo-router";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
|
||||
import { useArchivedThreadListActions } from "../home/useThreadListActions";
|
||||
import {
|
||||
ArchivedThreadsScreen,
|
||||
type ArchivedThreadsHeaderEnvironment,
|
||||
} from "./ArchivedThreadsScreen";
|
||||
import { buildArchivedThreadGroups, type ArchivedThreadSortOrder } from "./archivedThreadList";
|
||||
import {
|
||||
refreshArchivedThreadsForEnvironment,
|
||||
useArchivedThreadSnapshots,
|
||||
} from "./useArchivedThreadSnapshots";
|
||||
|
||||
export function ArchivedThreadsRouteScreen() {
|
||||
const { expand } = useClerkSettingsSheetDetent();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
|
||||
const [sortOrder, setSortOrder] = useState<ArchivedThreadSortOrder>("newest");
|
||||
const environments = useMemo<ReadonlyArray<ArchivedThreadsHeaderEnvironment>>(
|
||||
() =>
|
||||
Arr.sort(
|
||||
Object.values(savedConnectionsById).map((connection) => ({
|
||||
environmentId: connection.environmentId,
|
||||
label: connection.environmentLabel,
|
||||
})),
|
||||
Order.mapInput(Order.String, (environment: ArchivedThreadsHeaderEnvironment) =>
|
||||
environment.label.toLocaleLowerCase(),
|
||||
),
|
||||
),
|
||||
[savedConnectionsById],
|
||||
);
|
||||
const environmentIds = useMemo(
|
||||
() => environments.map((environment) => environment.environmentId),
|
||||
[environments],
|
||||
);
|
||||
const environmentLabels = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
environments.map((environment) => [environment.environmentId, environment.label]),
|
||||
),
|
||||
[environments],
|
||||
);
|
||||
const { error, isLoading, refresh, snapshots } = useArchivedThreadSnapshots(environmentIds);
|
||||
const groups = useMemo(
|
||||
() =>
|
||||
buildArchivedThreadGroups({
|
||||
snapshots,
|
||||
environmentLabels,
|
||||
environmentId: selectedEnvironmentId,
|
||||
searchQuery,
|
||||
sortOrder,
|
||||
}),
|
||||
[environmentLabels, searchQuery, selectedEnvironmentId, snapshots, sortOrder],
|
||||
);
|
||||
const refreshChangedEnvironment = useCallback(
|
||||
(thread: { readonly environmentId: EnvironmentId }) => {
|
||||
refreshArchivedThreadsForEnvironment(thread.environmentId);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const { unarchiveThread, confirmDeleteThread } =
|
||||
useArchivedThreadListActions(refreshChangedEnvironment);
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
expand();
|
||||
refresh();
|
||||
}, [expand, refresh]),
|
||||
);
|
||||
|
||||
return (
|
||||
<ArchivedThreadsScreen
|
||||
environments={environments}
|
||||
error={error}
|
||||
groups={groups}
|
||||
isLoading={isLoading}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onRefresh={refresh}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSortOrderChange={setSortOrder}
|
||||
onUnarchiveThread={unarchiveThread}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
sortOrder={sortOrder}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,434 +0,0 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { Stack } from "expo-router";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useCallback, useRef } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Pressable,
|
||||
RefreshControl,
|
||||
ScrollView,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native";
|
||||
import ReanimatedSwipeable, {
|
||||
type SwipeableMethods,
|
||||
} from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
THREAD_SWIPE_ACTIONS_WIDTH,
|
||||
THREAD_SWIPE_SPRING,
|
||||
ThreadSwipeActions,
|
||||
} from "../home/thread-swipe-actions";
|
||||
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
|
||||
|
||||
export interface ArchivedThreadsHeaderEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
}
|
||||
|
||||
const THREAD_ACTIONS: MenuAction[] = [
|
||||
{
|
||||
id: "unarchive",
|
||||
title: "Unarchive",
|
||||
image: "arrow.uturn.backward",
|
||||
},
|
||||
{
|
||||
id: "delete",
|
||||
title: "Delete",
|
||||
image: "trash",
|
||||
attributes: { destructive: true },
|
||||
},
|
||||
];
|
||||
|
||||
function ArchivedThreadsHeader(props: {
|
||||
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly sortOrder: ArchivedThreadSortOrder;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
|
||||
}) {
|
||||
const hasCustomFilter = props.selectedEnvironmentId !== null || props.sortOrder !== "newest";
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "Archived Threads",
|
||||
headerSearchBarOptions: {
|
||||
autoCapitalize: "none",
|
||||
hideNavigationBar: false,
|
||||
obscureBackground: false,
|
||||
placeholder: "Search archived threads",
|
||||
placement: "stacked",
|
||||
onChangeText: (event) => {
|
||||
props.onSearchQueryChange(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
props.onSearchQueryChange("");
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu
|
||||
accessibilityLabel="Filter and sort archived threads"
|
||||
icon={
|
||||
hasCustomFilter
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle"
|
||||
}
|
||||
separateBackground
|
||||
title="Archived thread options"
|
||||
>
|
||||
<Stack.Toolbar.Menu title="Environment">
|
||||
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.selectedEnvironmentId === null}
|
||||
onPress={() => props.onEnvironmentChange(null)}
|
||||
>
|
||||
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
{props.environments.map((environment) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={environment.environmentId}
|
||||
isOn={props.selectedEnvironmentId === environment.environmentId}
|
||||
onPress={() => props.onEnvironmentChange(environment.environmentId)}
|
||||
>
|
||||
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Menu title="Sort by archived date">
|
||||
<Stack.Toolbar.Label>Sort by archived date</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.sortOrder === "newest"}
|
||||
onPress={() => props.onSortOrderChange("newest")}
|
||||
>
|
||||
<Stack.Toolbar.Label>Newest first</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.sortOrder === "oldest"}
|
||||
onPress={() => props.onSortOrderChange("oldest")}
|
||||
>
|
||||
<Stack.Toolbar.Label>Oldest first</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ProjectGroupLabel(props: {
|
||||
readonly environmentLabel: string | null;
|
||||
readonly project: EnvironmentProject;
|
||||
}) {
|
||||
return (
|
||||
<View className="flex-row items-center gap-2.5 px-1 pb-2">
|
||||
<ProjectFavicon
|
||||
environmentId={props.project.environmentId}
|
||||
projectTitle={props.project.title}
|
||||
size={18}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
<Text
|
||||
className="flex-1 text-[12px] font-t3-medium uppercase text-foreground-muted"
|
||||
numberOfLines={1}
|
||||
style={{ letterSpacing: 0.5 }}
|
||||
>
|
||||
{props.project.title}
|
||||
</Text>
|
||||
{props.environmentLabel ? (
|
||||
<Text className="max-w-[42%] text-[11px] text-foreground-tertiary" numberOfLines={1}>
|
||||
{props.environmentLabel}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ArchivedThreadRow(props: {
|
||||
readonly environmentLabel: string | null;
|
||||
readonly isLast: boolean;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onUnarchive: () => void;
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
}) {
|
||||
const swipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const fullSwipeArmedRef = useRef(false);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const cardColor = useThemeColor("--color-card");
|
||||
const iconColor = useThemeColor("--color-icon-subtle");
|
||||
const separatorColor = useThemeColor("--color-separator");
|
||||
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
|
||||
const timestamp = relativeTime(props.thread.archivedAt ?? props.thread.updatedAt);
|
||||
const subtitle = [props.environmentLabel, props.thread.branch].filter((part): part is string =>
|
||||
Boolean(part),
|
||||
);
|
||||
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
|
||||
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
|
||||
}
|
||||
fullSwipeArmedRef.current = armed;
|
||||
}, []);
|
||||
const handleMenuAction = useCallback(
|
||||
(event: { nativeEvent: { event: string } }) => {
|
||||
if (event.nativeEvent.event === "unarchive") {
|
||||
props.onUnarchive();
|
||||
} else if (event.nativeEvent.event === "delete") {
|
||||
props.onDelete();
|
||||
}
|
||||
},
|
||||
[props.onDelete, props.onUnarchive],
|
||||
);
|
||||
|
||||
return (
|
||||
<ReanimatedSwipeable
|
||||
ref={swipeableRef}
|
||||
animationOptions={THREAD_SWIPE_SPRING}
|
||||
childrenContainerStyle={{ backgroundColor: cardColor }}
|
||||
containerStyle={{ backgroundColor: cardColor }}
|
||||
dragOffsetFromRightEdge={8}
|
||||
enableTrackpadTwoFingerGesture
|
||||
friction={1}
|
||||
onSwipeableClose={() => {
|
||||
fullSwipeArmedRef.current = false;
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableClose(swipeableRef.current);
|
||||
}
|
||||
}}
|
||||
onSwipeableOpenStartDrag={() => {
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableWillOpen(swipeableRef.current);
|
||||
}
|
||||
}}
|
||||
onSwipeableWillOpen={() => {
|
||||
const methods = swipeableRef.current;
|
||||
if (!methods) return;
|
||||
|
||||
props.onSwipeableWillOpen(methods);
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
props.onDelete();
|
||||
}
|
||||
}}
|
||||
overshootFriction={1}
|
||||
overshootRight
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={cardColor}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
primaryAction={{
|
||||
accessibilityLabel: `Unarchive ${props.thread.title}`,
|
||||
icon: "arrow.uturn.backward",
|
||||
label: "Unarchive",
|
||||
onPress: props.onUnarchive,
|
||||
}}
|
||||
swipeableMethods={methods}
|
||||
threadTitle={props.thread.title}
|
||||
translation={translation}
|
||||
/>
|
||||
)}
|
||||
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
|
||||
>
|
||||
<View
|
||||
className="flex-row items-center gap-3 bg-card px-4 py-3"
|
||||
style={{
|
||||
borderBottomColor: separatorColor,
|
||||
borderBottomWidth: props.isLast ? 0 : 1,
|
||||
}}
|
||||
>
|
||||
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
|
||||
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
|
||||
</View>
|
||||
|
||||
<View className="min-w-0 flex-1 gap-1">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-[12px] text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"] }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
</View>
|
||||
{subtitle.length > 0 ? (
|
||||
<View className="flex-row items-center gap-1.5">
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={10}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-[11px] text-foreground-tertiary"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: "monospace" }}
|
||||
>
|
||||
{subtitle.join(" · ")}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
|
||||
<Pressable
|
||||
accessibilityLabel={`Actions for ${props.thread.title}`}
|
||||
accessibilityRole="button"
|
||||
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
|
||||
hitSlop={6}
|
||||
>
|
||||
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</ControlPillMenu>
|
||||
</View>
|
||||
</ReanimatedSwipeable>
|
||||
);
|
||||
}
|
||||
|
||||
function ArchiveError(props: { readonly message: string; readonly onRetry: () => void }) {
|
||||
return (
|
||||
<View className="rounded-[20px] border border-danger-border bg-danger p-4">
|
||||
<Text className="font-t3-bold text-danger-foreground">Could not load every archive</Text>
|
||||
<Text className="mt-1 text-[13px] leading-[18px] text-foreground-muted">{props.message}</Text>
|
||||
<Pressable className="mt-3 self-start active:opacity-60" onPress={props.onRetry}>
|
||||
<Text className="text-[13px] font-t3-bold text-danger-foreground">Try again</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ArchivedThreadsScreen(props: {
|
||||
readonly environments: ReadonlyArray<ArchivedThreadsHeaderEnvironment>;
|
||||
readonly error: string | null;
|
||||
readonly groups: ReadonlyArray<ArchivedThreadGroup>;
|
||||
readonly isLoading: boolean;
|
||||
readonly searchQuery: string;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly sortOrder: ArchivedThreadSortOrder;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onRefresh: () => void;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
|
||||
readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
}) {
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const refreshTint = useThemeColor("--color-icon");
|
||||
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
|
||||
if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
|
||||
openSwipeableRef.current.close();
|
||||
}
|
||||
openSwipeableRef.current = methods;
|
||||
}, []);
|
||||
const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
|
||||
if (openSwipeableRef.current === methods) {
|
||||
openSwipeableRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
const isInitialLoad = props.isLoading && props.groups.length === 0 && props.error === null;
|
||||
const isFiltered = props.searchQuery.trim().length > 0 || props.selectedEnvironmentId !== null;
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<ArchivedThreadsHeader
|
||||
environments={props.environments}
|
||||
onEnvironmentChange={props.onEnvironmentChange}
|
||||
onSearchQueryChange={props.onSearchQueryChange}
|
||||
onSortOrderChange={props.onSortOrderChange}
|
||||
selectedEnvironmentId={props.selectedEnvironmentId}
|
||||
sortOrder={props.sortOrder}
|
||||
/>
|
||||
|
||||
<ScrollView
|
||||
className="flex-1"
|
||||
contentContainerStyle={{ gap: 20, paddingBottom: 32, paddingHorizontal: 16, paddingTop: 8 }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
onRefresh={props.onRefresh}
|
||||
refreshing={props.isLoading && !isInitialLoad}
|
||||
tintColor={String(refreshTint)}
|
||||
/>
|
||||
}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
|
||||
|
||||
{isInitialLoad ? (
|
||||
<View className="items-center py-16">
|
||||
<ActivityIndicator color={refreshTint} />
|
||||
<Text className="mt-3 text-[13px] text-foreground-muted">Loading archive…</Text>
|
||||
</View>
|
||||
) : props.groups.length === 0 ? (
|
||||
<EmptyState
|
||||
detail={
|
||||
isFiltered
|
||||
? "Try another search or environment."
|
||||
: "Threads you archive will appear here."
|
||||
}
|
||||
title={isFiltered ? "No matching threads" : "No archived threads"}
|
||||
/>
|
||||
) : (
|
||||
props.groups.map((group) => {
|
||||
const environmentLabel =
|
||||
props.environments.find(
|
||||
(environment) => environment.environmentId === group.project.environmentId,
|
||||
)?.label ?? null;
|
||||
|
||||
return (
|
||||
<View key={group.key} collapsable={false}>
|
||||
<ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
|
||||
<View
|
||||
className="overflow-hidden rounded-[20px] bg-card"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
>
|
||||
{group.threads.map((thread, index) => (
|
||||
<ArchivedThreadRow
|
||||
key={`${thread.environmentId}:${thread.id}`}
|
||||
environmentLabel={environmentLabel}
|
||||
isLast={index === group.threads.length - 1}
|
||||
onDelete={() => props.onDeleteThread(thread)}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
onUnarchive={() => props.onUnarchiveThread(thread)}
|
||||
thread={thread}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
|
||||
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildArchivedThreadGroups } from "./archivedThreadList";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
function makeProject(
|
||||
input: Partial<OrchestrationProjectShell> & Pick<OrchestrationProjectShell, "id" | "title">,
|
||||
): OrchestrationProjectShell {
|
||||
return {
|
||||
workspaceRoot: `/workspaces/${input.id}`,
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<OrchestrationThreadShell> &
|
||||
Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
|
||||
): OrchestrationThreadShell {
|
||||
return {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: "2026-06-02T00:00:00.000Z",
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function makeSnapshot(
|
||||
projects: ReadonlyArray<OrchestrationProjectShell>,
|
||||
threads: ReadonlyArray<OrchestrationThreadShell>,
|
||||
targetEnvironmentId = environmentId,
|
||||
): ArchivedSnapshotEntry {
|
||||
return {
|
||||
environmentId: targetEnvironmentId,
|
||||
snapshot: {
|
||||
snapshotSequence: 1,
|
||||
projects,
|
||||
threads,
|
||||
updatedAt: "2026-06-04T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildArchivedThreadGroups", () => {
|
||||
it("groups archived threads by project and sorts newest first", () => {
|
||||
const project = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
|
||||
const older = makeThread({
|
||||
id: ThreadId.make("thread-older"),
|
||||
projectId: project.id,
|
||||
title: "Older",
|
||||
});
|
||||
const newer = makeThread({
|
||||
archivedAt: "2026-06-03T00:00:00.000Z",
|
||||
id: ThreadId.make("thread-newer"),
|
||||
projectId: project.id,
|
||||
title: "Newer",
|
||||
});
|
||||
|
||||
const result = buildArchivedThreadGroups({
|
||||
snapshots: [makeSnapshot([project], [older, newer])],
|
||||
environmentLabels: { [environmentId]: "Julius's MacBook Pro" },
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
sortOrder: "newest",
|
||||
});
|
||||
|
||||
expect(result[0]?.threads.map((thread) => thread.id)).toEqual(["thread-newer", "thread-older"]);
|
||||
});
|
||||
|
||||
it("filters by environment and matches project, thread, and branch text", () => {
|
||||
const secondEnvironmentId = EnvironmentId.make("environment-2");
|
||||
const firstProject = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
|
||||
const secondProject = makeProject({ id: ProjectId.make("project-2"), title: "Website" });
|
||||
const firstThread = makeThread({
|
||||
branch: "fix/archive-screen",
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: firstProject.id,
|
||||
title: "Build settings route",
|
||||
});
|
||||
const secondThread = makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
projectId: secondProject.id,
|
||||
title: "Unrelated",
|
||||
});
|
||||
const snapshots = [
|
||||
makeSnapshot([firstProject], [firstThread]),
|
||||
makeSnapshot([secondProject], [secondThread], secondEnvironmentId),
|
||||
];
|
||||
|
||||
const result = buildArchivedThreadGroups({
|
||||
snapshots,
|
||||
environmentLabels: {
|
||||
[environmentId]: "Local",
|
||||
[secondEnvironmentId]: "Remote",
|
||||
},
|
||||
environmentId,
|
||||
searchQuery: "archive-screen",
|
||||
sortOrder: "oldest",
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]?.project.environmentId).toBe(environmentId);
|
||||
expect(result[0]?.threads.map((thread) => thread.id)).toEqual(["thread-1"]);
|
||||
});
|
||||
|
||||
it("ignores non-archived entries returned in a snapshot", () => {
|
||||
const project = makeProject({ id: ProjectId.make("project-1"), title: "T3 Code" });
|
||||
const active = makeThread({
|
||||
archivedAt: null,
|
||||
id: ThreadId.make("thread-active"),
|
||||
projectId: project.id,
|
||||
title: "Active",
|
||||
});
|
||||
|
||||
const result = buildArchivedThreadGroups({
|
||||
snapshots: [makeSnapshot([project], [active])],
|
||||
environmentLabels: {},
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
sortOrder: "newest",
|
||||
});
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,106 +0,0 @@
|
||||
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
|
||||
import {
|
||||
scopeProject,
|
||||
scopeThreadShell,
|
||||
type EnvironmentProject,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
|
||||
export type ArchivedThreadSortOrder = "newest" | "oldest";
|
||||
|
||||
export interface ArchivedThreadGroup {
|
||||
readonly key: string;
|
||||
readonly project: EnvironmentProject;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
}
|
||||
|
||||
function archiveTimestamp(thread: EnvironmentThreadShell): number {
|
||||
const timestamp = Date.parse(thread.archivedAt ?? thread.updatedAt);
|
||||
return Number.isNaN(timestamp) ? 0 : timestamp;
|
||||
}
|
||||
|
||||
function matchesQuery(value: string | null, query: string): boolean {
|
||||
return value?.toLocaleLowerCase().includes(query) ?? false;
|
||||
}
|
||||
|
||||
export function buildArchivedThreadGroups(input: {
|
||||
readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
|
||||
readonly environmentLabels: Readonly<Record<string, string>>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly searchQuery: string;
|
||||
readonly sortOrder: ArchivedThreadSortOrder;
|
||||
}): ReadonlyArray<ArchivedThreadGroup> {
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
const groups: ArchivedThreadGroup[] = [];
|
||||
|
||||
for (const entry of input.snapshots) {
|
||||
if (input.environmentId !== null && input.environmentId !== entry.environmentId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const environmentLabel = input.environmentLabels[entry.environmentId] ?? null;
|
||||
const threadsByProjectId = new Map<string, EnvironmentThreadShell[]>();
|
||||
for (const thread of entry.snapshot.threads) {
|
||||
if (thread.archivedAt === null) {
|
||||
continue;
|
||||
}
|
||||
const threads = threadsByProjectId.get(thread.projectId) ?? [];
|
||||
threads.push(scopeThreadShell(entry.environmentId, thread));
|
||||
threadsByProjectId.set(thread.projectId, threads);
|
||||
}
|
||||
|
||||
for (const rawProject of entry.snapshot.projects) {
|
||||
const project = scopeProject(entry.environmentId, rawProject);
|
||||
const projectThreads = threadsByProjectId.get(project.id) ?? [];
|
||||
const groupMatches =
|
||||
query.length === 0 ||
|
||||
matchesQuery(project.title, query) ||
|
||||
matchesQuery(project.workspaceRoot, query) ||
|
||||
matchesQuery(environmentLabel, query);
|
||||
const matchingThreads = groupMatches
|
||||
? projectThreads
|
||||
: projectThreads.filter(
|
||||
(thread) => matchesQuery(thread.title, query) || matchesQuery(thread.branch, query),
|
||||
);
|
||||
|
||||
if (matchingThreads.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const timestampOrder = input.sortOrder === "newest" ? Order.flip(Order.Number) : Order.Number;
|
||||
groups.push({
|
||||
key: scopedProjectKey(project.environmentId, project.id),
|
||||
project,
|
||||
threads: Arr.sort(
|
||||
matchingThreads,
|
||||
Order.mapInput(
|
||||
Order.Struct({ timestamp: timestampOrder, title: Order.String, id: Order.String }),
|
||||
(thread: EnvironmentThreadShell) => ({
|
||||
timestamp: archiveTimestamp(thread),
|
||||
title: thread.title,
|
||||
id: thread.id,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const timestampOrder = input.sortOrder === "newest" ? Order.flip(Order.Number) : Order.Number;
|
||||
return Arr.sort(
|
||||
groups,
|
||||
Order.mapInput(
|
||||
Order.Struct({ timestamp: timestampOrder, title: Order.String, key: Order.String }),
|
||||
(group: ArchivedThreadGroup) => ({
|
||||
timestamp: group.threads[0] ? archiveTimestamp(group.threads[0]) : 0,
|
||||
title: group.project.title,
|
||||
key: group.key,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
type ArchivedSnapshotEntry,
|
||||
createArchivedThreadSnapshotsAtomFamily,
|
||||
makeArchivedThreadsEnvironmentKey,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useMemo } from "react";
|
||||
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { orchestrationEnvironment } from "../../state/orchestration";
|
||||
|
||||
function archivedSnapshotAtom(environmentId: EnvironmentId) {
|
||||
return orchestrationEnvironment.archivedShellSnapshot({
|
||||
environmentId,
|
||||
input: {},
|
||||
});
|
||||
}
|
||||
|
||||
const archivedSnapshotsAtom = createArchivedThreadSnapshotsAtomFamily({
|
||||
getSnapshotAtom: archivedSnapshotAtom,
|
||||
labelPrefix: "mobile:archived-thread-snapshots",
|
||||
});
|
||||
|
||||
export function refreshArchivedThreadsForEnvironment(environmentId: EnvironmentId): void {
|
||||
appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
|
||||
}
|
||||
|
||||
export function useArchivedThreadSnapshots(environmentIds: ReadonlyArray<EnvironmentId>): {
|
||||
readonly snapshots: ReadonlyArray<ArchivedSnapshotEntry>;
|
||||
readonly error: string | null;
|
||||
readonly isLoading: boolean;
|
||||
readonly refresh: () => void;
|
||||
} {
|
||||
const environmentKey = useMemo(
|
||||
() => makeArchivedThreadsEnvironmentKey(environmentIds),
|
||||
[environmentIds],
|
||||
);
|
||||
const result = useAtomValue(archivedSnapshotsAtom(environmentKey));
|
||||
const refresh = useCallback(() => {
|
||||
for (const environmentId of environmentIds) {
|
||||
appAtomRegistry.refresh(archivedSnapshotAtom(environmentId));
|
||||
}
|
||||
}, [environmentIds]);
|
||||
|
||||
return { ...result, refresh };
|
||||
}
|
||||
@@ -110,7 +110,6 @@ export interface NativeReviewDiffViewProps extends ViewProps {
|
||||
readonly styleJson?: string;
|
||||
readonly rowHeight: number;
|
||||
readonly contentWidth: number;
|
||||
readonly initialRowIndex?: number;
|
||||
readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
|
||||
readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
|
||||
readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
Markdown,
|
||||
type CustomRenderers,
|
||||
type NodeStyleOverrides,
|
||||
type PartialMarkdownTheme,
|
||||
} from "react-native-nitro-markdown";
|
||||
import { Linking, ScrollView, Text as NativeText, View } from "react-native";
|
||||
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
hasNativeSelectableMarkdownText,
|
||||
SelectableMarkdownText,
|
||||
type NativeMarkdownTextStyle,
|
||||
} from "../../native/SelectableMarkdownText";
|
||||
|
||||
interface MarkdownPreviewStyles {
|
||||
readonly theme: PartialMarkdownTheme;
|
||||
readonly styles: NodeStyleOverrides;
|
||||
readonly renderers: CustomRenderers;
|
||||
readonly nativeTextStyle: NativeMarkdownTextStyle;
|
||||
}
|
||||
|
||||
function useMarkdownPreviewStyles(): MarkdownPreviewStyles {
|
||||
const body = String(useThemeColor("--color-md-body"));
|
||||
const strong = String(useThemeColor("--color-md-strong"));
|
||||
const link = String(useThemeColor("--color-md-link"));
|
||||
const blockquoteBorder = String(useThemeColor("--color-md-blockquote-border"));
|
||||
const blockquoteBackground = String(useThemeColor("--color-md-blockquote-bg"));
|
||||
const codeBackground = String(useThemeColor("--color-md-code-bg"));
|
||||
const codeText = String(useThemeColor("--color-md-code-text"));
|
||||
const horizontalRule = String(useThemeColor("--color-md-hr"));
|
||||
|
||||
return useMemo(() => {
|
||||
const renderers: CustomRenderers = {
|
||||
link: ({ href, children }) => (
|
||||
<NativeText
|
||||
onPress={() => {
|
||||
if (href) {
|
||||
void Linking.openURL(href);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
color: link,
|
||||
fontFamily: "DMSans_500Medium",
|
||||
textDecorationLine: "none",
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</NativeText>
|
||||
),
|
||||
};
|
||||
|
||||
return {
|
||||
theme: {
|
||||
colors: {
|
||||
text: body,
|
||||
heading: strong,
|
||||
link,
|
||||
blockquote: blockquoteBorder,
|
||||
border: horizontalRule,
|
||||
surfaceLight: blockquoteBackground,
|
||||
accent: link,
|
||||
tableBorder: horizontalRule,
|
||||
tableHeader: blockquoteBackground,
|
||||
tableHeaderText: strong,
|
||||
code: codeText,
|
||||
codeBackground,
|
||||
},
|
||||
},
|
||||
styles: {
|
||||
text: {
|
||||
color: body,
|
||||
fontFamily: "DMSans_400Regular",
|
||||
fontSize: 15,
|
||||
lineHeight: 22,
|
||||
},
|
||||
heading: {
|
||||
color: strong,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
},
|
||||
strong: {
|
||||
color: strong,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
},
|
||||
link: {
|
||||
color: link,
|
||||
fontFamily: "DMSans_500Medium",
|
||||
},
|
||||
blockquote: {
|
||||
backgroundColor: blockquoteBackground,
|
||||
borderLeftColor: blockquoteBorder,
|
||||
borderLeftWidth: 3,
|
||||
paddingLeft: 12,
|
||||
},
|
||||
code: {
|
||||
backgroundColor: codeBackground,
|
||||
color: codeText,
|
||||
fontFamily: "ui-monospace",
|
||||
},
|
||||
codeBlock: {
|
||||
backgroundColor: codeBackground,
|
||||
borderRadius: 12,
|
||||
color: codeText,
|
||||
fontFamily: "ui-monospace",
|
||||
padding: 12,
|
||||
},
|
||||
hr: {
|
||||
backgroundColor: horizontalRule,
|
||||
},
|
||||
},
|
||||
renderers,
|
||||
nativeTextStyle: {
|
||||
color: body,
|
||||
strongColor: strong,
|
||||
mutedColor: body,
|
||||
linkColor: link,
|
||||
inlineCodeColor: codeText,
|
||||
codeColor: codeText,
|
||||
codeBackgroundColor: codeBackground,
|
||||
codeBlockBackgroundColor: codeBackground,
|
||||
fileTextColor: codeText,
|
||||
skillTextColor: codeText,
|
||||
quoteMarkerColor: blockquoteBorder,
|
||||
dividerColor: horizontalRule,
|
||||
fontSize: 15,
|
||||
lineHeight: 22,
|
||||
fontFamily: "DMSans_400Regular",
|
||||
headingFontFamily: "DMSans_700Bold",
|
||||
boldFontFamily: "DMSans_700Bold",
|
||||
},
|
||||
};
|
||||
}, [
|
||||
blockquoteBackground,
|
||||
blockquoteBorder,
|
||||
body,
|
||||
codeBackground,
|
||||
codeText,
|
||||
horizontalRule,
|
||||
link,
|
||||
strong,
|
||||
]);
|
||||
}
|
||||
|
||||
export function FileMarkdownPreview(props: { readonly markdown: string }) {
|
||||
const styles = useMarkdownPreviewStyles();
|
||||
|
||||
return (
|
||||
<ScrollView className="flex-1 bg-card" contentContainerStyle={{ padding: 18 }}>
|
||||
<View className="mx-auto w-full max-w-[760px]">
|
||||
{hasNativeSelectableMarkdownText() ? (
|
||||
<SelectableMarkdownText markdown={props.markdown} textStyle={styles.nativeTextStyle} />
|
||||
) : (
|
||||
<Markdown
|
||||
options={{ gfm: true }}
|
||||
renderers={styles.renderers}
|
||||
styles={styles.styles}
|
||||
theme={styles.theme}
|
||||
>
|
||||
{props.markdown}
|
||||
</Markdown>
|
||||
)}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
import type { ProjectEntry } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { memo, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
buildFileTree,
|
||||
defaultExpandedTreePaths,
|
||||
flattenFileTree,
|
||||
type VisibleFileTreeNode,
|
||||
} from "./fileTree";
|
||||
|
||||
function ancestorPaths(path: string): ReadonlyArray<string> {
|
||||
const parts = path.split("/").filter(Boolean);
|
||||
const ancestors: string[] = [];
|
||||
for (let index = 1; index < parts.length; index += 1) {
|
||||
ancestors.push(parts.slice(0, index).join("/"));
|
||||
}
|
||||
return ancestors;
|
||||
}
|
||||
|
||||
const FileTreeRow = memo(function FileTreeRow(props: {
|
||||
readonly item: VisibleFileTreeNode;
|
||||
readonly selectedPath: string | null;
|
||||
readonly expanded: boolean;
|
||||
readonly iconColor: string;
|
||||
readonly onPressDirectory: (path: string) => void;
|
||||
readonly onPressFile: (path: string) => void;
|
||||
}) {
|
||||
const { node, depth } = props.item;
|
||||
const selected = node.kind === "file" && node.path === props.selectedPath;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={node.path}
|
||||
onPress={() => {
|
||||
if (node.kind === "directory") {
|
||||
props.onPressDirectory(node.path);
|
||||
return;
|
||||
}
|
||||
props.onPressFile(node.path);
|
||||
}}
|
||||
className={cn(
|
||||
"mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
|
||||
selected && "bg-subtle-strong",
|
||||
)}
|
||||
style={{ paddingLeft: 8 + depth * 18 }}
|
||||
>
|
||||
{node.kind === "directory" ? (
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.down" : "chevron.right"}
|
||||
size={12}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
) : (
|
||||
<View className="w-3" />
|
||||
)}
|
||||
<PierreEntryIcon path={node.path} kind={node.kind} size={17} />
|
||||
<Text
|
||||
className={cn(
|
||||
"min-w-0 flex-1 text-[14px] leading-[19px]",
|
||||
selected ? "font-t3-bold text-foreground" : "font-t3-medium text-foreground-secondary",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{node.name}
|
||||
</Text>
|
||||
{node.kind === "directory" ? (
|
||||
<Text className="text-[11px] font-t3-medium text-foreground-tertiary">
|
||||
{node.children.length}
|
||||
</Text>
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
export function FileTreeBrowser(props: {
|
||||
readonly entries: ReadonlyArray<ProjectEntry>;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly searchQuery: string;
|
||||
readonly selectedPath: string | null;
|
||||
readonly onRefresh: () => void;
|
||||
readonly onSelectFile: (path: string) => void;
|
||||
}) {
|
||||
const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
|
||||
const tree = useMemo(() => buildFileTree(props.entries), [props.entries]);
|
||||
const defaultExpanded = useMemo(() => defaultExpandedTreePaths(tree), [tree]);
|
||||
const visibleNodes = useMemo(
|
||||
() =>
|
||||
flattenFileTree({
|
||||
nodes: tree,
|
||||
expanded: expandedPaths,
|
||||
searchQuery: props.searchQuery,
|
||||
}),
|
||||
[expandedPaths, props.searchQuery, tree],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setExpandedPaths((current) => {
|
||||
if (current.size > 0 || defaultExpanded.size === 0) {
|
||||
return current;
|
||||
}
|
||||
return new Set(defaultExpanded);
|
||||
});
|
||||
}, [defaultExpanded]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!props.selectedPath) {
|
||||
return;
|
||||
}
|
||||
setExpandedPaths((current) => {
|
||||
const next = new Set(current);
|
||||
for (const ancestor of ancestorPaths(props.selectedPath ?? "")) {
|
||||
next.add(ancestor);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, [props.selectedPath]);
|
||||
|
||||
const toggleDirectory = useCallback((path: string) => {
|
||||
setExpandedPaths((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(path)) {
|
||||
next.delete(path);
|
||||
} else {
|
||||
next.add(path);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
{props.error && props.entries.length === 0 ? (
|
||||
<View className="px-4 py-5">
|
||||
<Text className="text-[13px] font-t3-bold text-foreground">Files unavailable</Text>
|
||||
<Text className="mt-1 text-[12px] leading-[18px] text-foreground-muted">
|
||||
{props.error}
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<FlatList
|
||||
data={visibleNodes}
|
||||
keyExtractor={(item) => item.node.path}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
contentContainerStyle={{ paddingVertical: 8 }}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />
|
||||
}
|
||||
renderItem={({ item }) => (
|
||||
<FileTreeRow
|
||||
item={item}
|
||||
selectedPath={props.selectedPath}
|
||||
expanded={expandedPaths.has(item.node.path)}
|
||||
iconColor={iconColor}
|
||||
onPressDirectory={toggleDirectory}
|
||||
onPressFile={props.onSelectFile}
|
||||
/>
|
||||
)}
|
||||
ListEmptyComponent={
|
||||
<View className="px-4 py-5">
|
||||
{props.isPending ? (
|
||||
<ActivityIndicator size="small" />
|
||||
) : (
|
||||
<>
|
||||
<Text className="text-[13px] font-t3-bold text-foreground">No files found</Text>
|
||||
<Text className="mt-1 text-[12px] leading-[18px] text-foreground-muted">
|
||||
{props.searchQuery.trim().length > 0
|
||||
? "Try a different search."
|
||||
: "The workspace file index is empty."}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import type { ComponentType } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { FlatList, ScrollView, Text as NativeText, useColorScheme, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { LoadingStrip } from "../../components/LoadingStrip";
|
||||
import {
|
||||
type NativeReviewDiffViewProps,
|
||||
resolveNativeReviewDiffView,
|
||||
} from "../diffs/nativeReviewDiffSurface";
|
||||
import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
|
||||
import {
|
||||
REVIEW_DIFF_LINE_HEIGHT,
|
||||
REVIEW_MONO_FONT_FAMILY,
|
||||
renderVisibleWhitespace,
|
||||
} from "../review/reviewDiffRendering";
|
||||
import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
|
||||
import { cn } from "../../lib/cn";
|
||||
import {
|
||||
buildNativeSourceRows,
|
||||
buildNativeSourceTokens,
|
||||
NATIVE_SOURCE_CONTENT_WIDTH,
|
||||
NATIVE_SOURCE_ROW_HEIGHT,
|
||||
NATIVE_SOURCE_STYLE,
|
||||
nativeSourceRowId,
|
||||
} from "./nativeSourceFileAdapter";
|
||||
import { sourceHighlightAtom } from "./sourceHighlightingState";
|
||||
|
||||
const SOURCE_LINE_HEIGHT = 24;
|
||||
const SOURCE_LINE_NUMBER_WIDTH = 58;
|
||||
const NATIVE_SOURCE_STYLE_JSON = JSON.stringify(NATIVE_SOURCE_STYLE);
|
||||
|
||||
interface SourceFileSurfaceProps {
|
||||
readonly contents: string;
|
||||
readonly path: string;
|
||||
readonly initialLine?: number | null;
|
||||
}
|
||||
|
||||
type SourceHighlightStatus = "highlighting" | "ready" | "error";
|
||||
|
||||
function splitSourceLines(contents: string): ReadonlyArray<string> {
|
||||
return contents.replace(/\r\n?/g, "\n").split("\n");
|
||||
}
|
||||
|
||||
const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
|
||||
readonly index: number;
|
||||
readonly line: string;
|
||||
readonly tokens: ReadonlyArray<ReviewHighlightedToken> | null;
|
||||
readonly highlighted: boolean;
|
||||
}) {
|
||||
return (
|
||||
<View
|
||||
className={cn("flex-row", props.highlighted && "bg-primary/10")}
|
||||
style={{ minHeight: SOURCE_LINE_HEIGHT }}
|
||||
>
|
||||
<NativeText
|
||||
className="select-none pr-3 text-right text-[11px] leading-[24px] text-foreground-tertiary"
|
||||
style={{
|
||||
width: SOURCE_LINE_NUMBER_WIDTH,
|
||||
fontFamily: REVIEW_MONO_FONT_FAMILY,
|
||||
}}
|
||||
>
|
||||
{props.index + 1}
|
||||
</NativeText>
|
||||
<NativeText
|
||||
selectable
|
||||
numberOfLines={1}
|
||||
className="text-[13px] font-medium leading-[24px] text-foreground"
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY, minWidth: 320 }}
|
||||
>
|
||||
{props.tokens && props.tokens.length > 0
|
||||
? (() => {
|
||||
let offset = 0;
|
||||
return props.tokens.map((token) => {
|
||||
const start = offset;
|
||||
offset += token.content.length;
|
||||
|
||||
const fontWeight =
|
||||
token.fontStyle !== null && (token.fontStyle & 2) === 2
|
||||
? ("700" as const)
|
||||
: ("500" as const);
|
||||
const fontStyle =
|
||||
token.fontStyle !== null && (token.fontStyle & 1) === 1
|
||||
? ("italic" as const)
|
||||
: ("normal" as const);
|
||||
|
||||
return (
|
||||
<NativeText
|
||||
key={`${start}:${token.content.length}:${token.color ?? ""}`}
|
||||
selectable
|
||||
style={{
|
||||
color: token.color ?? undefined,
|
||||
fontFamily: REVIEW_MONO_FONT_FAMILY,
|
||||
fontWeight,
|
||||
fontStyle,
|
||||
}}
|
||||
>
|
||||
{token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
|
||||
</NativeText>
|
||||
);
|
||||
});
|
||||
})()
|
||||
: renderVisibleWhitespace(props.line || " ")}
|
||||
</NativeText>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
function useSourceFileModel(props: SourceFileSurfaceProps) {
|
||||
const colorScheme = useColorScheme();
|
||||
const theme: "dark" | "light" = colorScheme === "dark" ? "dark" : "light";
|
||||
const normalizedContents = useMemo(
|
||||
() => props.contents.replace(/\r\n?/g, "\n"),
|
||||
[props.contents],
|
||||
);
|
||||
const lines = useMemo(() => splitSourceLines(normalizedContents), [normalizedContents]);
|
||||
const targetIndex =
|
||||
props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
|
||||
? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
|
||||
: null;
|
||||
const highlightAtom = useMemo(
|
||||
() => sourceHighlightAtom({ path: props.path, contents: normalizedContents, theme }),
|
||||
[normalizedContents, props.path, theme],
|
||||
);
|
||||
const highlightResult = useAtomValue(highlightAtom);
|
||||
const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;
|
||||
const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)
|
||||
? "error"
|
||||
: AsyncResult.isSuccess(highlightResult)
|
||||
? "ready"
|
||||
: "highlighting";
|
||||
|
||||
return { lines, status, targetIndex, theme, tokens };
|
||||
}
|
||||
|
||||
function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
|
||||
if (props.status === "highlighting") {
|
||||
return <LoadingStrip />;
|
||||
}
|
||||
if (props.status === "error") {
|
||||
return (
|
||||
<View className="border-b border-border bg-card px-4 py-2">
|
||||
<Text className="text-[11px] font-t3-medium uppercase text-foreground-muted">
|
||||
Plain text
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function NativeSourceFileSurface(
|
||||
props: SourceFileSurfaceProps & {
|
||||
readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
|
||||
},
|
||||
) {
|
||||
const { NativeView } = props;
|
||||
const { lines, status, targetIndex, theme, tokens } = useSourceFileModel(props);
|
||||
const rowsJson = useMemo(() => JSON.stringify(buildNativeSourceRows(lines)), [lines]);
|
||||
const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
|
||||
const selectedRowIdsJson = useMemo(
|
||||
() => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
|
||||
[targetIndex],
|
||||
);
|
||||
const themeJson = useMemo(() => JSON.stringify(createNativeReviewDiffTheme(theme)), [theme]);
|
||||
|
||||
return (
|
||||
<View className="relative flex-1 bg-card">
|
||||
<SourceHighlightStatusView status={status} />
|
||||
<NativeView
|
||||
key={props.path}
|
||||
collapsable={false}
|
||||
testID="source-native-code-view"
|
||||
style={{ flex: 1 }}
|
||||
appearanceScheme={theme}
|
||||
contentWidth={NATIVE_SOURCE_CONTENT_WIDTH}
|
||||
initialRowIndex={targetIndex ?? -1}
|
||||
rowHeight={NATIVE_SOURCE_ROW_HEIGHT}
|
||||
rowsJson={rowsJson}
|
||||
selectedRowIdsJson={selectedRowIdsJson}
|
||||
styleJson={NATIVE_SOURCE_STYLE_JSON}
|
||||
themeJson={themeJson}
|
||||
tokensJson={tokensJson}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
|
||||
const { lines, status, targetIndex, tokens } = useSourceFileModel(props);
|
||||
const listRef = useRef<FlatList<string>>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (targetIndex === null) {
|
||||
return;
|
||||
}
|
||||
const frame = requestAnimationFrame(() => {
|
||||
listRef.current?.scrollToIndex({ index: targetIndex, animated: false, viewPosition: 0.3 });
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [props.path, targetIndex]);
|
||||
|
||||
const renderLine = useCallback(
|
||||
({ item, index }: { item: string; index: number }) => (
|
||||
<HighlightedSourceLine
|
||||
index={index}
|
||||
line={item}
|
||||
tokens={tokens?.[index] ?? null}
|
||||
highlighted={index === targetIndex}
|
||||
/>
|
||||
),
|
||||
[targetIndex, tokens],
|
||||
);
|
||||
|
||||
return (
|
||||
<View className="relative flex-1 bg-card">
|
||||
<SourceHighlightStatusView status={status} />
|
||||
<ScrollView horizontal bounces={false} className="flex-1">
|
||||
<FlatList
|
||||
ref={listRef}
|
||||
data={lines}
|
||||
keyExtractor={(_line, index) => String(index)}
|
||||
initialNumToRender={80}
|
||||
maxToRenderPerBatch={80}
|
||||
windowSize={12}
|
||||
getItemLayout={(_data, index) => ({
|
||||
length: SOURCE_LINE_HEIGHT,
|
||||
offset: SOURCE_LINE_HEIGHT * index,
|
||||
index,
|
||||
})}
|
||||
contentContainerStyle={{
|
||||
minWidth: "100%",
|
||||
paddingBottom: REVIEW_DIFF_LINE_HEIGHT,
|
||||
paddingTop: 8,
|
||||
}}
|
||||
renderItem={renderLine}
|
||||
/>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function SourceFileSurface(props: SourceFileSurfaceProps) {
|
||||
const NativeView = resolveNativeReviewDiffView();
|
||||
return NativeView ? (
|
||||
<NativeSourceFileSurface {...props} NativeView={NativeView} />
|
||||
) : (
|
||||
<JavaScriptSourceFileSurface {...props} />
|
||||
);
|
||||
}
|
||||
@@ -1,631 +0,0 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Linking,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
Text as RNText,
|
||||
View,
|
||||
} from "react-native";
|
||||
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
|
||||
import {
|
||||
EnvironmentId,
|
||||
type ProjectListEntriesResult,
|
||||
type ProjectReadFileResult,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { CopyTextButton } from "../../components/CopyTextButton";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { LoadingScreen } from "../../components/LoadingScreen";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { buildThreadFilesNavigation } from "../../lib/routes";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import { projectEnvironment } from "../../state/projects";
|
||||
import { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider";
|
||||
import { FileMarkdownPreview } from "./FileMarkdownPreview";
|
||||
import { FileTreeBrowser } from "./FileTreeBrowser";
|
||||
import { SourceFileSurface } from "./SourceFileSurface";
|
||||
import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
|
||||
import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
|
||||
import {
|
||||
basename,
|
||||
fileBreadcrumbs,
|
||||
isBrowserPreviewFile,
|
||||
isImagePreviewFile,
|
||||
isMarkdownPreviewFile,
|
||||
isSvgImagePreviewFile,
|
||||
} from "./filePath";
|
||||
import { useWorkspaceFileAssetUrl } from "./workspaceFileAssetUrl";
|
||||
|
||||
type FileViewMode = "preview" | "source";
|
||||
|
||||
function firstRouteParam(value: string | string[] | undefined): string | null {
|
||||
if (Array.isArray(value)) {
|
||||
return value[0] ?? null;
|
||||
}
|
||||
|
||||
return value ?? null;
|
||||
}
|
||||
|
||||
function normalizeRoutePath(value: string | string[] | undefined): string | null {
|
||||
const path = Array.isArray(value) ? value.join("/") : value;
|
||||
if (path === undefined || path.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
function normalizeRouteLine(value: string | null): number | null {
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
const parsed = Number(value);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function defaultViewMode(path: string | null): FileViewMode {
|
||||
return path !== null && (isBrowserPreviewFile(path) || isImagePreviewFile(path))
|
||||
? "preview"
|
||||
: "source";
|
||||
}
|
||||
|
||||
function ModeButton(props: {
|
||||
readonly active: boolean;
|
||||
readonly icon: "doc.text" | "eye";
|
||||
readonly label: string;
|
||||
readonly onPress: () => void;
|
||||
}) {
|
||||
const iconColor = String(
|
||||
useThemeColor(props.active ? "--color-primary-foreground" : "--color-icon-muted"),
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: props.active }}
|
||||
className={cn(
|
||||
"h-8 flex-row items-center justify-center gap-1.5 rounded-full px-3 active:opacity-70",
|
||||
props.active ? "bg-primary" : "bg-subtle",
|
||||
)}
|
||||
onPress={props.onPress}
|
||||
>
|
||||
<SymbolView name={props.icon} size={13} tintColor={iconColor} type="monochrome" />
|
||||
<Text
|
||||
className={cn(
|
||||
"text-[12px] font-t3-bold",
|
||||
props.active ? "text-primary-foreground" : "text-foreground-muted",
|
||||
)}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function BreadcrumbFade(props: { readonly color: string; readonly side: "left" | "right" }) {
|
||||
const gradientId = `file-breadcrumb-${props.side}-fade`;
|
||||
const isLeft = props.side === "left";
|
||||
|
||||
return (
|
||||
<View
|
||||
pointerEvents="none"
|
||||
className={cn("absolute inset-y-0 w-7", isLeft ? "left-0" : "right-0")}
|
||||
>
|
||||
<Svg width="100%" height="100%">
|
||||
<Defs>
|
||||
<LinearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">
|
||||
<Stop offset="0%" stopColor={props.color} stopOpacity={isLeft ? 1 : 0} />
|
||||
<Stop offset="100%" stopColor={props.color} stopOpacity={isLeft ? 0 : 1} />
|
||||
</LinearGradient>
|
||||
</Defs>
|
||||
<Rect width="100%" height="100%" fill={`url(#${gradientId})`} />
|
||||
</Svg>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FileBreadcrumbs(props: { readonly projectName: string; readonly relativePath: string }) {
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
const cardColor = String(useThemeColor("--color-card"));
|
||||
const scrollMetrics = useRef({ contentWidth: 0, offsetX: 0, viewportWidth: 0 });
|
||||
const [fadeVisibility, setFadeVisibility] = useState({ left: false, right: false });
|
||||
const breadcrumbs = useMemo(
|
||||
() => fileBreadcrumbs(props.projectName, props.relativePath),
|
||||
[props.projectName, props.relativePath],
|
||||
);
|
||||
const updateFadeVisibility = useCallback(
|
||||
(metrics: Partial<(typeof scrollMetrics)["current"]>) => {
|
||||
Object.assign(scrollMetrics.current, metrics);
|
||||
const { contentWidth, offsetX, viewportWidth } = scrollMetrics.current;
|
||||
const maxOffset = Math.max(0, contentWidth - viewportWidth);
|
||||
const next = {
|
||||
left: maxOffset > 1 && offsetX > 1,
|
||||
right: maxOffset > 1 && offsetX < maxOffset - 1,
|
||||
};
|
||||
|
||||
setFadeVisibility((current) =>
|
||||
current.left === next.left && current.right === next.right ? current : next,
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<View className="min-w-0 flex-1">
|
||||
<ScrollView
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
onContentSizeChange={(contentWidth) => {
|
||||
updateFadeVisibility({ contentWidth });
|
||||
}}
|
||||
onLayout={(event) => {
|
||||
updateFadeVisibility({ viewportWidth: event.nativeEvent.layout.width });
|
||||
}}
|
||||
onScroll={(event) => {
|
||||
updateFadeVisibility({ offsetX: event.nativeEvent.contentOffset.x });
|
||||
}}
|
||||
scrollEventThrottle={16}
|
||||
>
|
||||
<View className="h-8 flex-row items-center">
|
||||
{breadcrumbs.map((crumb, index) => (
|
||||
<View key={crumb.path || "project"} className="flex-row items-center">
|
||||
{index > 0 ? (
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={10}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"max-w-[180px] px-1 text-[12px]",
|
||||
crumb.kind === "file"
|
||||
? "font-t3-bold text-foreground"
|
||||
: "font-t3-medium text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{crumb.label}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</ScrollView>
|
||||
{fadeVisibility.left ? <BreadcrumbFade color={cardColor} side="left" /> : null}
|
||||
{fadeVisibility.right ? <BreadcrumbFade color={cardColor} side="right" /> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FilePreviewHeader(props: {
|
||||
readonly activeMode: FileViewMode;
|
||||
readonly showModeSelector: boolean;
|
||||
readonly externalPreviewUri?: string | null;
|
||||
readonly projectName: string;
|
||||
readonly relativePath: string;
|
||||
readonly onSetMode: (mode: FileViewMode) => void;
|
||||
}) {
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
|
||||
return (
|
||||
<View className="border-b border-border bg-card px-3 py-2">
|
||||
<View className="flex-row items-center gap-2">
|
||||
<FileBreadcrumbs projectName={props.projectName} relativePath={props.relativePath} />
|
||||
<CopyTextButton
|
||||
accessibilityLabel="Copy file path"
|
||||
text={props.relativePath}
|
||||
tintColor={iconColor}
|
||||
buttonSize={32}
|
||||
iconSize={13}
|
||||
/>
|
||||
</View>
|
||||
{props.showModeSelector ? (
|
||||
<View className="mt-2 flex-row items-center gap-2">
|
||||
<ModeButton
|
||||
active={props.activeMode === "preview"}
|
||||
icon="eye"
|
||||
label="Preview"
|
||||
onPress={() => props.onSetMode("preview")}
|
||||
/>
|
||||
<ModeButton
|
||||
active={props.activeMode === "source"}
|
||||
icon="doc.text"
|
||||
label="Source"
|
||||
onPress={() => props.onSetMode("source")}
|
||||
/>
|
||||
{props.externalPreviewUri !== undefined ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Open preview in Safari"
|
||||
disabled={props.externalPreviewUri === null}
|
||||
hitSlop={8}
|
||||
className={cn(
|
||||
"ml-auto h-8 w-8 items-center justify-center rounded-full bg-subtle active:opacity-70",
|
||||
props.externalPreviewUri === null && "opacity-40",
|
||||
)}
|
||||
onPress={() => {
|
||||
if (typeof props.externalPreviewUri === "string") {
|
||||
void Linking.openURL(props.externalPreviewUri);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SymbolView name="safari" size={15} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FileContent(props: {
|
||||
readonly activeMode: FileViewMode;
|
||||
readonly previewUri: string | null;
|
||||
readonly fileContents: string | null;
|
||||
readonly fileError: string | null;
|
||||
readonly relativePath: string;
|
||||
readonly initialLine: number | null;
|
||||
readonly truncated: boolean;
|
||||
}) {
|
||||
const isMarkdown = isMarkdownPreviewFile(props.relativePath);
|
||||
const isBrowserFile = isBrowserPreviewFile(props.relativePath);
|
||||
const isImageFile = isImagePreviewFile(props.relativePath);
|
||||
|
||||
if (props.activeMode === "preview" && isImageFile) {
|
||||
if (isSvgImagePreviewFile(props.relativePath)) {
|
||||
return <WorkspaceFileWebPreview uri={props.previewUri} />;
|
||||
}
|
||||
return (
|
||||
<WorkspaceFileImagePreview
|
||||
accessibilityLabel={basename(props.relativePath)}
|
||||
uri={props.previewUri}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.activeMode === "preview" && isBrowserFile) {
|
||||
return <WorkspaceFileWebPreview uri={props.previewUri} />;
|
||||
}
|
||||
|
||||
if (props.fileError && props.fileContents === null) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center bg-card px-6">
|
||||
<EmptyState title="File unavailable" detail={props.fileError} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.fileContents === null) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
|
||||
<ActivityIndicator />
|
||||
<Text className="text-center text-[13px] text-foreground-muted">Loading file...</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-card">
|
||||
{props.truncated ? (
|
||||
<View className="border-b border-amber-200 bg-amber-50 px-4 py-2 dark:border-amber-900/60 dark:bg-amber-950/40">
|
||||
<Text className="text-[11px] font-t3-bold uppercase text-amber-700 dark:text-amber-300">
|
||||
Partial file
|
||||
</Text>
|
||||
<Text className="text-[12px] leading-[17px] text-amber-800 dark:text-amber-200">
|
||||
Preview limited to the first 1 MB of a truncated file.
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{props.activeMode === "preview" && isMarkdown ? (
|
||||
<FileMarkdownPreview markdown={props.fileContents} />
|
||||
) : (
|
||||
<SourceFileSurface
|
||||
contents={props.fileContents}
|
||||
path={props.relativePath}
|
||||
initialLine={props.initialLine}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function useThreadFilesWorkspace() {
|
||||
const params = useLocalSearchParams<{
|
||||
environmentId?: string | string[];
|
||||
threadId?: string | string[];
|
||||
}>();
|
||||
const routeEnvironmentId = firstRouteParam(params.environmentId);
|
||||
const routeThreadId = firstRouteParam(params.threadId);
|
||||
const { selectedThread, selectedThreadProject } = useThreadSelection();
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const environmentId =
|
||||
routeEnvironmentId !== null
|
||||
? EnvironmentId.make(routeEnvironmentId)
|
||||
: (selectedThread?.environmentId ?? null);
|
||||
const threadId = routeThreadId !== null ? ThreadId.make(routeThreadId) : null;
|
||||
const project = selectedThreadProject as {
|
||||
readonly title?: string;
|
||||
readonly workspaceRoot?: string;
|
||||
} | null;
|
||||
|
||||
return {
|
||||
cwd: selectedThreadCwd ?? project?.workspaceRoot ?? null,
|
||||
environmentId,
|
||||
projectName: project?.title ?? "Files",
|
||||
selectedThread,
|
||||
threadId,
|
||||
};
|
||||
}
|
||||
|
||||
function FilesUnavailable() {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center bg-sheet px-6">
|
||||
<Stack.Screen options={{ title: "Files" }} />
|
||||
<EmptyState
|
||||
title="Files unavailable"
|
||||
detail="This thread does not have an active workspace path."
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FilesHeaderTitle(props: { readonly projectName: string }) {
|
||||
const foregroundColor = String(useThemeColor("--color-foreground"));
|
||||
const secondaryForegroundColor = String(useThemeColor("--color-foreground-secondary"));
|
||||
|
||||
return (
|
||||
<View style={{ alignItems: "center", maxWidth: 220 }}>
|
||||
<RNText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: foregroundColor,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 18,
|
||||
fontWeight: "900",
|
||||
letterSpacing: -0.4,
|
||||
}}
|
||||
>
|
||||
Files
|
||||
</RNText>
|
||||
<RNText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: secondaryForegroundColor,
|
||||
fontFamily: "DMSans_500Medium",
|
||||
fontSize: 12,
|
||||
fontWeight: "500",
|
||||
letterSpacing: 0.2,
|
||||
}}
|
||||
>
|
||||
{props.projectName}
|
||||
</RNText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FilesToolbarBottomFade() {
|
||||
const sheetColor = String(useThemeColor("--color-sheet"));
|
||||
|
||||
if (process.env.EXPO_OS !== "ios") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<View
|
||||
pointerEvents="none"
|
||||
accessibilityElementsHidden
|
||||
importantForAccessibility="no-hide-descendants"
|
||||
style={{
|
||||
bottom: 0,
|
||||
height: 112,
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
right: 0,
|
||||
zIndex: 1,
|
||||
}}
|
||||
>
|
||||
<Svg width="100%" height="100%">
|
||||
<Defs>
|
||||
<LinearGradient id="files-toolbar-bottom-fade" x1="0%" x2="0%" y1="0%" y2="100%">
|
||||
<Stop offset="0%" stopColor={sheetColor} stopOpacity={0} />
|
||||
<Stop offset="58%" stopColor={sheetColor} stopOpacity={0.72} />
|
||||
<Stop offset="100%" stopColor={sheetColor} stopOpacity={0.96} />
|
||||
</LinearGradient>
|
||||
</Defs>
|
||||
<Rect width="100%" height="100%" fill="url(#files-toolbar-bottom-fade)" />
|
||||
</Svg>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ThreadFilesTreeScreen() {
|
||||
const router = useRouter();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
|
||||
const entriesQuery = useEnvironmentQuery(
|
||||
environmentId !== null && cwd !== null
|
||||
? projectEnvironment.listEntries({
|
||||
environmentId,
|
||||
input: { cwd },
|
||||
})
|
||||
: null,
|
||||
);
|
||||
const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
|
||||
|
||||
const handleSelectFile = useCallback(
|
||||
(path: string) => {
|
||||
if (environmentId === null || threadId === null) {
|
||||
return;
|
||||
}
|
||||
router.push(buildThreadFilesNavigation({ environmentId, threadId }, path));
|
||||
},
|
||||
[environmentId, router, threadId],
|
||||
);
|
||||
|
||||
if (selectedThread === null || environmentId === null || threadId === null) {
|
||||
return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
|
||||
}
|
||||
|
||||
if (cwd === null) {
|
||||
return <FilesUnavailable />;
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "Files",
|
||||
headerShown: true,
|
||||
headerTransparent: true,
|
||||
headerStyle: { backgroundColor: "transparent" },
|
||||
headerShadowVisible: false,
|
||||
headerTitle: () => <FilesHeaderTitle projectName={projectName} />,
|
||||
headerSearchBarOptions: {
|
||||
allowToolbarIntegration: true,
|
||||
autoCapitalize: "none",
|
||||
hideNavigationBar: false,
|
||||
placeholder: "Search files",
|
||||
onChangeText: (event) => {
|
||||
setSearchQuery(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
setSearchQuery("");
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Button
|
||||
accessibilityLabel="Refresh files"
|
||||
icon="arrow.clockwise"
|
||||
onPress={entriesQuery.refresh}
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
<Stack.Toolbar placement="bottom">
|
||||
<Stack.Toolbar.SearchBarSlot />
|
||||
</Stack.Toolbar>
|
||||
<FileTreeBrowser
|
||||
entries={entriesData?.entries ?? []}
|
||||
error={entriesQuery.error}
|
||||
isPending={entriesQuery.isPending}
|
||||
searchQuery={searchQuery}
|
||||
selectedPath={null}
|
||||
onRefresh={entriesQuery.refresh}
|
||||
onSelectFile={handleSelectFile}
|
||||
/>
|
||||
<FilesToolbarBottomFade />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ThreadFileScreen() {
|
||||
const params = useLocalSearchParams<{
|
||||
line?: string | string[];
|
||||
path?: string | string[];
|
||||
}>();
|
||||
const relativePath = normalizeRoutePath(params.path);
|
||||
const targetLine = normalizeRouteLine(firstRouteParam(params.line));
|
||||
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
|
||||
const [modeOverride, setModeOverride] = useState<{
|
||||
readonly path: string;
|
||||
readonly mode: FileViewMode;
|
||||
} | null>(null);
|
||||
const [previewRevision, setPreviewRevision] = useState(0);
|
||||
const isBrowserFile = relativePath !== null && isBrowserPreviewFile(relativePath);
|
||||
const isImageFile = relativePath !== null && isImagePreviewFile(relativePath);
|
||||
const canPreview =
|
||||
relativePath !== null && (isMarkdownPreviewFile(relativePath) || isBrowserFile || isImageFile);
|
||||
const activeMode =
|
||||
relativePath !== null && modeOverride?.path === relativePath
|
||||
? modeOverride.mode
|
||||
: defaultViewMode(relativePath);
|
||||
const resolvedActiveMode = canPreview ? activeMode : "source";
|
||||
const assetPreviewPath = isBrowserFile || isImageFile ? relativePath : null;
|
||||
const assetPreviewUri = useWorkspaceFileAssetUrl({
|
||||
cwd,
|
||||
environmentId,
|
||||
relativePath: assetPreviewPath,
|
||||
threadId,
|
||||
});
|
||||
const previewUri =
|
||||
assetPreviewUri === null || previewRevision === 0
|
||||
? assetPreviewUri
|
||||
: `${assetPreviewUri}${assetPreviewUri.includes("?") ? "&" : "?"}revision=${previewRevision}`;
|
||||
const needsFileContents =
|
||||
relativePath !== null &&
|
||||
(resolvedActiveMode === "source" || isMarkdownPreviewFile(relativePath));
|
||||
const fileQuery = useEnvironmentQuery(
|
||||
environmentId !== null && cwd !== null && relativePath !== null && needsFileContents
|
||||
? projectEnvironment.readFile({
|
||||
environmentId,
|
||||
input: { cwd, relativePath },
|
||||
})
|
||||
: null,
|
||||
);
|
||||
const fileData = fileQuery.data as ProjectReadFileResult | null;
|
||||
|
||||
if (selectedThread === null || environmentId === null || threadId === null) {
|
||||
return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
|
||||
}
|
||||
|
||||
if (cwd === null) {
|
||||
return <FilesUnavailable />;
|
||||
}
|
||||
|
||||
if (relativePath === null) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center bg-sheet px-6">
|
||||
<Stack.Screen options={{ title: "Files" }} />
|
||||
<EmptyState title="File unavailable" detail="This file path is invalid." />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ReviewHighlighterProvider>
|
||||
<View className="flex-1 bg-sheet">
|
||||
<Stack.Screen options={{ title: basename(relativePath) }} />
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Button
|
||||
icon="arrow.clockwise"
|
||||
onPress={() => {
|
||||
if (resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)) {
|
||||
setPreviewRevision((current) => current + 1);
|
||||
return;
|
||||
}
|
||||
fileQuery.refresh();
|
||||
}}
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
<FilePreviewHeader
|
||||
activeMode={resolvedActiveMode}
|
||||
showModeSelector={canPreview && !isImageFile}
|
||||
externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
|
||||
projectName={projectName}
|
||||
relativePath={relativePath}
|
||||
onSetMode={(mode) => {
|
||||
setModeOverride({ path: relativePath, mode });
|
||||
}}
|
||||
/>
|
||||
<FileContent
|
||||
activeMode={resolvedActiveMode}
|
||||
previewUri={previewUri}
|
||||
fileContents={fileData?.contents ?? null}
|
||||
fileError={fileQuery.error}
|
||||
initialLine={targetLine}
|
||||
relativePath={relativePath}
|
||||
truncated={fileData?.truncated ?? false}
|
||||
/>
|
||||
</View>
|
||||
</ReviewHighlighterProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { ActivityIndicator, Image, Pressable, View } from "react-native";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { workspaceFileImageAtom } from "./workspace-file-image-cache";
|
||||
|
||||
function ResolvedWorkspaceFileImagePreview(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly uri: string;
|
||||
}) {
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [fullScreenVisible, setFullScreenVisible] = useState(false);
|
||||
const imageSource = useMemo(
|
||||
() => ({ uri: props.uri, cache: "force-cache" as const }),
|
||||
[props.uri],
|
||||
);
|
||||
const fullScreenImages = useMemo(() => [imageSource], [imageSource]);
|
||||
|
||||
return (
|
||||
<View className="relative flex-1 bg-subtle">
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Open full-screen preview of ${props.accessibilityLabel}`}
|
||||
disabled={loadError !== null}
|
||||
className="flex-1 p-4 active:bg-subtle-strong"
|
||||
onPress={() => setFullScreenVisible(true)}
|
||||
>
|
||||
<Image
|
||||
accessible={false}
|
||||
source={imageSource}
|
||||
className="h-full w-full"
|
||||
resizeMode="contain"
|
||||
onLoadStart={() => setLoadError(null)}
|
||||
onError={(event) => {
|
||||
setLoadError(event.nativeEvent.error || "The image could not be rendered.");
|
||||
}}
|
||||
/>
|
||||
</Pressable>
|
||||
|
||||
{loadError !== null ? (
|
||||
<View className="absolute inset-0 items-center justify-center bg-card px-6">
|
||||
<EmptyState title="Image unavailable" detail={loadError} />
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<ImageViewing
|
||||
images={fullScreenImages}
|
||||
imageIndex={0}
|
||||
visible={fullScreenVisible}
|
||||
onRequestClose={() => setFullScreenVisible(false)}
|
||||
swipeToCloseEnabled
|
||||
doubleTapToZoomEnabled
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function CachedWorkspaceFileImagePreview(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly uri: string;
|
||||
}) {
|
||||
const imageAtom = useMemo(() => workspaceFileImageAtom(props.uri), [props.uri]);
|
||||
const imageResult = useAtomValue(imageAtom);
|
||||
|
||||
if (AsyncResult.isFailure(imageResult)) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center bg-card px-6">
|
||||
<EmptyState
|
||||
title="Image unavailable"
|
||||
detail="The image could not be loaded into the local cache."
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (!AsyncResult.isSuccess(imageResult)) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
|
||||
<ActivityIndicator />
|
||||
<Text className="text-center text-[13px] text-foreground-muted">Loading image...</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ResolvedWorkspaceFileImagePreview
|
||||
accessibilityLabel={props.accessibilityLabel}
|
||||
uri={imageResult.value}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function WorkspaceFileImagePreview(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly uri: string | null;
|
||||
}) {
|
||||
if (props.uri === null) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
|
||||
<ActivityIndicator />
|
||||
<Text className="text-center text-[13px] text-foreground-muted">
|
||||
Preparing image preview...
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CachedWorkspaceFileImagePreview
|
||||
accessibilityLabel={props.accessibilityLabel}
|
||||
uri={props.uri}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { ActivityIndicator, View } from "react-native";
|
||||
import { WebView } from "react-native-webview";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { LoadingStrip } from "../../components/LoadingStrip";
|
||||
|
||||
export function WorkspaceFileWebPreview(props: { readonly uri: string | null }) {
|
||||
const [loadProgress, setLoadProgress] = useState(0);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
|
||||
if (props.uri === null) {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center gap-3 bg-card px-6">
|
||||
<ActivityIndicator />
|
||||
<Text className="text-center text-[13px] text-foreground-muted">Preparing preview...</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="relative flex-1 bg-card">
|
||||
{loadProgress > 0 && loadProgress < 1 ? <LoadingStrip progress={loadProgress} /> : null}
|
||||
{loadError ? (
|
||||
<View className="border-b border-border bg-card px-4 py-2">
|
||||
<Text className="text-[12px] font-t3-bold text-foreground">Preview failed</Text>
|
||||
<Text className="mt-0.5 text-[12px] leading-[17px] text-foreground-muted">
|
||||
{loadError}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
<WebView
|
||||
source={{ uri: props.uri }}
|
||||
originWhitelist={["*"]}
|
||||
allowsBackForwardNavigationGestures
|
||||
allowsFullscreenVideo
|
||||
setSupportMultipleWindows={false}
|
||||
startInLoadingState
|
||||
onLoadProgress={(event) => {
|
||||
setLoadProgress(event.nativeEvent.progress);
|
||||
}}
|
||||
onLoadStart={() => {
|
||||
setLoadProgress(0.05);
|
||||
setLoadError(null);
|
||||
}}
|
||||
onLoadEnd={() => {
|
||||
setLoadProgress(0);
|
||||
}}
|
||||
onError={(event) => {
|
||||
setLoadProgress(0);
|
||||
setLoadError(event.nativeEvent.description || "The file could not be rendered.");
|
||||
}}
|
||||
renderLoading={() => (
|
||||
<View className="absolute inset-0 items-center justify-center bg-card">
|
||||
<ActivityIndicator />
|
||||
</View>
|
||||
)}
|
||||
style={{ flex: 1, backgroundColor: "transparent" }}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
isBrowserPreviewFile,
|
||||
isImagePreviewFile,
|
||||
isSvgImagePreviewFile,
|
||||
resolveWorkspaceRelativeFilePath,
|
||||
} from "./filePath";
|
||||
|
||||
describe("resolveWorkspaceRelativeFilePath", () => {
|
||||
it("keeps normalized workspace-relative paths", () => {
|
||||
expect(resolveWorkspaceRelativeFilePath("/repo", "./src/../src/main.ts")).toBe("src/main.ts");
|
||||
});
|
||||
|
||||
it("converts absolute paths inside the workspace", () => {
|
||||
expect(
|
||||
resolveWorkspaceRelativeFilePath("/Users/julius/repo", "/Users/julius/repo/src/main.ts"),
|
||||
).toBe("src/main.ts");
|
||||
expect(resolveWorkspaceRelativeFilePath("C:\\repo", "c:\\repo\\src\\main.ts")).toBe(
|
||||
"src/main.ts",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects paths outside the workspace", () => {
|
||||
expect(resolveWorkspaceRelativeFilePath("/repo", "/other/main.ts")).toBeNull();
|
||||
expect(resolveWorkspaceRelativeFilePath("/repo", "../other/main.ts")).toBeNull();
|
||||
expect(resolveWorkspaceRelativeFilePath(null, "/repo/main.ts")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("file preview types", () => {
|
||||
it("recognizes browser and image previews", () => {
|
||||
expect(isBrowserPreviewFile("reports/summary.html")).toBe(true);
|
||||
expect(isImagePreviewFile("assets/icon.png")).toBe(true);
|
||||
expect(isImagePreviewFile("assets/diagram.SVG?raw=1")).toBe(true);
|
||||
expect(isImagePreviewFile("src/image.ts")).toBe(false);
|
||||
});
|
||||
|
||||
it("identifies SVG images that need web rendering", () => {
|
||||
expect(isSvgImagePreviewFile("assets/diagram.svg#icon")).toBe(true);
|
||||
expect(isSvgImagePreviewFile("assets/photo.png")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,116 +0,0 @@
|
||||
import {
|
||||
isWorkspaceBrowserPreviewPath,
|
||||
isWorkspaceImagePreviewPath,
|
||||
} from "@t3tools/shared/filePreview";
|
||||
|
||||
export interface FileBreadcrumb {
|
||||
readonly label: string;
|
||||
readonly path: string;
|
||||
readonly kind: "project" | "directory" | "file";
|
||||
}
|
||||
|
||||
function isWindowsAbsolutePath(value: string): boolean {
|
||||
return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
|
||||
}
|
||||
|
||||
function isAbsolutePath(value: string): boolean {
|
||||
return value.startsWith("/") || isWindowsAbsolutePath(value);
|
||||
}
|
||||
|
||||
function isWindowsPathStyle(value: string): boolean {
|
||||
return isWindowsAbsolutePath(value) || /^[A-Za-z]:\\/.test(value);
|
||||
}
|
||||
|
||||
function joinPath(base: string, next: string, separator: "/" | "\\"): string {
|
||||
const cleanBase = base.replace(/[\\/]+$/, "");
|
||||
if (separator === "\\") {
|
||||
return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
|
||||
}
|
||||
return `${cleanBase}/${next.replace(/^\/+/, "")}`;
|
||||
}
|
||||
|
||||
export function basename(path: string): string {
|
||||
const parts = path.split(/[\\/]/).filter(Boolean);
|
||||
return parts.at(-1) ?? path;
|
||||
}
|
||||
|
||||
export function resolveWorkspaceFilePath(cwd: string, relativePath: string): string {
|
||||
if (isAbsolutePath(relativePath)) {
|
||||
return relativePath;
|
||||
}
|
||||
|
||||
const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
|
||||
return joinPath(cwd, relativePath, separator);
|
||||
}
|
||||
|
||||
function normalizeRelativePath(value: string): string | null {
|
||||
const segments: string[] = [];
|
||||
for (const segment of value.replaceAll("\\", "/").split("/")) {
|
||||
if (segment.length === 0 || segment === ".") {
|
||||
continue;
|
||||
}
|
||||
if (segment === "..") {
|
||||
if (segments.length === 0) {
|
||||
return null;
|
||||
}
|
||||
segments.pop();
|
||||
continue;
|
||||
}
|
||||
segments.push(segment);
|
||||
}
|
||||
return segments.length > 0 ? segments.join("/") : null;
|
||||
}
|
||||
|
||||
export function resolveWorkspaceRelativeFilePath(
|
||||
workspaceRoot: string | null | undefined,
|
||||
targetPath: string,
|
||||
): string | null {
|
||||
if (!isAbsolutePath(targetPath)) {
|
||||
if (targetPath.startsWith("~/") || targetPath.startsWith("~\\")) {
|
||||
return null;
|
||||
}
|
||||
return normalizeRelativePath(targetPath);
|
||||
}
|
||||
if (!workspaceRoot) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalizedTarget = targetPath.replaceAll("\\", "/");
|
||||
const normalizedRoot = workspaceRoot.replaceAll("\\", "/").replace(/\/+$/, "");
|
||||
const caseInsensitive = isWindowsAbsolutePath(targetPath) || isWindowsAbsolutePath(workspaceRoot);
|
||||
const comparableTarget = caseInsensitive ? normalizedTarget.toLowerCase() : normalizedTarget;
|
||||
const comparableRoot = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;
|
||||
if (!comparableTarget.startsWith(`${comparableRoot}/`)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeRelativePath(normalizedTarget.slice(normalizedRoot.length + 1));
|
||||
}
|
||||
|
||||
export function isBrowserPreviewFile(path: string): boolean {
|
||||
return isWorkspaceBrowserPreviewPath(path);
|
||||
}
|
||||
|
||||
export function isImagePreviewFile(path: string): boolean {
|
||||
return isWorkspaceImagePreviewPath(path);
|
||||
}
|
||||
|
||||
export function isSvgImagePreviewFile(path: string): boolean {
|
||||
return /\.svg$/i.test(path.split(/[?#]/, 1)[0] ?? "");
|
||||
}
|
||||
|
||||
export function isMarkdownPreviewFile(path: string): boolean {
|
||||
return /\.(?:md|mdx)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
|
||||
}
|
||||
|
||||
export function fileBreadcrumbs(projectName: string, relativePath: string): FileBreadcrumb[] {
|
||||
const parts = relativePath.split("/").filter(Boolean);
|
||||
return [
|
||||
{ label: projectName, path: "", kind: "project" },
|
||||
...parts.map((part, index) => ({
|
||||
label: part,
|
||||
path: parts.slice(0, index + 1).join("/"),
|
||||
kind: index === parts.length - 1 ? ("file" as const) : ("directory" as const),
|
||||
})),
|
||||
];
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type { ProjectEntry } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildFileTree,
|
||||
countFileNodes,
|
||||
defaultExpandedTreePaths,
|
||||
firstFilePath,
|
||||
flattenFileTree,
|
||||
} from "./fileTree";
|
||||
|
||||
const entries = [
|
||||
{ kind: "file", path: "README.md" },
|
||||
{ kind: "directory", path: "src" },
|
||||
{ kind: "file", path: "src/index.ts" },
|
||||
{ kind: "file", path: "src/components/App.tsx" },
|
||||
{ kind: "file", path: "package.json" },
|
||||
] satisfies ReadonlyArray<ProjectEntry>;
|
||||
|
||||
describe("mobile file tree helpers", () => {
|
||||
it("builds a deterministic hierarchy with directories before files", () => {
|
||||
const tree = buildFileTree(entries);
|
||||
|
||||
expect(tree.map((node) => `${node.kind}:${node.path}`)).toEqual([
|
||||
"directory:src",
|
||||
"file:package.json",
|
||||
"file:README.md",
|
||||
]);
|
||||
expect(tree[0]?.children.map((node) => `${node.kind}:${node.path}`)).toEqual([
|
||||
"directory:src/components",
|
||||
"file:src/index.ts",
|
||||
]);
|
||||
expect(countFileNodes(tree)).toBe(4);
|
||||
expect(firstFilePath(tree)).toBe("src/components/App.tsx");
|
||||
});
|
||||
|
||||
it("flattens expanded directories and hides collapsed descendants", () => {
|
||||
const tree = buildFileTree(entries);
|
||||
|
||||
expect(
|
||||
flattenFileTree({
|
||||
nodes: tree,
|
||||
expanded: new Set(["src"]),
|
||||
}).map((item) => `${item.depth}:${item.node.path}`),
|
||||
).toEqual(["0:src", "1:src/components", "1:src/index.ts", "0:package.json", "0:README.md"]);
|
||||
|
||||
expect(
|
||||
flattenFileTree({
|
||||
nodes: tree,
|
||||
expanded: new Set(),
|
||||
}).map((item) => item.node.path),
|
||||
).toEqual(["src", "package.json", "README.md"]);
|
||||
});
|
||||
|
||||
it("includes matching descendants and their ancestors during search", () => {
|
||||
const tree = buildFileTree(entries);
|
||||
|
||||
expect(
|
||||
flattenFileTree({
|
||||
nodes: tree,
|
||||
expanded: new Set(),
|
||||
searchQuery: "app",
|
||||
}).map((item) => item.node.path),
|
||||
).toEqual(["src", "src/components", "src/components/App.tsx"]);
|
||||
});
|
||||
|
||||
it("supports fuzzy, whitespace-separated path queries", () => {
|
||||
const tree = buildFileTree([
|
||||
{
|
||||
kind: "file",
|
||||
path: ".plans/19-version-control-phase-1-vcs-driver-foundation.md",
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
path: ".repos/alchemy-effect/examples/aws-lambda/src/JobNotifications.ts",
|
||||
},
|
||||
{ kind: "directory", path: "apps/web/src/components/chat" },
|
||||
{ kind: "file", path: "apps/web/src/components/chat/ChatHeader.test.ts" },
|
||||
{ kind: "file", path: "apps/web/src/components/chat/ChatHeader.tsx" },
|
||||
{ kind: "file", path: "apps/web/src/components/chat/Composer.tsx" },
|
||||
]);
|
||||
|
||||
const expectedPaths = [
|
||||
"apps",
|
||||
"apps/web",
|
||||
"apps/web/src",
|
||||
"apps/web/src/components",
|
||||
"apps/web/src/components/chat",
|
||||
"apps/web/src/components/chat/ChatHeader.test.ts",
|
||||
"apps/web/src/components/chat/ChatHeader.tsx",
|
||||
];
|
||||
|
||||
for (const searchQuery of ["chat hea", "cht hdr"]) {
|
||||
expect(
|
||||
flattenFileTree({
|
||||
nodes: tree,
|
||||
expanded: new Set(),
|
||||
searchQuery,
|
||||
}).map((item) => item.node.path),
|
||||
).toEqual(expectedPaths);
|
||||
}
|
||||
});
|
||||
|
||||
it("expands top-level directories by default", () => {
|
||||
const tree = buildFileTree(entries);
|
||||
|
||||
expect([...defaultExpandedTreePaths(tree)]).toEqual(["src"]);
|
||||
});
|
||||
});
|
||||
@@ -1,220 +0,0 @@
|
||||
import type { ProjectEntry } from "@t3tools/contracts";
|
||||
import { normalizeSearchQuery, scoreQueryMatch } from "@t3tools/shared/searchRanking";
|
||||
|
||||
export interface FileTreeNode {
|
||||
readonly path: string;
|
||||
readonly name: string;
|
||||
readonly kind: ProjectEntry["kind"];
|
||||
readonly children: ReadonlyArray<FileTreeNode>;
|
||||
readonly searchSegments: ReadonlyArray<string>;
|
||||
readonly searchWords: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export interface VisibleFileTreeNode {
|
||||
readonly node: FileTreeNode;
|
||||
readonly depth: number;
|
||||
}
|
||||
|
||||
interface MutableFileTreeNode {
|
||||
path: string;
|
||||
name: string;
|
||||
kind: ProjectEntry["kind"];
|
||||
children: Map<string, MutableFileTreeNode>;
|
||||
}
|
||||
|
||||
function createMutableNode(
|
||||
path: string,
|
||||
name: string,
|
||||
kind: ProjectEntry["kind"],
|
||||
): MutableFileTreeNode {
|
||||
return {
|
||||
path,
|
||||
name,
|
||||
kind,
|
||||
children: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
function splitSearchWords(value: string): ReadonlyArray<string> {
|
||||
return value
|
||||
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.split(/[^A-Za-z0-9]+/)
|
||||
.filter(Boolean)
|
||||
.map((word) => word.toLowerCase());
|
||||
}
|
||||
|
||||
function buildNodeSearchTerms(path: string): {
|
||||
readonly segments: ReadonlyArray<string>;
|
||||
readonly words: ReadonlyArray<string>;
|
||||
} {
|
||||
const segments: string[] = [];
|
||||
const words: string[] = [];
|
||||
|
||||
for (const segment of path.split("/")) {
|
||||
if (!segment) {
|
||||
continue;
|
||||
}
|
||||
segments.push(segment.toLowerCase());
|
||||
words.push(...splitSearchWords(segment));
|
||||
}
|
||||
|
||||
return { segments, words };
|
||||
}
|
||||
|
||||
function freezeNode(node: MutableFileTreeNode): FileTreeNode {
|
||||
const searchTerms = buildNodeSearchTerms(node.path);
|
||||
return {
|
||||
path: node.path,
|
||||
name: node.name,
|
||||
kind: node.kind,
|
||||
children: [...node.children.values()].sort(compareNodes).map(freezeNode),
|
||||
searchSegments: searchTerms.segments,
|
||||
searchWords: searchTerms.words,
|
||||
};
|
||||
}
|
||||
|
||||
function compareNodes(
|
||||
left: Pick<FileTreeNode, "kind" | "name">,
|
||||
right: Pick<FileTreeNode, "kind" | "name">,
|
||||
): number {
|
||||
if (left.kind !== right.kind) {
|
||||
return left.kind === "directory" ? -1 : 1;
|
||||
}
|
||||
return left.name.localeCompare(right.name, undefined, { numeric: true, sensitivity: "base" });
|
||||
}
|
||||
|
||||
export function buildFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<FileTreeNode> {
|
||||
const root = createMutableNode("", "", "directory");
|
||||
|
||||
for (const entry of entries) {
|
||||
const parts = entry.path.split("/").filter(Boolean);
|
||||
if (parts.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let current = root;
|
||||
for (let index = 0; index < parts.length; index += 1) {
|
||||
const part = parts[index];
|
||||
if (!part) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const path = parts.slice(0, index + 1).join("/");
|
||||
const isLeaf = index === parts.length - 1;
|
||||
const kind = isLeaf ? entry.kind : "directory";
|
||||
let child = current.children.get(part);
|
||||
if (!child) {
|
||||
child = createMutableNode(path, part, kind);
|
||||
current.children.set(part, child);
|
||||
} else if (isLeaf) {
|
||||
child.kind = entry.kind;
|
||||
}
|
||||
current = child;
|
||||
}
|
||||
}
|
||||
|
||||
return [...root.children.values()].sort(compareNodes).map(freezeNode);
|
||||
}
|
||||
|
||||
export function countFileNodes(nodes: ReadonlyArray<FileTreeNode>): number {
|
||||
let count = 0;
|
||||
for (const node of nodes) {
|
||||
if (node.kind === "file") {
|
||||
count += 1;
|
||||
} else {
|
||||
count += countFileNodes(node.children);
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
export function defaultExpandedTreePaths(nodes: ReadonlyArray<FileTreeNode>): ReadonlySet<string> {
|
||||
const expanded = new Set<string>();
|
||||
for (const node of nodes) {
|
||||
if (node.kind === "directory") {
|
||||
expanded.add(node.path);
|
||||
}
|
||||
}
|
||||
return expanded;
|
||||
}
|
||||
|
||||
function valueMatchesSearchToken(value: string, token: string, fuzzy: boolean): boolean {
|
||||
return (
|
||||
scoreQueryMatch({
|
||||
value,
|
||||
query: token,
|
||||
exactBase: 0,
|
||||
prefixBase: 2,
|
||||
boundaryBase: 4,
|
||||
includesBase: 6,
|
||||
...(fuzzy ? { fuzzyBase: 100 } : {}),
|
||||
boundaryMarkers: ["/", "-", "_", "."],
|
||||
}) !== null
|
||||
);
|
||||
}
|
||||
|
||||
function nodeMatchesSearch(node: FileTreeNode, tokens: ReadonlyArray<string>): boolean {
|
||||
return tokens.every(
|
||||
(token) =>
|
||||
node.searchSegments.some((segment) => valueMatchesSearchToken(segment, token, false)) ||
|
||||
node.searchWords.some((word) => valueMatchesSearchToken(word, token, true)),
|
||||
);
|
||||
}
|
||||
|
||||
function flattenNode(
|
||||
output: VisibleFileTreeNode[],
|
||||
node: FileTreeNode,
|
||||
depth: number,
|
||||
expanded: ReadonlySet<string>,
|
||||
searchTokens: ReadonlyArray<string>,
|
||||
): boolean {
|
||||
const isSearching = searchTokens.length > 0;
|
||||
const matches = isSearching && nodeMatchesSearch(node, searchTokens);
|
||||
let descendantMatches = false;
|
||||
const childOutput: VisibleFileTreeNode[] = [];
|
||||
|
||||
if (node.kind === "directory" && (expanded.has(node.path) || isSearching)) {
|
||||
for (const child of node.children) {
|
||||
if (flattenNode(childOutput, child, depth + 1, expanded, searchTokens)) {
|
||||
descendantMatches = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const visible = !isSearching || matches || descendantMatches;
|
||||
if (!visible) {
|
||||
return false;
|
||||
}
|
||||
|
||||
output.push({ node, depth });
|
||||
output.push(...childOutput);
|
||||
return matches || descendantMatches;
|
||||
}
|
||||
|
||||
export function flattenFileTree(input: {
|
||||
readonly nodes: ReadonlyArray<FileTreeNode>;
|
||||
readonly expanded: ReadonlySet<string>;
|
||||
readonly searchQuery?: string;
|
||||
}): ReadonlyArray<VisibleFileTreeNode> {
|
||||
const output: VisibleFileTreeNode[] = [];
|
||||
const normalizedSearch = normalizeSearchQuery(input.searchQuery ?? "");
|
||||
const searchTokens = normalizedSearch.split(/[\s/\\._-]+/).filter(Boolean);
|
||||
for (const node of input.nodes) {
|
||||
flattenNode(output, node, 0, input.expanded, searchTokens);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
export function firstFilePath(nodes: ReadonlyArray<FileTreeNode>): string | null {
|
||||
for (const node of nodes) {
|
||||
if (node.kind === "file") {
|
||||
return node.path;
|
||||
}
|
||||
const child = firstFilePath(node.children);
|
||||
if (child !== null) {
|
||||
return child;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildNativeSourceRows,
|
||||
buildNativeSourceTokens,
|
||||
nativeSourceRowId,
|
||||
} from "./nativeSourceFileAdapter";
|
||||
|
||||
describe("nativeSourceFileAdapter", () => {
|
||||
it("maps plain source lines onto context rows with stable line numbers", () => {
|
||||
expect(buildNativeSourceRows(["const value = 1;", "\treturn value;"])).toEqual([
|
||||
{
|
||||
kind: "line",
|
||||
id: nativeSourceRowId(0),
|
||||
fileId: "source-file",
|
||||
content: "const value = 1;",
|
||||
change: "context",
|
||||
newLineNumber: 1,
|
||||
},
|
||||
{
|
||||
kind: "line",
|
||||
id: nativeSourceRowId(1),
|
||||
fileId: "source-file",
|
||||
content: " return value;",
|
||||
change: "context",
|
||||
newLineNumber: 2,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps cached source tokens to the same row identifiers", () => {
|
||||
expect(
|
||||
buildNativeSourceTokens([
|
||||
[{ content: "const", color: "#ff0000", fontStyle: 2 }],
|
||||
[{ content: "\tvalue", color: null, fontStyle: null }],
|
||||
]),
|
||||
).toEqual({
|
||||
[nativeSourceRowId(0)]: [{ content: "const", color: "#ff0000", fontStyle: 2 }],
|
||||
[nativeSourceRowId(1)]: [{ content: " value", color: null, fontStyle: null }],
|
||||
});
|
||||
});
|
||||
|
||||
it("clears native tokens while highlighting is unavailable", () => {
|
||||
expect(buildNativeSourceTokens(null)).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -1,65 +0,0 @@
|
||||
import type {
|
||||
NativeReviewDiffRow,
|
||||
NativeReviewDiffStyle,
|
||||
NativeReviewDiffToken,
|
||||
} from "../diffs/nativeReviewDiffSurface";
|
||||
import type { SourceHighlightTokens } from "./sourceHighlightingState";
|
||||
|
||||
export const NATIVE_SOURCE_ROW_HEIGHT = 24;
|
||||
export const NATIVE_SOURCE_CONTENT_WIDTH = 32_000;
|
||||
|
||||
export const NATIVE_SOURCE_STYLE: NativeReviewDiffStyle = {
|
||||
rowHeight: NATIVE_SOURCE_ROW_HEIGHT,
|
||||
contentWidth: NATIVE_SOURCE_CONTENT_WIDTH,
|
||||
changeBarWidth: 0,
|
||||
gutterWidth: 58,
|
||||
codePadding: 8,
|
||||
codeFontSize: 13,
|
||||
codeFontWeight: "medium",
|
||||
lineNumberFontSize: 11,
|
||||
lineNumberFontWeight: "medium",
|
||||
emptyStateFontSize: 12,
|
||||
emptyStateFontWeight: "medium",
|
||||
};
|
||||
|
||||
const SOURCE_FILE_ID = "source-file";
|
||||
|
||||
function expandTabs(value: string): string {
|
||||
return value.replace(/\t/g, " ");
|
||||
}
|
||||
|
||||
export function nativeSourceRowId(index: number): string {
|
||||
return `source-line:${index}`;
|
||||
}
|
||||
|
||||
export function buildNativeSourceRows(
|
||||
lines: ReadonlyArray<string>,
|
||||
): ReadonlyArray<NativeReviewDiffRow> {
|
||||
return lines.map((line, index) => ({
|
||||
kind: "line",
|
||||
id: nativeSourceRowId(index),
|
||||
fileId: SOURCE_FILE_ID,
|
||||
content: expandTabs(line),
|
||||
change: "context",
|
||||
newLineNumber: index + 1,
|
||||
}));
|
||||
}
|
||||
|
||||
export function buildNativeSourceTokens(
|
||||
tokenLines: SourceHighlightTokens | null,
|
||||
): Readonly<Record<string, ReadonlyArray<NativeReviewDiffToken>>> {
|
||||
if (tokenLines === null) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return Object.fromEntries(
|
||||
tokenLines.map((tokens, index) => [
|
||||
nativeSourceRowId(index),
|
||||
tokens.map((token) => ({
|
||||
content: expandTabs(token.content),
|
||||
color: token.color,
|
||||
fontStyle: token.fontStyle,
|
||||
})),
|
||||
]),
|
||||
);
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createSourceHighlightAtomFamily,
|
||||
type SourceHighlightTokens,
|
||||
} from "./sourceHighlightingState";
|
||||
|
||||
const highlightedTokens: SourceHighlightTokens = [
|
||||
[{ content: "const", color: "#0000ff", fontStyle: null }],
|
||||
];
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("sourceHighlightingState", () => {
|
||||
it("reuses completed highlighting across equivalent route remounts", async () => {
|
||||
const highlight = vi.fn(async () => highlightedTokens);
|
||||
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight, idleTtlMs: 1_000 });
|
||||
const registry = AtomRegistry.make({ timeoutResolution: 1 });
|
||||
const input = {
|
||||
path: "src/example.ts",
|
||||
contents: "const value = 1;",
|
||||
theme: "light" as const,
|
||||
};
|
||||
const firstAtom = sourceHighlightAtom(input);
|
||||
const firstUnmount = registry.mount(firstAtom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isSuccess(registry.get(firstAtom))).toBe(true);
|
||||
});
|
||||
firstUnmount();
|
||||
|
||||
const remountedAtom = sourceHighlightAtom({ ...input });
|
||||
const secondUnmount = registry.mount(remountedAtom);
|
||||
|
||||
expect(remountedAtom).toBe(firstAtom);
|
||||
expect(AsyncResult.isSuccess(registry.get(remountedAtom))).toBe(true);
|
||||
expect(highlight).toHaveBeenCalledTimes(1);
|
||||
|
||||
secondUnmount();
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("does not reuse highlighting when the source contents change", async () => {
|
||||
const highlight = vi.fn(async () => highlightedTokens);
|
||||
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
|
||||
const registry = AtomRegistry.make();
|
||||
const firstAtom = sourceHighlightAtom({
|
||||
path: "src/example.ts",
|
||||
contents: "const value = 1;",
|
||||
theme: "light",
|
||||
});
|
||||
const secondAtom = sourceHighlightAtom({
|
||||
path: "src/example.ts",
|
||||
contents: "const value = 2;",
|
||||
theme: "light",
|
||||
});
|
||||
const firstUnmount = registry.mount(firstAtom);
|
||||
const secondUnmount = registry.mount(secondAtom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isSuccess(registry.get(firstAtom))).toBe(true);
|
||||
expect(AsyncResult.isSuccess(registry.get(secondAtom))).toBe(true);
|
||||
});
|
||||
expect(secondAtom).not.toBe(firstAtom);
|
||||
expect(highlight).toHaveBeenCalledTimes(2);
|
||||
|
||||
firstUnmount();
|
||||
secondUnmount();
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("recomputes highlighting after the idle cache entry expires", async () => {
|
||||
const highlight = vi.fn(async () => highlightedTokens);
|
||||
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight, idleTtlMs: 5 });
|
||||
const registry = AtomRegistry.make({ timeoutResolution: 1 });
|
||||
const atom = sourceHighlightAtom({
|
||||
path: "src/example.ts",
|
||||
contents: "const value = 1;",
|
||||
theme: "light",
|
||||
});
|
||||
const firstUnmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true);
|
||||
});
|
||||
firstUnmount();
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
|
||||
const secondUnmount = registry.mount(atom);
|
||||
await vi.waitFor(() => {
|
||||
expect(highlight).toHaveBeenCalledTimes(2);
|
||||
expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true);
|
||||
});
|
||||
|
||||
secondUnmount();
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("exposes highlighter errors as a failed async result", async () => {
|
||||
const highlight = vi.fn(async () => {
|
||||
throw new Error("highlight failed");
|
||||
});
|
||||
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
|
||||
const registry = AtomRegistry.make();
|
||||
const atom = sourceHighlightAtom({
|
||||
path: "src/example.ts",
|
||||
contents: "const value = 1;",
|
||||
theme: "light",
|
||||
});
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
});
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
});
|
||||
});
|
||||
@@ -1,50 +0,0 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
highlightSourceFile,
|
||||
type ReviewDiffTheme,
|
||||
type ReviewHighlightedToken,
|
||||
} from "../review/shikiReviewHighlighter";
|
||||
|
||||
const SOURCE_HIGHLIGHT_IDLE_TTL_MS = 5 * 60_000;
|
||||
|
||||
export interface SourceHighlightInput {
|
||||
readonly path: string;
|
||||
readonly contents: string;
|
||||
readonly theme: ReviewDiffTheme;
|
||||
}
|
||||
|
||||
export type SourceHighlightTokens = ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;
|
||||
|
||||
type SourceHighlighter = (input: SourceHighlightInput) => Promise<SourceHighlightTokens>;
|
||||
|
||||
class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}
|
||||
|
||||
class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export function createSourceHighlightAtomFamily(options?: {
|
||||
readonly highlight?: SourceHighlighter;
|
||||
readonly idleTtlMs?: number;
|
||||
}) {
|
||||
const highlight = options?.highlight ?? highlightSourceFile;
|
||||
const idleTtlMs = options?.idleTtlMs ?? SOURCE_HIGHLIGHT_IDLE_TTL_MS;
|
||||
const family = Atom.family((request: SourceHighlightCacheKey) =>
|
||||
Atom.make(
|
||||
Effect.tryPromise({
|
||||
try: () => highlight(request),
|
||||
catch: (cause) => new SourceHighlightError({ cause }),
|
||||
}),
|
||||
).pipe(
|
||||
Atom.setIdleTTL(idleTtlMs),
|
||||
Atom.withLabel(`mobile:source-highlight:${request.theme}:${request.path}`),
|
||||
),
|
||||
);
|
||||
|
||||
return (input: SourceHighlightInput) => family(new SourceHighlightCacheKey(input));
|
||||
}
|
||||
|
||||
export const sourceHighlightAtom = createSourceHighlightAtomFamily();
|
||||
@@ -1,64 +0,0 @@
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { createWorkspaceFileImageAtomFamily } from "./workspace-file-image-cache";
|
||||
|
||||
describe("workspaceFileImageAtom", () => {
|
||||
it("reuses a prefetched image across route remounts", async () => {
|
||||
const prefetch = vi.fn(async () => true);
|
||||
const imageAtom = createWorkspaceFileImageAtomFamily({ idleTtlMs: 1_000, prefetch });
|
||||
const registry = AtomRegistry.make({ timeoutResolution: 1 });
|
||||
const first = imageAtom("https://example.test/image.png");
|
||||
const firstUnmount = registry.mount(first);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isSuccess(registry.get(first))).toBe(true);
|
||||
});
|
||||
firstUnmount();
|
||||
|
||||
const remounted = imageAtom("https://example.test/image.png");
|
||||
const secondUnmount = registry.mount(remounted);
|
||||
|
||||
expect(remounted).toBe(first);
|
||||
expect(AsyncResult.isSuccess(registry.get(remounted))).toBe(true);
|
||||
expect(prefetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
secondUnmount();
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("prefetches different asset URLs independently", async () => {
|
||||
const prefetch = vi.fn(async () => true);
|
||||
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch });
|
||||
const registry = AtomRegistry.make();
|
||||
const first = imageAtom("https://example.test/first.png");
|
||||
const second = imageAtom("https://example.test/second.png");
|
||||
const firstUnmount = registry.mount(first);
|
||||
const secondUnmount = registry.mount(second);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isSuccess(registry.get(first))).toBe(true);
|
||||
expect(AsyncResult.isSuccess(registry.get(second))).toBe(true);
|
||||
});
|
||||
expect(prefetch).toHaveBeenCalledTimes(2);
|
||||
|
||||
firstUnmount();
|
||||
secondUnmount();
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("exposes prefetch failures", async () => {
|
||||
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: async () => false });
|
||||
const registry = AtomRegistry.make();
|
||||
const atom = imageAtom("https://example.test/missing.png");
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
});
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
});
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
const WORKSPACE_IMAGE_IDLE_TTL_MS = 30 * 60_000;
|
||||
|
||||
type ImagePrefetch = (uri: string) => Promise<boolean>;
|
||||
|
||||
class WorkspaceImageCacheKey extends Data.Class<{ readonly uri: string }> {}
|
||||
|
||||
export class WorkspaceImagePrefetchError extends Data.TaggedError("WorkspaceImagePrefetchError")<{
|
||||
readonly cause?: unknown;
|
||||
readonly uri: string;
|
||||
}> {}
|
||||
|
||||
async function prefetchWithNativeImage(uri: string): Promise<boolean> {
|
||||
const { Image } = await import("react-native");
|
||||
return Image.prefetch(uri);
|
||||
}
|
||||
|
||||
export function createWorkspaceFileImageAtomFamily(options?: {
|
||||
readonly idleTtlMs?: number;
|
||||
readonly prefetch?: ImagePrefetch;
|
||||
}) {
|
||||
const idleTtlMs = options?.idleTtlMs ?? WORKSPACE_IMAGE_IDLE_TTL_MS;
|
||||
const prefetch = options?.prefetch ?? prefetchWithNativeImage;
|
||||
const family = Atom.family((key: WorkspaceImageCacheKey) =>
|
||||
Atom.make(
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const cached = await prefetch(key.uri);
|
||||
if (!cached) {
|
||||
throw new WorkspaceImagePrefetchError({ uri: key.uri });
|
||||
}
|
||||
return key.uri;
|
||||
},
|
||||
catch: (cause) =>
|
||||
cause instanceof WorkspaceImagePrefetchError
|
||||
? cause
|
||||
: new WorkspaceImagePrefetchError({ uri: key.uri, cause }),
|
||||
}),
|
||||
).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`mobile:workspace-image:${key.uri}`)),
|
||||
);
|
||||
|
||||
return (uri: string) => family(new WorkspaceImageCacheKey({ uri }));
|
||||
}
|
||||
|
||||
export const workspaceFileImageAtom = createWorkspaceFileImageAtomFamily();
|
||||
@@ -1,31 +0,0 @@
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceFilePath } from "./filePath";
|
||||
|
||||
export function useWorkspaceFileAssetUrl(props: {
|
||||
readonly cwd: string | null;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly relativePath: string | null;
|
||||
readonly threadId: ThreadId | null;
|
||||
}) {
|
||||
const absolutePath = useMemo(
|
||||
() =>
|
||||
props.cwd !== null && props.relativePath !== null
|
||||
? resolveWorkspaceFilePath(props.cwd, props.relativePath)
|
||||
: null,
|
||||
[props.cwd, props.relativePath],
|
||||
);
|
||||
|
||||
return useAssetUrl(
|
||||
props.environmentId,
|
||||
absolutePath !== null && props.threadId !== null
|
||||
? {
|
||||
_tag: "workspace-file",
|
||||
threadId: props.threadId,
|
||||
path: absolutePath,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "@t3tools/contracts";
|
||||
import { Stack } from "expo-router";
|
||||
import { Text as RNText, View } from "react-native";
|
||||
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
|
||||
export interface HomeHeaderEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
}
|
||||
|
||||
const PROJECT_SORT_OPTIONS: ReadonlyArray<{
|
||||
readonly value: HomeProjectSortOrder;
|
||||
readonly label: string;
|
||||
}> = [
|
||||
{ value: "updated_at", label: "Last user message" },
|
||||
{ value: "created_at", label: "Created at" },
|
||||
];
|
||||
|
||||
const THREAD_SORT_OPTIONS: ReadonlyArray<{
|
||||
readonly value: SidebarThreadSortOrder;
|
||||
readonly label: string;
|
||||
}> = [
|
||||
{ value: "updated_at", label: "Last user message" },
|
||||
{ value: "created_at", label: "Created at" },
|
||||
];
|
||||
|
||||
const PROJECT_GROUPING_OPTIONS: ReadonlyArray<{
|
||||
readonly value: SidebarProjectGroupingMode;
|
||||
readonly label: string;
|
||||
readonly subtitle: string;
|
||||
}> = [
|
||||
{
|
||||
value: "repository",
|
||||
label: "Group by repository",
|
||||
subtitle: "Combine matching repositories across environments",
|
||||
},
|
||||
{
|
||||
value: "repository_path",
|
||||
label: "Group by repository path",
|
||||
subtitle: "Combine only matching paths within a repository",
|
||||
},
|
||||
{
|
||||
value: "separate",
|
||||
label: "Keep separate",
|
||||
subtitle: "Show every project path separately",
|
||||
},
|
||||
];
|
||||
|
||||
export function HomeHeader(props: {
|
||||
readonly environments: ReadonlyArray<HomeHeaderEnvironment>;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onSearchQueryChange: (query: string) => void;
|
||||
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
readonly onStartNewTask: () => void;
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
const hasCustomListOptions =
|
||||
props.selectedEnvironmentId !== null ||
|
||||
props.projectSortOrder !== DEFAULT_SIDEBAR_PROJECT_SORT_ORDER ||
|
||||
props.threadSortOrder !== DEFAULT_SIDEBAR_THREAD_SORT_ORDER ||
|
||||
props.projectGroupingMode !== DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerShown: true,
|
||||
headerTransparent: true,
|
||||
headerStyle: { backgroundColor: "transparent" },
|
||||
headerShadowVisible: false,
|
||||
headerTintColor: iconColor,
|
||||
headerTitle: "",
|
||||
headerSearchBarOptions: {
|
||||
placeholder: "Search threads",
|
||||
hideNavigationBar: false,
|
||||
onChangeText: (event) => {
|
||||
props.onSearchQueryChange(event.nativeEvent.text);
|
||||
},
|
||||
onCancelButtonPress: () => {
|
||||
props.onSearchQueryChange("");
|
||||
},
|
||||
allowToolbarIntegration: true,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack.Toolbar placement="left">
|
||||
<Stack.Toolbar.View hidesSharedBackground>
|
||||
<View
|
||||
style={{
|
||||
width: 128,
|
||||
height: 32,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<RNText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 17,
|
||||
color: iconColor,
|
||||
letterSpacing: -0.4,
|
||||
}}
|
||||
>
|
||||
T3 Code
|
||||
</RNText>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: subtleColor,
|
||||
borderRadius: 99,
|
||||
paddingHorizontal: 8,
|
||||
paddingVertical: 3,
|
||||
}}
|
||||
>
|
||||
<RNText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 10,
|
||||
color: mutedColor,
|
||||
letterSpacing: 1.1,
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
Alpha
|
||||
</RNText>
|
||||
</View>
|
||||
</View>
|
||||
</Stack.Toolbar.View>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu
|
||||
accessibilityLabel="Filter and sort threads"
|
||||
icon={
|
||||
hasCustomListOptions
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle"
|
||||
}
|
||||
separateBackground
|
||||
title="Thread list options"
|
||||
>
|
||||
<Stack.Toolbar.Menu title="Environment">
|
||||
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
isOn={props.selectedEnvironmentId === null}
|
||||
onPress={() => props.onEnvironmentChange(null)}
|
||||
subtitle="Show threads from every environment"
|
||||
>
|
||||
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
{props.environments.map((environment) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={environment.environmentId}
|
||||
isOn={props.selectedEnvironmentId === environment.environmentId}
|
||||
onPress={() => props.onEnvironmentChange(environment.environmentId)}
|
||||
>
|
||||
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Menu title="Sort projects">
|
||||
<Stack.Toolbar.Label>Sort projects</Stack.Toolbar.Label>
|
||||
{PROJECT_SORT_OPTIONS.map((option) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.projectSortOrder === option.value}
|
||||
onPress={() => props.onProjectSortOrderChange(option.value)}
|
||||
>
|
||||
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Menu title="Sort threads">
|
||||
<Stack.Toolbar.Label>Sort threads</Stack.Toolbar.Label>
|
||||
{THREAD_SORT_OPTIONS.map((option) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.threadSortOrder === option.value}
|
||||
onPress={() => props.onThreadSortOrderChange(option.value)}
|
||||
>
|
||||
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Menu title="Group projects">
|
||||
<Stack.Toolbar.Label>Group projects</Stack.Toolbar.Label>
|
||||
{PROJECT_GROUPING_OPTIONS.map((option) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.projectGroupingMode === option.value}
|
||||
onPress={() => props.onProjectGroupingModeChange(option.value)}
|
||||
subtitle={option.subtitle}
|
||||
>
|
||||
<Stack.Toolbar.Label>{option.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Button
|
||||
accessibilityLabel="Open settings"
|
||||
icon="gearshape"
|
||||
onPress={props.onOpenSettings}
|
||||
separateBackground
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<Stack.Toolbar placement="bottom">
|
||||
<Stack.Toolbar.SearchBarSlot />
|
||||
<Stack.Toolbar.Spacer width={8} sharesBackground={false} />
|
||||
<Stack.Toolbar.Button
|
||||
accessibilityLabel="New task"
|
||||
icon="square.and.pencil"
|
||||
onPress={props.onStartNewTask}
|
||||
separateBackground
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -2,26 +2,12 @@ import {
|
||||
type EnvironmentProject,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, Pressable, ScrollView, useWindowDimensions, View } from "react-native";
|
||||
import ReanimatedSwipeable, {
|
||||
type SwipeableMethods,
|
||||
} from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import Animated, {
|
||||
Easing,
|
||||
LinearTransition,
|
||||
type ExitAnimationsValues,
|
||||
withDelay,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -29,14 +15,9 @@ import { EmptyState } from "../../components/EmptyState";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import { threadStatusTone } from "../threads/threadPresentation";
|
||||
import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
|
||||
import {
|
||||
THREAD_SWIPE_ACTIONS_WIDTH,
|
||||
THREAD_SWIPE_SPRING,
|
||||
ThreadSwipeActions,
|
||||
} from "./thread-swipe-actions";
|
||||
|
||||
/* ─── Types ──────────────────────────────────────────────────────────── */
|
||||
|
||||
@@ -46,17 +27,26 @@ interface HomeScreenProps {
|
||||
readonly catalogState: WorkspaceState;
|
||||
readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
|
||||
readonly searchQuery: string;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
readonly onAddConnection: () => void;
|
||||
readonly onOpenEnvironments: () => void;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
}
|
||||
|
||||
interface ProjectGroup {
|
||||
readonly key: string;
|
||||
readonly project: EnvironmentProject;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
}
|
||||
|
||||
const projectGroupActivityOrder = Order.mapInput(
|
||||
Order.Struct({
|
||||
activityAt: Order.flip(Order.Number),
|
||||
}),
|
||||
(group: ProjectGroup) => ({
|
||||
activityAt: new Date(group.threads[0]!.updatedAt ?? group.threads[0]!.createdAt).getTime(),
|
||||
}),
|
||||
);
|
||||
|
||||
/* ─── Status indicator colors ────────────────────────────────────────── */
|
||||
|
||||
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
|
||||
@@ -75,33 +65,6 @@ function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string
|
||||
}
|
||||
|
||||
const COLLAPSED_THREAD_LIMIT = 6;
|
||||
const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic));
|
||||
|
||||
function threadRowExit(values: ExitAnimationsValues) {
|
||||
"worklet";
|
||||
|
||||
return {
|
||||
initialValues: {
|
||||
height: values.currentHeight,
|
||||
opacity: 1,
|
||||
originX: values.currentOriginX,
|
||||
},
|
||||
animations: {
|
||||
height: withDelay(
|
||||
90,
|
||||
withTiming(0, {
|
||||
duration: 170,
|
||||
easing: Easing.inOut(Easing.cubic),
|
||||
}),
|
||||
),
|
||||
opacity: withDelay(80, withTiming(0, { duration: 100 })),
|
||||
originX: withTiming(values.currentOriginX - values.windowWidth, {
|
||||
duration: 190,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function deriveEmptyState(props: {
|
||||
readonly catalogState: WorkspaceState;
|
||||
@@ -170,7 +133,6 @@ function deriveEmptyState(props: {
|
||||
|
||||
function ProjectGroupLabel(props: {
|
||||
readonly project: EnvironmentProject;
|
||||
readonly title: string;
|
||||
readonly totalThreadCount: number;
|
||||
readonly isExpanded: boolean;
|
||||
readonly onToggleExpand: () => void;
|
||||
@@ -190,7 +152,7 @@ function ProjectGroupLabel(props: {
|
||||
style={{ letterSpacing: 0.5 }}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.title}
|
||||
{props.project.title}
|
||||
</Text>
|
||||
|
||||
{hiddenCount > 0 ? (
|
||||
@@ -213,172 +175,95 @@ function ThreadRow(props: {
|
||||
readonly thread: EnvironmentThreadShell;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly onPress: () => void;
|
||||
readonly onArchive: () => void;
|
||||
readonly onDelete: () => void;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
readonly isLast: boolean;
|
||||
}) {
|
||||
const swipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const fullSwipeArmedRef = useRef(false);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const separatorColor = useThemeColor("--color-separator");
|
||||
const iconSubtleColor = useThemeColor("--color-icon-subtle");
|
||||
const cardColor = useThemeColor("--color-card");
|
||||
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
|
||||
const { bg, fg } = statusColors(props.thread);
|
||||
const tone = threadStatusTone(props.thread);
|
||||
const timestamp = relativeTime(
|
||||
props.thread.latestUserMessageAt ?? props.thread.updatedAt ?? props.thread.createdAt,
|
||||
);
|
||||
const timestamp = relativeTime(props.thread.updatedAt ?? props.thread.createdAt);
|
||||
const branch = props.thread.branch;
|
||||
const subtitleParts = [props.environmentLabel, branch].filter((part): part is string =>
|
||||
Boolean(part),
|
||||
);
|
||||
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
|
||||
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
|
||||
}
|
||||
fullSwipeArmedRef.current = armed;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ReanimatedSwipeable
|
||||
ref={swipeableRef}
|
||||
animationOptions={THREAD_SWIPE_SPRING}
|
||||
childrenContainerStyle={{ backgroundColor: cardColor }}
|
||||
containerStyle={{ backgroundColor: cardColor }}
|
||||
dragOffsetFromRightEdge={8}
|
||||
enableTrackpadTwoFingerGesture
|
||||
friction={1}
|
||||
onSwipeableClose={() => {
|
||||
fullSwipeArmedRef.current = false;
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableClose(swipeableRef.current);
|
||||
}
|
||||
}}
|
||||
onSwipeableOpenStartDrag={() => {
|
||||
if (swipeableRef.current) {
|
||||
props.onSwipeableWillOpen(swipeableRef.current);
|
||||
}
|
||||
}}
|
||||
onSwipeableWillOpen={() => {
|
||||
const methods = swipeableRef.current;
|
||||
if (!methods) {
|
||||
return;
|
||||
}
|
||||
|
||||
props.onSwipeableWillOpen(methods);
|
||||
if (fullSwipeArmedRef.current) {
|
||||
fullSwipeArmedRef.current = false;
|
||||
methods.close();
|
||||
props.onDelete();
|
||||
}
|
||||
}}
|
||||
overshootFriction={1}
|
||||
overshootRight
|
||||
renderRightActions={(_progress, translation, methods) => (
|
||||
<ThreadSwipeActions
|
||||
backgroundColor={cardColor}
|
||||
fullSwipeThreshold={fullSwipeThreshold}
|
||||
onDelete={props.onDelete}
|
||||
onFullSwipeArmedChange={handleFullSwipeArmedChange}
|
||||
primaryAction={{
|
||||
accessibilityLabel: `Archive ${props.thread.title}`,
|
||||
icon: "archivebox",
|
||||
label: "Archive",
|
||||
onPress: props.onArchive,
|
||||
}}
|
||||
swipeableMethods={methods}
|
||||
threadTitle={props.thread.title}
|
||||
translation={translation}
|
||||
/>
|
||||
)}
|
||||
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityHint="Swipe left for archive and delete actions"
|
||||
accessibilityLabel={props.thread.title}
|
||||
accessibilityRole="button"
|
||||
className="bg-card"
|
||||
onPress={() => {
|
||||
swipeableRef.current?.close();
|
||||
props.onPress();
|
||||
<Pressable onPress={props.onPress} style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}>
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
paddingLeft: 16,
|
||||
paddingRight: 16,
|
||||
paddingVertical: 10,
|
||||
gap: 12,
|
||||
borderBottomWidth: props.isLast ? 0 : 1,
|
||||
borderBottomColor: separatorColor,
|
||||
}}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
|
||||
>
|
||||
{/* Git status indicator */}
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
paddingLeft: 16,
|
||||
paddingRight: 16,
|
||||
paddingVertical: 10,
|
||||
gap: 12,
|
||||
borderBottomWidth: props.isLast ? 0 : 1,
|
||||
borderBottomColor: separatorColor,
|
||||
width: 30,
|
||||
height: 30,
|
||||
borderRadius: 9,
|
||||
backgroundColor: bg,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
marginTop: 2,
|
||||
}}
|
||||
>
|
||||
<View
|
||||
style={{
|
||||
width: 30,
|
||||
height: 30,
|
||||
borderRadius: 9,
|
||||
backgroundColor: bg,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
marginTop: 2,
|
||||
}}
|
||||
>
|
||||
<SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
|
||||
</View>
|
||||
|
||||
<View style={{ flex: 1, gap: 3 }}>
|
||||
<View className="flex-row items-center justify-between gap-2">
|
||||
<Text
|
||||
className="flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View
|
||||
className={tone.pillClassName}
|
||||
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
|
||||
>
|
||||
<Text className={`text-[10px] font-t3-bold ${tone.textClassName}`}>
|
||||
{tone.label}
|
||||
</Text>
|
||||
</View>
|
||||
<Text
|
||||
className="text-[12px] text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"] }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{subtitleParts.length > 0 ? (
|
||||
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={10}
|
||||
tintColor={iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text
|
||||
className="text-[11px] text-foreground-tertiary"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: "monospace" }}
|
||||
>
|
||||
{subtitleParts.join(" · ")}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
<SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
|
||||
</View>
|
||||
</Pressable>
|
||||
</ReanimatedSwipeable>
|
||||
|
||||
{/* Content */}
|
||||
<View style={{ flex: 1, gap: 3 }}>
|
||||
{/* Title + Status + Timestamp */}
|
||||
<View className="flex-row items-center justify-between gap-2">
|
||||
<Text
|
||||
className="flex-1 text-[15px] font-t3-bold leading-[20px] text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.thread.title}
|
||||
</Text>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View
|
||||
className={tone.pillClassName}
|
||||
style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
|
||||
>
|
||||
<Text className={`text-[10px] font-t3-bold ${tone.textClassName}`}>
|
||||
{tone.label}
|
||||
</Text>
|
||||
</View>
|
||||
<Text
|
||||
className="text-[12px] text-foreground-tertiary"
|
||||
style={{ fontVariant: ["tabular-nums"] }}
|
||||
>
|
||||
{timestamp}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* Environment + branch */}
|
||||
{subtitleParts.length > 0 ? (
|
||||
<View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={10}
|
||||
tintColor={iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text
|
||||
className="text-[11px] text-foreground-tertiary"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: "monospace" }}
|
||||
>
|
||||
{subtitleParts.join(" · ")}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -438,7 +323,6 @@ function StaleCatalogStatusPill(props: {
|
||||
|
||||
export function HomeScreen(props: HomeScreenProps) {
|
||||
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const insets = useSafeAreaInsets();
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
|
||||
@@ -451,50 +335,51 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
|
||||
if (openSwipeableRef.current !== methods) {
|
||||
openSwipeableRef.current?.close();
|
||||
openSwipeableRef.current = methods;
|
||||
/* Build project title lookup for search */
|
||||
const projectTitleByKey = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
for (const p of props.projects) {
|
||||
map.set(scopedProjectKey(p.environmentId, p.id), p.title);
|
||||
}
|
||||
}, []);
|
||||
return map;
|
||||
}, [props.projects]);
|
||||
|
||||
const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
|
||||
if (openSwipeableRef.current === methods) {
|
||||
openSwipeableRef.current = null;
|
||||
/* Filter threads by search query */
|
||||
const filteredThreads = useMemo(() => {
|
||||
const q = props.searchQuery.trim().toLowerCase();
|
||||
if (!q) return props.threads;
|
||||
return props.threads.filter((t) => {
|
||||
if (t.title.toLowerCase().includes(q)) return true;
|
||||
const key = scopedProjectKey(t.environmentId, t.projectId);
|
||||
return projectTitleByKey.get(key)?.toLowerCase().includes(q) ?? false;
|
||||
});
|
||||
}, [props.threads, props.searchQuery, projectTitleByKey]);
|
||||
|
||||
/* Group filtered threads by project */
|
||||
const projectGroups = useMemo<ReadonlyArray<ProjectGroup>>(() => {
|
||||
const byProject = new Map<string, EnvironmentThreadShell[]>();
|
||||
for (const thread of filteredThreads) {
|
||||
const key = scopedProjectKey(thread.environmentId, thread.projectId);
|
||||
const existing = byProject.get(key);
|
||||
if (existing) existing.push(thread);
|
||||
else byProject.set(key, [thread]);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const projectGroups = useMemo(
|
||||
() =>
|
||||
buildHomeThreadGroups({
|
||||
projects: props.projects,
|
||||
threads: props.threads,
|
||||
environmentId: props.selectedEnvironmentId,
|
||||
searchQuery: props.searchQuery,
|
||||
projectSortOrder: props.projectSortOrder,
|
||||
threadSortOrder: props.threadSortOrder,
|
||||
projectGroupingMode: props.projectGroupingMode,
|
||||
}),
|
||||
[
|
||||
props.projectGroupingMode,
|
||||
props.projects,
|
||||
props.projectSortOrder,
|
||||
props.searchQuery,
|
||||
props.selectedEnvironmentId,
|
||||
props.threadSortOrder,
|
||||
props.threads,
|
||||
],
|
||||
);
|
||||
const groups: ProjectGroup[] = [];
|
||||
for (const project of props.projects) {
|
||||
const key = scopedProjectKey(project.environmentId, project.id);
|
||||
const threads = byProject.get(key);
|
||||
if (threads && threads.length > 0) {
|
||||
groups.push({ key, project, threads });
|
||||
}
|
||||
}
|
||||
|
||||
return Arr.sort(groups, projectGroupActivityOrder);
|
||||
}, [props.projects, filteredThreads]);
|
||||
|
||||
/* Empty states */
|
||||
const hasAnyThreads = props.threads.some((thread) => thread.archivedAt === null);
|
||||
const hasResults = projectGroups.length > 0;
|
||||
const selectedEnvironmentLabel =
|
||||
props.selectedEnvironmentId === null
|
||||
? null
|
||||
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
|
||||
"this environment");
|
||||
const hasSearchQuery = props.searchQuery.trim().length > 0;
|
||||
const hasAnyThreads = props.threads.length > 0;
|
||||
const hasResults = filteredThreads.length > 0;
|
||||
const shouldShowConnectionStatus =
|
||||
props.catalogState.networkStatus === "offline" ||
|
||||
props.catalogState.hasConnectingEnvironment ||
|
||||
@@ -511,7 +396,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
showsVerticalScrollIndicator={false}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
|
||||
className="flex-1"
|
||||
contentContainerStyle={{
|
||||
paddingHorizontal: 16,
|
||||
@@ -534,18 +418,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
) : !hasResults && hasSearchQuery ? (
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : !hasResults && selectedEnvironmentLabel ? (
|
||||
<EmptyState
|
||||
title={`No threads in ${selectedEnvironmentLabel}`}
|
||||
detail="Choose another environment or create a new task."
|
||||
/>
|
||||
) : !hasResults ? (
|
||||
<EmptyState
|
||||
title="No threads yet"
|
||||
detail="Create a task to start a new coding session."
|
||||
/>
|
||||
<EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
|
||||
) : (
|
||||
projectGroups.map((group) => {
|
||||
const isExpanded = expandedProjects.has(group.key);
|
||||
@@ -554,52 +428,30 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
key={group.key}
|
||||
collapsable={false}
|
||||
exiting={threadRowExit}
|
||||
layout={THREAD_LAYOUT_TRANSITION}
|
||||
style={{ overflow: "hidden" }}
|
||||
>
|
||||
<View key={group.key}>
|
||||
<ProjectGroupLabel
|
||||
project={group.project}
|
||||
totalThreadCount={group.threads.length}
|
||||
isExpanded={isExpanded}
|
||||
onToggleExpand={() => toggleExpanded(group.key)}
|
||||
project={group.representative}
|
||||
title={group.title}
|
||||
totalThreadCount={group.threads.length}
|
||||
/>
|
||||
<View
|
||||
className="overflow-hidden rounded-[20px] bg-card"
|
||||
style={{ borderCurve: "continuous" }}
|
||||
>
|
||||
{visibleThreads.map((thread, i) => {
|
||||
const threadKey = `${thread.environmentId}:${thread.id}`;
|
||||
return (
|
||||
<Animated.View
|
||||
key={threadKey}
|
||||
collapsable={false}
|
||||
exiting={threadRowExit}
|
||||
layout={THREAD_LAYOUT_TRANSITION}
|
||||
style={{ overflow: "hidden" }}
|
||||
>
|
||||
<ThreadRow
|
||||
thread={thread}
|
||||
environmentLabel={
|
||||
props.savedConnectionsById[thread.environmentId]?.environmentLabel ??
|
||||
null
|
||||
}
|
||||
isLast={i === visibleThreads.length - 1}
|
||||
onArchive={() => props.onArchiveThread(thread)}
|
||||
onDelete={() => props.onDeleteThread(thread)}
|
||||
onPress={() => props.onSelectThread(thread)}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
onSwipeableWillOpen={handleSwipeableWillOpen}
|
||||
/>
|
||||
</Animated.View>
|
||||
);
|
||||
})}
|
||||
{visibleThreads.map((thread, i) => (
|
||||
<ThreadRow
|
||||
key={`${thread.environmentId}:${thread.id}`}
|
||||
thread={thread}
|
||||
environmentLabel={
|
||||
props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
|
||||
}
|
||||
onPress={() => props.onSelectThread(thread)}
|
||||
isLast={i === visibleThreads.length - 1}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</Animated.View>
|
||||
</View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
|
||||
@@ -1,223 +0,0 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildHomeThreadGroups } from "./homeThreadList";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
): EnvironmentProject {
|
||||
return {
|
||||
workspaceRoot: `/workspaces/${input.id}`,
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function buildGroups(
|
||||
projects: ReadonlyArray<EnvironmentProject>,
|
||||
threads: ReadonlyArray<EnvironmentThreadShell>,
|
||||
overrides: Partial<Parameters<typeof buildHomeThreadGroups>[0]> = {},
|
||||
) {
|
||||
return buildHomeThreadGroups({
|
||||
projects,
|
||||
threads,
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
projectSortOrder: "updated_at",
|
||||
threadSortOrder: "updated_at",
|
||||
projectGroupingMode: "repository",
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
describe("buildHomeThreadGroups", () => {
|
||||
it("sorts the newest thread first regardless of snapshot order", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const project = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "T3 Code",
|
||||
});
|
||||
const threads = [
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("thread-old"),
|
||||
projectId: project.id,
|
||||
title: "Older thread",
|
||||
updatedAt: "2026-06-02T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("thread-new"),
|
||||
projectId: project.id,
|
||||
title: "Newer thread",
|
||||
updatedAt: "2026-06-03T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
expect(buildGroups([project], threads)[0]?.threads.map((thread) => thread.id)).toEqual([
|
||||
"thread-new",
|
||||
"thread-old",
|
||||
]);
|
||||
});
|
||||
|
||||
it("supports independent project and thread creation-time sorting", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const olderProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-older"),
|
||||
title: "Older project",
|
||||
});
|
||||
const newerProject = makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-newer"),
|
||||
title: "Newer project",
|
||||
});
|
||||
const threads = [
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("old-created"),
|
||||
projectId: olderProject.id,
|
||||
title: "Updated recently",
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-05T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("new-created"),
|
||||
projectId: olderProject.id,
|
||||
title: "Created recently",
|
||||
createdAt: "2026-06-04T00:00:00.000Z",
|
||||
updatedAt: "2026-06-04T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make("newest-project-thread"),
|
||||
projectId: newerProject.id,
|
||||
title: "Newest project",
|
||||
createdAt: "2026-06-06T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
const groups = buildGroups([olderProject, newerProject], threads, {
|
||||
projectSortOrder: "created_at",
|
||||
threadSortOrder: "created_at",
|
||||
projectGroupingMode: "separate",
|
||||
});
|
||||
|
||||
expect(groups.map((group) => group.representative.id)).toEqual([
|
||||
"project-newer",
|
||||
"project-older",
|
||||
]);
|
||||
expect(groups[1]?.threads.map((thread) => thread.id)).toEqual(["new-created", "old-created"]);
|
||||
});
|
||||
|
||||
it("filters both projects and threads to one environment", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: localEnvironmentId,
|
||||
id: ProjectId.make("project-local"),
|
||||
title: "Local",
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ProjectId.make("project-remote"),
|
||||
title: "Remote",
|
||||
}),
|
||||
];
|
||||
const threads = projects.map((project) =>
|
||||
makeThread({
|
||||
environmentId: project.environmentId,
|
||||
id: ThreadId.make(`thread-${project.id}`),
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
}),
|
||||
);
|
||||
|
||||
const groups = buildGroups(projects, threads, { environmentId: remoteEnvironmentId });
|
||||
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.representative.environmentId).toBe(remoteEnvironmentId);
|
||||
expect(groups[0]?.threads.map((thread) => thread.environmentId)).toEqual([remoteEnvironmentId]);
|
||||
});
|
||||
|
||||
it("matches web repository, repository-path, and separate grouping modes", () => {
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const repositoryIdentity = {
|
||||
canonicalKey: "github.com/t3tools/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:t3tools/t3code.git",
|
||||
},
|
||||
provider: "github",
|
||||
owner: "t3tools",
|
||||
name: "t3code",
|
||||
displayName: "T3 Code",
|
||||
rootPath: "/workspaces/t3code",
|
||||
};
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-web"),
|
||||
title: "Web",
|
||||
workspaceRoot: "/workspaces/t3code/apps/web",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
makeProject({
|
||||
environmentId,
|
||||
id: ProjectId.make("project-mobile"),
|
||||
title: "Mobile",
|
||||
workspaceRoot: "/workspaces/t3code/apps/mobile",
|
||||
repositoryIdentity,
|
||||
}),
|
||||
];
|
||||
const threads = projects.map((project) =>
|
||||
makeThread({
|
||||
environmentId,
|
||||
id: ThreadId.make(`thread-${project.id}`),
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(buildGroups(projects, threads, { projectGroupingMode: "repository" })).toHaveLength(1);
|
||||
expect(buildGroups(projects, threads, { projectGroupingMode: "repository_path" })).toHaveLength(
|
||||
2,
|
||||
);
|
||||
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -1,140 +0,0 @@
|
||||
import {
|
||||
deriveLogicalProjectKey,
|
||||
deriveProjectGroupLabel,
|
||||
} from "@t3tools/client-runtime/state/project-grouping";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { getThreadSortTimestamp, sortThreads } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
SidebarProjectSortOrder,
|
||||
SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
|
||||
export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
|
||||
|
||||
export interface HomeThreadGroup {
|
||||
readonly key: string;
|
||||
readonly title: string;
|
||||
readonly representative: EnvironmentProject;
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
}
|
||||
|
||||
interface MutableHomeThreadGroup {
|
||||
readonly key: string;
|
||||
readonly projects: EnvironmentProject[];
|
||||
readonly threads: EnvironmentThreadShell[];
|
||||
}
|
||||
|
||||
function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOrder): number {
|
||||
return group.threads.reduce(
|
||||
(latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
}
|
||||
|
||||
export function buildHomeThreadGroups(input: {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly searchQuery: string;
|
||||
readonly projectSortOrder: HomeProjectSortOrder;
|
||||
readonly threadSortOrder: SidebarThreadSortOrder;
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}): ReadonlyArray<HomeThreadGroup> {
|
||||
const groups = new Map<string, MutableHomeThreadGroup>();
|
||||
const groupKeyByProjectKey = new Map<string, string>();
|
||||
|
||||
for (const project of input.projects) {
|
||||
if (input.environmentId !== null && project.environmentId !== input.environmentId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const groupKey = deriveLogicalProjectKey(project, {
|
||||
groupingMode: input.projectGroupingMode,
|
||||
});
|
||||
const physicalKey = scopedProjectKey(project.environmentId, project.id);
|
||||
groupKeyByProjectKey.set(physicalKey, groupKey);
|
||||
|
||||
const existing = groups.get(groupKey);
|
||||
if (existing) {
|
||||
existing.projects.push(project);
|
||||
} else {
|
||||
groups.set(groupKey, { key: groupKey, projects: [project], threads: [] });
|
||||
}
|
||||
}
|
||||
|
||||
for (const thread of input.threads) {
|
||||
if (thread.archivedAt !== null) {
|
||||
continue;
|
||||
}
|
||||
if (input.environmentId !== null && thread.environmentId !== input.environmentId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const physicalKey = scopedProjectKey(thread.environmentId, thread.projectId);
|
||||
const groupKey = groupKeyByProjectKey.get(physicalKey);
|
||||
if (!groupKey) {
|
||||
continue;
|
||||
}
|
||||
groups.get(groupKey)?.threads.push(thread);
|
||||
}
|
||||
|
||||
const query = input.searchQuery.trim().toLocaleLowerCase();
|
||||
const result: HomeThreadGroup[] = [];
|
||||
|
||||
for (const group of groups.values()) {
|
||||
const representative = group.projects[0];
|
||||
if (!representative || group.threads.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const title =
|
||||
group.projects.length > 1
|
||||
? deriveProjectGroupLabel({ representative, members: group.projects })
|
||||
: representative.title;
|
||||
const groupMatches =
|
||||
query.length === 0 ||
|
||||
title.toLocaleLowerCase().includes(query) ||
|
||||
group.projects.some((project) => project.title.toLocaleLowerCase().includes(query));
|
||||
const matchingThreads = groupMatches
|
||||
? group.threads
|
||||
: group.threads.filter((thread) => thread.title.toLocaleLowerCase().includes(query));
|
||||
|
||||
if (matchingThreads.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
result.push({
|
||||
key: group.key,
|
||||
title,
|
||||
representative,
|
||||
projects: group.projects,
|
||||
threads: sortThreads(matchingThreads, input.threadSortOrder),
|
||||
});
|
||||
}
|
||||
|
||||
return Arr.sort(
|
||||
result,
|
||||
Order.mapInput(
|
||||
Order.Struct({
|
||||
timestamp: Order.flip(Order.Number),
|
||||
title: Order.String,
|
||||
key: Order.String,
|
||||
}),
|
||||
(group: HomeThreadGroup) => ({
|
||||
timestamp: groupSortTimestamp(group, input.projectSortOrder),
|
||||
title: group.title,
|
||||
key: group.key,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import type { ComponentProps } from "react";
|
||||
import type { ColorValue } from "react-native";
|
||||
import { Pressable, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import Animated, {
|
||||
Extrapolation,
|
||||
interpolate,
|
||||
runOnJS,
|
||||
type SharedValue,
|
||||
useAnimatedReaction,
|
||||
useAnimatedStyle,
|
||||
} from "react-native-reanimated";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
|
||||
const ACTION_ITEM_WIDTH = 50;
|
||||
const ACTION_CIRCLE_SIZE = 36;
|
||||
const ACTION_ICON_SIZE = 15;
|
||||
|
||||
export const THREAD_SWIPE_ACTIONS_WIDTH = ACTION_ITEM_WIDTH * 2;
|
||||
export const THREAD_SWIPE_SPRING = {
|
||||
damping: 26,
|
||||
mass: 0.7,
|
||||
overshootClamping: true,
|
||||
stiffness: 330,
|
||||
};
|
||||
|
||||
function SwipeActionButton(props: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly backgroundColor: string;
|
||||
readonly entryRange: readonly [number, number];
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly label: string;
|
||||
readonly onPress: () => void;
|
||||
readonly stretchesOnFullSwipe: boolean;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
const actionStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const entryProgress = interpolate(reveal, props.entryRange, [0, 1], Extrapolation.CLAMP);
|
||||
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
|
||||
const fullSwipeProgress = interpolate(
|
||||
reveal,
|
||||
[THREAD_SWIPE_ACTIONS_WIDTH, props.fullSwipeThreshold + 20],
|
||||
[0, 1],
|
||||
Extrapolation.CLAMP,
|
||||
);
|
||||
|
||||
return {
|
||||
opacity: props.stretchesOnFullSwipe ? entryProgress : entryProgress * (1 - fullSwipeProgress),
|
||||
transform: [
|
||||
{
|
||||
translateX:
|
||||
interpolate(entryProgress, [0, 1], [22, 0]) -
|
||||
(props.stretchesOnFullSwipe ? 0 : stretch),
|
||||
},
|
||||
{ scale: interpolate(entryProgress, [0, 1], [0.78, 1]) },
|
||||
],
|
||||
};
|
||||
});
|
||||
const circleStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const stretch = props.stretchesOnFullSwipe
|
||||
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
|
||||
: 0;
|
||||
|
||||
return {
|
||||
transform: [{ translateX: -stretch }],
|
||||
width: ACTION_CIRCLE_SIZE + stretch,
|
||||
};
|
||||
});
|
||||
const iconStyle = useAnimatedStyle(() => {
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const stretch = props.stretchesOnFullSwipe
|
||||
? Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0)
|
||||
: 0;
|
||||
const armedProgress = interpolate(
|
||||
reveal,
|
||||
[props.fullSwipeThreshold, props.fullSwipeThreshold + 20],
|
||||
[0, 1],
|
||||
Extrapolation.CLAMP,
|
||||
);
|
||||
|
||||
return {
|
||||
transform: [{ translateX: -stretch * (0.5 + armedProgress * 0.5) }],
|
||||
};
|
||||
});
|
||||
const labelStyle = useAnimatedStyle(() => {
|
||||
if (!props.stretchesOnFullSwipe) {
|
||||
return { opacity: 1 };
|
||||
}
|
||||
|
||||
const reveal = Math.max(-props.translation.value, 0);
|
||||
const stretch = Math.max(reveal - THREAD_SWIPE_ACTIONS_WIDTH, 0);
|
||||
return {
|
||||
opacity: interpolate(
|
||||
reveal,
|
||||
[props.fullSwipeThreshold - 24, props.fullSwipeThreshold],
|
||||
[1, 0],
|
||||
Extrapolation.CLAMP,
|
||||
),
|
||||
transform: [{ translateX: -stretch * 0.5 }],
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
alignItems: "center",
|
||||
height: "100%",
|
||||
justifyContent: "center",
|
||||
width: ACTION_ITEM_WIDTH,
|
||||
zIndex: props.stretchesOnFullSwipe ? 2 : 1,
|
||||
},
|
||||
actionStyle,
|
||||
]}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel}
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
style={({ pressed }) => ({
|
||||
alignItems: "center",
|
||||
height: "100%",
|
||||
justifyContent: "center",
|
||||
opacity: pressed ? 0.72 : 1,
|
||||
width: "100%",
|
||||
})}
|
||||
>
|
||||
<View style={{ height: ACTION_CIRCLE_SIZE, width: ACTION_CIRCLE_SIZE }}>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
backgroundColor: props.backgroundColor,
|
||||
borderRadius: 999,
|
||||
height: ACTION_CIRCLE_SIZE,
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
},
|
||||
circleStyle,
|
||||
]}
|
||||
/>
|
||||
<Animated.View
|
||||
style={[
|
||||
{
|
||||
alignItems: "center",
|
||||
height: ACTION_CIRCLE_SIZE,
|
||||
justifyContent: "center",
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
width: ACTION_CIRCLE_SIZE,
|
||||
},
|
||||
iconStyle,
|
||||
]}
|
||||
>
|
||||
<SymbolView
|
||||
name={props.icon}
|
||||
size={ACTION_ICON_SIZE}
|
||||
tintColor="#ffffff"
|
||||
type="monochrome"
|
||||
/>
|
||||
</Animated.View>
|
||||
</View>
|
||||
<Animated.View style={[{ paddingTop: 2 }, labelStyle]}>
|
||||
<Text className="text-[10px] font-t3-medium text-foreground-muted">{props.label}</Text>
|
||||
</Animated.View>
|
||||
</Pressable>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ThreadSwipeActions(props: {
|
||||
readonly backgroundColor: ColorValue;
|
||||
readonly fullSwipeThreshold: number;
|
||||
readonly onDelete: () => void;
|
||||
readonly onFullSwipeArmedChange: (armed: boolean) => void;
|
||||
readonly primaryAction: {
|
||||
readonly accessibilityLabel: string;
|
||||
readonly icon: ComponentProps<typeof SymbolView>["name"];
|
||||
readonly label: string;
|
||||
readonly onPress: () => void;
|
||||
};
|
||||
readonly swipeableMethods: SwipeableMethods;
|
||||
readonly threadTitle: string;
|
||||
readonly translation: SharedValue<number>;
|
||||
}) {
|
||||
useAnimatedReaction(
|
||||
() => -props.translation.value >= props.fullSwipeThreshold,
|
||||
(armed, previous) => {
|
||||
if (armed !== previous) {
|
||||
runOnJS(props.onFullSwipeArmedChange)(armed);
|
||||
}
|
||||
},
|
||||
[props.fullSwipeThreshold, props.onFullSwipeArmedChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: props.backgroundColor,
|
||||
flexDirection: "row",
|
||||
height: "100%",
|
||||
width: THREAD_SWIPE_ACTIONS_WIDTH,
|
||||
}}
|
||||
>
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={props.primaryAction.accessibilityLabel}
|
||||
backgroundColor="#007aff"
|
||||
entryRange={[ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon={props.primaryAction.icon}
|
||||
label={props.primaryAction.label}
|
||||
onPress={props.primaryAction.onPress}
|
||||
stretchesOnFullSwipe={false}
|
||||
translation={props.translation}
|
||||
/>
|
||||
<SwipeActionButton
|
||||
accessibilityLabel={`Delete ${props.threadTitle}`}
|
||||
backgroundColor="#ff2d55"
|
||||
entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
|
||||
fullSwipeThreshold={props.fullSwipeThreshold}
|
||||
icon="trash"
|
||||
label="Delete"
|
||||
onPress={() => {
|
||||
props.swipeableMethods.close();
|
||||
props.onDelete();
|
||||
}}
|
||||
stretchesOnFullSwipe
|
||||
translation={props.translation}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { Alert } from "react-native";
|
||||
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete";
|
||||
|
||||
function actionFailureMessage(action: ThreadListAction, cause: Cause.Cause<unknown>): string {
|
||||
const error = Cause.squash(cause);
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
const verb =
|
||||
action === "archive" ? "archived" : action === "unarchive" ? "unarchived" : "deleted";
|
||||
return `The thread could not be ${verb}.`;
|
||||
}
|
||||
|
||||
function selectionHaptic(): void {
|
||||
if (process.env.EXPO_OS === "ios") {
|
||||
void Haptics.selectionAsync();
|
||||
}
|
||||
}
|
||||
|
||||
function actionFailureTitle(action: ThreadListAction): string {
|
||||
if (action === "archive") return "Could not archive thread";
|
||||
if (action === "unarchive") return "Could not unarchive thread";
|
||||
return "Could not delete thread";
|
||||
}
|
||||
|
||||
function useThreadActionExecutor(
|
||||
onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void,
|
||||
) {
|
||||
const archiveMutation = useAtomCommand(threadEnvironment.archive, { reportFailure: false });
|
||||
const unarchiveMutation = useAtomCommand(threadEnvironment.unarchive, { reportFailure: false });
|
||||
const deleteMutation = useAtomCommand(threadEnvironment.delete, { reportFailure: false });
|
||||
const inFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const executeAction = useCallback(
|
||||
async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
|
||||
const key = scopedThreadKey(thread.environmentId, thread.id);
|
||||
if (inFlightThreadKeys.current.has(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
inFlightThreadKeys.current.add(key);
|
||||
selectionHaptic();
|
||||
try {
|
||||
const mutation =
|
||||
action === "archive"
|
||||
? archiveMutation
|
||||
: action === "unarchive"
|
||||
? unarchiveMutation
|
||||
: deleteMutation;
|
||||
const result = await mutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
Alert.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
|
||||
return;
|
||||
}
|
||||
onCompleted?.(action, thread);
|
||||
} finally {
|
||||
inFlightThreadKeys.current.delete(key);
|
||||
}
|
||||
},
|
||||
[archiveMutation, deleteMutation, onCompleted, unarchiveMutation],
|
||||
);
|
||||
|
||||
return executeAction;
|
||||
}
|
||||
|
||||
function useConfirmDeleteThread(
|
||||
executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<void>,
|
||||
) {
|
||||
return useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
Alert.alert(
|
||||
"Delete thread?",
|
||||
`“${thread.title}” will be permanently deleted, including its terminal history.`,
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{
|
||||
text: "Delete",
|
||||
style: "destructive",
|
||||
onPress: () => {
|
||||
void executeAction("delete", thread);
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
},
|
||||
[executeAction],
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadListActions(): {
|
||||
readonly archiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
|
||||
const archiveThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void executeAction("archive", thread);
|
||||
},
|
||||
[executeAction],
|
||||
);
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
return { archiveThread, confirmDeleteThread };
|
||||
}
|
||||
|
||||
export function useArchivedThreadListActions(
|
||||
onCompleted: (thread: EnvironmentThreadShell) => void,
|
||||
): {
|
||||
readonly unarchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
|
||||
} {
|
||||
const handleCompleted = useCallback(
|
||||
(_action: ThreadListAction, thread: EnvironmentThreadShell) => {
|
||||
onCompleted(thread);
|
||||
},
|
||||
[onCompleted],
|
||||
);
|
||||
const executeAction = useThreadActionExecutor(handleCompleted);
|
||||
const unarchiveThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void executeAction("unarchive", thread);
|
||||
},
|
||||
[executeAction],
|
||||
);
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
return { unarchiveThread, confirmDeleteThread };
|
||||
}
|
||||
@@ -695,15 +695,6 @@ export async function highlightCodeSnippet(input: {
|
||||
return highlightLines(input.code, language, SHIKI_THEME_NAME_BY_SCHEME[input.theme]);
|
||||
}
|
||||
|
||||
export async function highlightSourceFile(input: {
|
||||
readonly path: string;
|
||||
readonly contents: string;
|
||||
readonly theme: ReviewDiffTheme;
|
||||
}): Promise<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {
|
||||
const language = await resolveLanguageFromPath(input.path);
|
||||
return highlightLines(input.contents, language, SHIKI_THEME_NAME_BY_SCHEME[input.theme]);
|
||||
}
|
||||
|
||||
async function highlightPatchLinesInChunks(input: {
|
||||
readonly lines: ReadonlyArray<string>;
|
||||
readonly language: string;
|
||||
|
||||
@@ -62,7 +62,6 @@ export interface ThreadDetailScreenProps {
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
readonly threadCwd: string | null;
|
||||
readonly selectedThreadQueueCount: number;
|
||||
readonly serverConfig: T3ServerConfig | null;
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
@@ -310,7 +309,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
key={props.selectedThread.id}
|
||||
environmentId={props.environmentId}
|
||||
threadId={props.selectedThread.id}
|
||||
workspaceRoot={props.threadCwd}
|
||||
feed={props.selectedThreadFeed}
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
|
||||
@@ -4,7 +4,6 @@ import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useRouter } from "expo-router";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import {
|
||||
Markdown,
|
||||
@@ -55,7 +54,6 @@ import {
|
||||
import { buildReviewParsedDiff } from "../review/reviewModel";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { LayoutVariant } from "../../lib/layout";
|
||||
import { buildThreadFilesNavigation } from "../../lib/routes";
|
||||
import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
|
||||
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
|
||||
import {
|
||||
@@ -66,9 +64,7 @@ import {
|
||||
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import { ThreadWorkLog } from "./thread-work-log";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
|
||||
const THREAD_FEED_END_THRESHOLD = 80;
|
||||
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
|
||||
@@ -87,7 +83,6 @@ function formatMessageTime(input: string): string {
|
||||
export interface ThreadFeedProps {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly workspaceRoot?: string | null;
|
||||
readonly feed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
@@ -125,6 +120,32 @@ function MessageAttachmentImage(props: {
|
||||
);
|
||||
}
|
||||
|
||||
function stripShellWrapper(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
|
||||
return (match?.[1] ?? trimmed).trim();
|
||||
}
|
||||
|
||||
function compactActivityDetail(detail: string | null): string | null {
|
||||
if (!detail) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
|
||||
return cleaned.length > 0 ? cleaned : null;
|
||||
}
|
||||
|
||||
function buildActivityRows(
|
||||
activities: Extract<ThreadFeedEntry, { type: "activity-group" }>["activities"],
|
||||
) {
|
||||
return activities.map((activity) => ({
|
||||
...activity,
|
||||
detail: compactActivityDetail(activity.detail),
|
||||
}));
|
||||
}
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
|
||||
const MARKDOWN_COLORS = {
|
||||
light: {
|
||||
body: "#111111",
|
||||
@@ -134,12 +155,10 @@ const MARKDOWN_COLORS = {
|
||||
blockquoteBackground: "rgba(0, 0, 0, 0.02)",
|
||||
codeBackground: "rgba(0, 0, 0, 0.04)",
|
||||
codeText: "#262626",
|
||||
inlineCodeText: "#5f6368",
|
||||
horizontalRule: "rgba(0, 0, 0, 0.08)",
|
||||
userBody: "#ffffff",
|
||||
userCodeBackground: "rgba(255, 255, 255, 0.22)",
|
||||
userCodeText: "#ffffff",
|
||||
userInlineCodeText: "rgba(255, 255, 255, 0.82)",
|
||||
userFenceBackground: "rgba(0, 0, 0, 0.16)",
|
||||
userFenceText: "#ffffff",
|
||||
},
|
||||
@@ -151,12 +170,10 @@ const MARKDOWN_COLORS = {
|
||||
blockquoteBackground: "rgba(255, 255, 255, 0.03)",
|
||||
codeBackground: "rgba(255, 255, 255, 0.06)",
|
||||
codeText: "#e5e5e5",
|
||||
inlineCodeText: "#b8bcc2",
|
||||
horizontalRule: "rgba(255, 255, 255, 0.08)",
|
||||
userBody: "#ffffff",
|
||||
userCodeBackground: "rgba(255, 255, 255, 0.18)",
|
||||
userCodeText: "#ffffff",
|
||||
userInlineCodeText: "rgba(255, 255, 255, 0.82)",
|
||||
userFenceBackground: "rgba(0, 0, 0, 0.28)",
|
||||
userFenceText: "#ffffff",
|
||||
},
|
||||
@@ -185,18 +202,27 @@ interface ReviewCommentColors {
|
||||
|
||||
const failedMarkdownFaviconHosts = new Set<string>();
|
||||
const markdownLinkStyles = StyleSheet.create({
|
||||
inlineIcon: {
|
||||
favicon: {
|
||||
width: 14,
|
||||
height: 14,
|
||||
borderRadius: 3,
|
||||
marginHorizontal: 3,
|
||||
transform: [{ translateY: 2 }],
|
||||
},
|
||||
favicon: {
|
||||
borderRadius: 3,
|
||||
},
|
||||
file: {
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontWeight: "700",
|
||||
borderRadius: 5,
|
||||
borderWidth: StyleSheet.hairlineWidth,
|
||||
fontFamily: "DMSans_500Medium",
|
||||
fontSize: 13,
|
||||
lineHeight: 20,
|
||||
paddingHorizontal: 6,
|
||||
paddingVertical: 2,
|
||||
},
|
||||
fileIcon: {
|
||||
width: 15,
|
||||
height: 15,
|
||||
marginRight: 4,
|
||||
transform: [{ translateY: 2 }],
|
||||
},
|
||||
});
|
||||
|
||||
@@ -224,7 +250,7 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
|
||||
source={{
|
||||
uri: `https://www.google.com/s2/favicons?domain=${encodeURIComponent(props.host)}&sz=32`,
|
||||
}}
|
||||
style={[markdownLinkStyles.inlineIcon, markdownLinkStyles.favicon]}
|
||||
style={markdownLinkStyles.favicon}
|
||||
onError={() => {
|
||||
failedMarkdownFaviconHosts.add(props.host);
|
||||
setFailed(true);
|
||||
@@ -261,9 +287,11 @@ function useReviewCommentColors(): ReviewCommentColors {
|
||||
);
|
||||
}
|
||||
|
||||
function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSets {
|
||||
function useMarkdownStyles(): MarkdownStyleSets {
|
||||
const colorScheme = useColorScheme();
|
||||
const colors = MARKDOWN_COLORS[colorScheme === "dark" ? "dark" : "light"];
|
||||
const inlineChipBackground = String(useThemeColor("--color-subtle"));
|
||||
const inlineSkillBackground = String(useThemeColor("--color-inline-skill-background"));
|
||||
const inlineSkillForeground = String(useThemeColor("--color-inline-skill-foreground"));
|
||||
|
||||
return useMemo(() => {
|
||||
@@ -274,12 +302,10 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
const markdownBlockquoteBorder = colors.blockquoteBorder;
|
||||
const markdownCodeBg = colors.codeBackground;
|
||||
const markdownCodeText = colors.codeText;
|
||||
const markdownInlineCodeText = colors.inlineCodeText;
|
||||
const markdownHrColor = colors.horizontalRule;
|
||||
const markdownUserBodyColor = colors.userBody;
|
||||
const markdownUserCodeBg = colors.userCodeBackground;
|
||||
const markdownUserCodeText = colors.userCodeText;
|
||||
const markdownUserInlineCodeText = colors.userInlineCodeText;
|
||||
const markdownUserFenceBg = colors.userFenceBackground;
|
||||
const markdownUserFenceText = colors.userFenceText;
|
||||
|
||||
@@ -368,23 +394,28 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
};
|
||||
|
||||
const createMarkdownRenderers = (
|
||||
inlineBackgroundColor: string,
|
||||
inlineTextColor: string,
|
||||
inlineCodeTextColor: string,
|
||||
blockBackgroundColor: string,
|
||||
blockTextColor: string,
|
||||
preserveSoftBreaks: boolean,
|
||||
): CustomRenderers => ({
|
||||
link: ({ children, href = "" }) => {
|
||||
const presentation = resolveMarkdownLinkPresentation(href);
|
||||
if (presentation.kind === "file") {
|
||||
return (
|
||||
<NativeText
|
||||
onPress={() => onLinkPress(href)}
|
||||
style={[markdownLinkStyles.file, { color: inlineTextColor }]}
|
||||
style={[
|
||||
markdownLinkStyles.file,
|
||||
{
|
||||
backgroundColor: inlineBackgroundColor,
|
||||
borderColor: markdownHrColor,
|
||||
color: inlineTextColor,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Image
|
||||
source={markdownFileIconSource(presentation.icon)}
|
||||
style={markdownLinkStyles.inlineIcon}
|
||||
style={markdownLinkStyles.fileIcon}
|
||||
/>
|
||||
{presentation.label}
|
||||
</NativeText>
|
||||
@@ -461,24 +492,28 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
),
|
||||
code_inline: ({ content }) => {
|
||||
const value = content ?? "";
|
||||
const wrapsPoorly =
|
||||
value.length > 24 || value.includes("/") || value.includes("\\") || value.includes(":");
|
||||
return (
|
||||
<NativeText
|
||||
style={{
|
||||
color: inlineCodeTextColor,
|
||||
color: inlineTextColor,
|
||||
fontFamily: "ui-monospace",
|
||||
fontSize: 12,
|
||||
lineHeight: 22,
|
||||
lineHeight: 18,
|
||||
...(wrapsPoorly
|
||||
? { opacity: 0.82 }
|
||||
: {
|
||||
backgroundColor: inlineBackgroundColor,
|
||||
borderRadius: 4,
|
||||
paddingHorizontal: 3,
|
||||
}),
|
||||
}}
|
||||
>
|
||||
{value}
|
||||
</NativeText>
|
||||
);
|
||||
},
|
||||
...(preserveSoftBreaks
|
||||
? {
|
||||
soft_break: () => <NativeText>{"\n"}</NativeText>,
|
||||
}
|
||||
: {}),
|
||||
code_block: ({ content, language }) => (
|
||||
<View
|
||||
style={{
|
||||
@@ -584,23 +619,23 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
theme: userTheme,
|
||||
styles: userStyles,
|
||||
renderers: createMarkdownRenderers(
|
||||
markdownUserCodeBg,
|
||||
markdownUserCodeText,
|
||||
markdownUserInlineCodeText,
|
||||
markdownUserFenceBg,
|
||||
markdownUserFenceText,
|
||||
true,
|
||||
),
|
||||
nativeTextStyle: {
|
||||
color: markdownUserBodyColor,
|
||||
strongColor: markdownUserBodyColor,
|
||||
mutedColor: markdownUserBodyColor,
|
||||
linkColor: markdownUserBodyColor,
|
||||
inlineCodeColor: markdownUserInlineCodeText,
|
||||
codeColor: markdownUserCodeText,
|
||||
codeBackgroundColor: markdownUserCodeBg,
|
||||
codeBlockBackgroundColor: markdownUserFenceBg,
|
||||
fileBackgroundColor: "rgba(255, 255, 255, 0.12)",
|
||||
fileTextColor: "#ffffff",
|
||||
skillTextColor: "#f0abfc",
|
||||
skillBackgroundColor: "rgba(217, 70, 239, 0.24)",
|
||||
skillTextColor: "#ffffff",
|
||||
quoteMarkerColor: markdownUserBodyColor,
|
||||
dividerColor: markdownUserBodyColor,
|
||||
fontSize: 15,
|
||||
@@ -614,22 +649,22 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
theme: assistantTheme,
|
||||
styles: assistantStyles,
|
||||
renderers: createMarkdownRenderers(
|
||||
markdownCodeText,
|
||||
markdownInlineCodeText,
|
||||
markdownCodeBg,
|
||||
markdownCodeText,
|
||||
false,
|
||||
markdownCodeBg,
|
||||
markdownCodeText,
|
||||
),
|
||||
nativeTextStyle: {
|
||||
color: markdownBodyColor,
|
||||
strongColor: markdownStrongColor,
|
||||
mutedColor: markdownBodyColor,
|
||||
linkColor: markdownLinkColor,
|
||||
inlineCodeColor: markdownInlineCodeText,
|
||||
codeColor: markdownCodeText,
|
||||
codeBackgroundColor: markdownCodeBg,
|
||||
codeBlockBackgroundColor: markdownCodeBg,
|
||||
fileBackgroundColor: inlineChipBackground,
|
||||
fileTextColor: markdownCodeText,
|
||||
skillBackgroundColor: inlineSkillBackground,
|
||||
skillTextColor: inlineSkillForeground,
|
||||
quoteMarkerColor: markdownBlockquoteBorder,
|
||||
dividerColor: markdownHrColor,
|
||||
@@ -641,7 +676,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
},
|
||||
},
|
||||
};
|
||||
}, [colors, inlineSkillForeground, onLinkPress]);
|
||||
}, [colors, inlineChipBackground, inlineSkillBackground, inlineSkillForeground]);
|
||||
}
|
||||
|
||||
function renderFeedEntry(
|
||||
@@ -657,13 +692,11 @@ function renderFeedEntry(
|
||||
readonly onToggleWorkRow: (rowId: string) => void;
|
||||
readonly onToggleTurnFold: (turnId: TurnId) => void;
|
||||
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
|
||||
readonly onMarkdownLinkPress: (href: string) => void;
|
||||
readonly iconSubtleColor: string | import("react-native").ColorValue;
|
||||
readonly userBubbleColor: string | import("react-native").ColorValue;
|
||||
readonly markdownStyles: MarkdownStyleSets;
|
||||
readonly reviewCommentColors: ReviewCommentColors;
|
||||
readonly reviewCommentBubbleWidth: number;
|
||||
readonly userBubbleMaxWidth: number;
|
||||
},
|
||||
) {
|
||||
const entry = info.item;
|
||||
@@ -712,10 +745,9 @@ function renderFeedEntry(
|
||||
return (
|
||||
<View className="mb-5 items-end">
|
||||
<View
|
||||
className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
|
||||
className="max-w-[85%] gap-2 rounded-[20px] px-3.5 py-2.5"
|
||||
style={{
|
||||
backgroundColor: userBubbleColor,
|
||||
maxWidth: props.userBubbleMaxWidth,
|
||||
...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
|
||||
}}
|
||||
>
|
||||
@@ -725,7 +757,6 @@ function renderFeedEntry(
|
||||
markdownStyles={styles}
|
||||
reviewCommentColors={props.reviewCommentColors}
|
||||
skills={props.skills}
|
||||
onLinkPress={props.onMarkdownLinkPress}
|
||||
/>
|
||||
) : null}
|
||||
{attachments.map((attachment) => {
|
||||
@@ -772,7 +803,6 @@ function renderFeedEntry(
|
||||
markdown={message.text}
|
||||
skills={props.skills}
|
||||
textStyle={styles.nativeTextStyle}
|
||||
onLinkPress={props.onMarkdownLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<Markdown
|
||||
@@ -838,17 +868,123 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
const rows = buildActivityRows(entry.activities).filter(
|
||||
(activity) => !(activity.toolLike && activity.status === "neutral"),
|
||||
);
|
||||
if (rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const isExpanded = props.expandedWorkGroups[entry.id] ?? false;
|
||||
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleRows = hasOverflow && !isExpanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
|
||||
const hiddenCount = rows.length - visibleRows.length;
|
||||
const onlyToolRows = rows.every((row) => row.toolLike);
|
||||
const headerTitle = onlyToolRows
|
||||
? rows.length === 1
|
||||
? "1 tool call"
|
||||
: `${rows.length} tool calls`
|
||||
: "Work log";
|
||||
|
||||
return (
|
||||
<ThreadWorkLog
|
||||
activities={entry.activities}
|
||||
copiedRowId={props.copiedRowId}
|
||||
expanded={props.expandedWorkGroups[entry.id] ?? false}
|
||||
expandedRows={props.expandedWorkRows}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
onCopyRow={props.onCopyWorkRow}
|
||||
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
|
||||
onToggleRow={props.onToggleWorkRow}
|
||||
/>
|
||||
<View className="mb-3 rounded-[16px] border border-neutral-300/70 bg-background px-2 py-2.5 dark:border-white/[0.1] dark:bg-white/[0.035]">
|
||||
<View className="mb-1.5 flex-row items-center justify-between gap-3 px-2">
|
||||
<Text className="font-t3-medium text-xs text-foreground">{headerTitle}</Text>
|
||||
{hasOverflow ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: isExpanded }}
|
||||
onPress={() => props.onToggleWorkGroup(entry.id)}
|
||||
className="flex-row items-center gap-1"
|
||||
>
|
||||
<Text className="font-t3-medium text-xs text-foreground-muted">
|
||||
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
|
||||
</Text>
|
||||
<SymbolView
|
||||
name={isExpanded ? "chevron.up" : "chevron.down"}
|
||||
size={12}
|
||||
tintColor={iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
{visibleRows.map((row, index) => (
|
||||
<Pressable
|
||||
key={row.id}
|
||||
accessibilityRole={row.fullDetail ? "button" : undefined}
|
||||
accessibilityState={
|
||||
row.fullDetail ? { expanded: props.expandedWorkRows[row.id] ?? false } : undefined
|
||||
}
|
||||
onPress={() => {
|
||||
if (row.fullDetail) {
|
||||
props.onToggleWorkRow(row.id);
|
||||
}
|
||||
}}
|
||||
onLongPress={() => props.onCopyWorkRow(row.id, row.copyText)}
|
||||
className={cn(
|
||||
"rounded-lg px-2 py-1.5",
|
||||
index > 0 && "border-t border-neutral-200/80 dark:border-white/[0.06]",
|
||||
)}
|
||||
>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View className="w-4 items-center justify-center">
|
||||
<SymbolView
|
||||
name={
|
||||
row.status === "failure"
|
||||
? "xmark"
|
||||
: row.status === "success"
|
||||
? "checkmark"
|
||||
: row.status === "neutral"
|
||||
? "minus"
|
||||
: "terminal"
|
||||
}
|
||||
size={row.status ? 11 : 13}
|
||||
tintColor={row.status === "failure" ? "#e11d48" : iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-[12px] leading-[18px] text-neutral-700 dark:text-neutral-300"
|
||||
numberOfLines={props.expandedWorkRows[row.id] ? undefined : 1}
|
||||
>
|
||||
{row.detail ? `${row.summary} - ${row.detail}` : row.summary}
|
||||
</Text>
|
||||
{row.fullDetail ? (
|
||||
<SymbolView
|
||||
name={props.expandedWorkRows[row.id] ? "chevron.up" : "chevron.down"}
|
||||
size={11}
|
||||
tintColor={iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
) : null}
|
||||
{props.copiedRowId === row.id ? (
|
||||
<Text className="shrink-0 font-t3-medium text-[10px] text-emerald-600 dark:text-emerald-400">
|
||||
Copied
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{row.fullDetail && props.expandedWorkRows[row.id] ? (
|
||||
<ScrollView
|
||||
horizontal
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsHorizontalScrollIndicator
|
||||
bounces={false}
|
||||
className="mt-2 rounded-lg bg-neutral-100 dark:bg-black/20"
|
||||
contentContainerStyle={{ paddingHorizontal: 10, paddingVertical: 8 }}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
className="text-[11px] leading-[17px] text-neutral-600 dark:text-neutral-400"
|
||||
style={{ fontFamily: "ui-monospace" }}
|
||||
>
|
||||
{row.fullDetail}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
) : null}
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -857,7 +993,6 @@ function UserMessageContent(props: {
|
||||
readonly markdownStyles: MarkdownStyleSet;
|
||||
readonly reviewCommentColors: ReviewCommentColors;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
readonly onLinkPress: (href: string) => void;
|
||||
}) {
|
||||
const segments = parseReviewCommentMessageSegments(props.text);
|
||||
const hasReviewComment = segments.some((segment) => segment.kind === "review-comment");
|
||||
@@ -868,8 +1003,6 @@ function UserMessageContent(props: {
|
||||
markdown={props.text}
|
||||
skills={props.skills}
|
||||
textStyle={props.markdownStyles.nativeTextStyle}
|
||||
preserveSoftBreaks
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -909,8 +1042,6 @@ function UserMessageContent(props: {
|
||||
markdown={text}
|
||||
skills={props.skills}
|
||||
textStyle={props.markdownStyles.nativeTextStyle}
|
||||
preserveSoftBreaks
|
||||
onLinkPress={props.onLinkPress}
|
||||
/>
|
||||
) : (
|
||||
<Markdown
|
||||
@@ -1123,7 +1254,6 @@ function ThreadFeedPlaceholder(props: {
|
||||
}
|
||||
|
||||
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const router = useRouter();
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scrollFrameRef = useRef<number | null>(null);
|
||||
@@ -1153,7 +1283,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
} | null>(null);
|
||||
const horizontalPadding = props.layoutVariant === "split" ? 20 : 16;
|
||||
const contentWidth = Math.max(0, viewportWidth - horizontalPadding * 2);
|
||||
const userBubbleMaxWidth = contentWidth * 0.85;
|
||||
const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
|
||||
const insets = useSafeAreaInsets();
|
||||
const topContentInset = props.contentTopInset ?? insets.top + 44;
|
||||
@@ -1161,56 +1290,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
|
||||
const iconSubtleColor = useThemeColor("--color-icon-subtle");
|
||||
const userBubbleColor = useThemeColor("--color-user-bubble");
|
||||
const onMarkdownLinkPress = useCallback(
|
||||
(href: string) => {
|
||||
const presentation = resolveMarkdownLinkPresentation(href);
|
||||
if (presentation.kind === "file") {
|
||||
const relativePath = resolveWorkspaceRelativeFilePath(
|
||||
props.workspaceRoot,
|
||||
presentation.path,
|
||||
);
|
||||
if (relativePath) {
|
||||
void Haptics.selectionAsync();
|
||||
router.push(
|
||||
buildThreadFilesNavigation(
|
||||
{ environmentId: props.environmentId, threadId: props.threadId },
|
||||
relativePath,
|
||||
presentation.line,
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (presentation.href) {
|
||||
void Linking.openURL(presentation.href);
|
||||
}
|
||||
},
|
||||
[props.environmentId, props.threadId, props.workspaceRoot, router],
|
||||
);
|
||||
const markdownStyles = useMarkdownStyles(onMarkdownLinkPress);
|
||||
const markdownStyles = useMarkdownStyles();
|
||||
const reviewCommentColors = useReviewCommentColors();
|
||||
// LegendList does not invalidate visible rows when only the renderItem closure changes.
|
||||
// Keep row-local interaction props in extraData so disclosures and copy feedback repaint.
|
||||
const listAppearanceData = useMemo(
|
||||
() => ({
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
reviewCommentColors,
|
||||
userBubbleColor,
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
reviewCommentColors,
|
||||
userBubbleColor,
|
||||
],
|
||||
[iconSubtleColor, markdownStyles, reviewCommentColors, userBubbleColor],
|
||||
);
|
||||
const presentedFeed = useMemo(
|
||||
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
|
||||
@@ -1401,13 +1490,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onToggleWorkRow,
|
||||
onToggleTurnFold,
|
||||
onPressImage,
|
||||
onMarkdownLinkPress,
|
||||
iconSubtleColor,
|
||||
userBubbleColor,
|
||||
markdownStyles,
|
||||
reviewCommentColors,
|
||||
reviewCommentBubbleWidth,
|
||||
userBubbleMaxWidth,
|
||||
skills: props.skills,
|
||||
}),
|
||||
[
|
||||
@@ -1421,9 +1508,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
markdownStyles,
|
||||
reviewCommentColors,
|
||||
reviewCommentBubbleWidth,
|
||||
userBubbleMaxWidth,
|
||||
onCopyWorkRow,
|
||||
onMarkdownLinkPress,
|
||||
onPressImage,
|
||||
onToggleTurnFold,
|
||||
onToggleWorkGroup,
|
||||
|
||||
@@ -14,7 +14,7 @@ import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import Stack from "expo-router/stack";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { Alert, Linking } from "react-native";
|
||||
import { buildThreadFilesNavigation, buildThreadReviewRoutePath } from "../../lib/routes";
|
||||
import { buildThreadReviewRoutePath } from "../../lib/routes";
|
||||
import {
|
||||
basename,
|
||||
getTerminalStatusLabel,
|
||||
@@ -69,7 +69,6 @@ export function ThreadGitControls(props: {
|
||||
readonly gitStatus: VcsStatusResult | null;
|
||||
readonly gitOperationLabel: string | null;
|
||||
readonly canOpenTerminal: boolean;
|
||||
readonly canOpenFiles: boolean;
|
||||
readonly projectScripts: ReadonlyArray<ProjectScript>;
|
||||
readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
|
||||
readonly onOpenTerminal: (terminalId?: string | null) => void;
|
||||
@@ -260,14 +259,6 @@ export function ThreadGitControls(props: {
|
||||
>
|
||||
<Stack.Toolbar.Label>Review changes</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="folder"
|
||||
disabled={!props.canOpenFiles}
|
||||
onPress={() => router.push(buildThreadFilesNavigation({ environmentId, threadId }))}
|
||||
subtitle="Browse this workspace"
|
||||
>
|
||||
<Stack.Toolbar.Label>Files</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="ellipsis.circle"
|
||||
onPress={() =>
|
||||
|
||||
@@ -420,7 +420,6 @@ export function ThreadRouteScreen() {
|
||||
gitStatus={gitStatus.data}
|
||||
gitOperationLabel={gitState.gitOperationLabel}
|
||||
canOpenTerminal={Boolean(selectedThreadProject?.workspaceRoot)}
|
||||
canOpenFiles={Boolean(selectedThreadProject?.workspaceRoot)}
|
||||
projectScripts={selectedThreadProject?.scripts ?? []}
|
||||
terminalSessions={terminalMenuSessions}
|
||||
onOpenTerminal={handleOpenTerminal}
|
||||
@@ -453,7 +452,6 @@ export function ThreadRouteScreen() {
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
threadCwd={selectedThreadCwd}
|
||||
selectedThreadQueueCount={composer.selectedThreadQueueCount}
|
||||
onOpenDrawer={handleOpenDrawer}
|
||||
onOpenConnectionEditor={handleOpenConnectionEditor}
|
||||
|
||||
@@ -1,261 +0,0 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { SymbolView, type SFSymbol } from "expo-symbols";
|
||||
import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
const WORK_LOG_LAYOUT_ANIMATION = {
|
||||
duration: 180,
|
||||
create: {
|
||||
type: LayoutAnimation.Types.easeInEaseOut,
|
||||
property: LayoutAnimation.Properties.opacity,
|
||||
},
|
||||
update: { type: LayoutAnimation.Types.easeInEaseOut },
|
||||
delete: {
|
||||
type: LayoutAnimation.Types.easeInEaseOut,
|
||||
property: LayoutAnimation.Properties.opacity,
|
||||
},
|
||||
} as const;
|
||||
|
||||
function triggerDisclosureFeedback() {
|
||||
LayoutAnimation.configureNext(WORK_LOG_LAYOUT_ANIMATION);
|
||||
void Haptics.selectionAsync();
|
||||
}
|
||||
|
||||
function stripShellWrapper(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
const match = trimmed.match(/^\/bin\/zsh -lc ['"]?([\s\S]*?)['"]?$/);
|
||||
return (match?.[1] ?? trimmed).trim();
|
||||
}
|
||||
|
||||
function compactActivityDetail(detail: string | null): string | null {
|
||||
if (!detail) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cleaned = stripShellWrapper(detail).replace(/\s+/g, " ").trim();
|
||||
return cleaned.length > 0 ? cleaned : null;
|
||||
}
|
||||
|
||||
function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
|
||||
switch (icon) {
|
||||
case "agent":
|
||||
return "sparkles";
|
||||
case "alert":
|
||||
return "exclamationmark.triangle";
|
||||
case "check":
|
||||
return "checkmark";
|
||||
case "command":
|
||||
return "terminal";
|
||||
case "edit":
|
||||
return "square.and.pencil";
|
||||
case "eye":
|
||||
return "eye";
|
||||
case "globe":
|
||||
return "globe";
|
||||
case "hammer":
|
||||
return "hammer";
|
||||
case "message":
|
||||
return "bubble.left";
|
||||
case "warning":
|
||||
return "xmark";
|
||||
case "wrench":
|
||||
return "wrench";
|
||||
case "zap":
|
||||
return "bolt";
|
||||
}
|
||||
}
|
||||
|
||||
export function ThreadWorkLog(props: {
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expanded: boolean;
|
||||
readonly expandedRows: Readonly<Record<string, boolean>>;
|
||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||
readonly onCopyRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleGroup: () => void;
|
||||
readonly onToggleRow: (rowId: string) => void;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
|
||||
const rows = props.activities
|
||||
.filter((activity) => !(activity.toolLike && activity.status === "neutral"))
|
||||
.map((activity) => ({ ...activity, detail: compactActivityDetail(activity.detail) }));
|
||||
|
||||
if (rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleRows =
|
||||
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
|
||||
const hiddenCount = rows.length - visibleRows.length;
|
||||
const onlyToolRows = rows.every((row) => row.toolLike);
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-3 px-1 py-0.5">
|
||||
{!onlyToolRows ? (
|
||||
<Text className="px-0.5 pb-0.5 font-t3-medium text-[11px] text-foreground-muted opacity-60">
|
||||
work log
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
<View className="gap-px">
|
||||
{visibleRows.map((row) => {
|
||||
const expanded = props.expandedRows[row.id] ?? false;
|
||||
const canExpand = row.fullDetail !== null;
|
||||
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
|
||||
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
|
||||
|
||||
return (
|
||||
<View key={row.id}>
|
||||
<Pressable
|
||||
accessibilityRole={canExpand ? "button" : undefined}
|
||||
accessibilityLabel={displayText}
|
||||
accessibilityHint={
|
||||
canExpand
|
||||
? "Double tap to show full details. Long press to copy."
|
||||
: "Long press to copy."
|
||||
}
|
||||
accessibilityState={canExpand ? { expanded } : undefined}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
if (canExpand) {
|
||||
triggerDisclosureFeedback();
|
||||
props.onToggleRow(row.id);
|
||||
}
|
||||
}}
|
||||
onLongPress={() => props.onCopyRow(row.id, row.copyText)}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="min-h-9 flex-row items-center gap-1.5">
|
||||
<View className="h-5 w-5 shrink-0 items-center justify-center">
|
||||
<SymbolView
|
||||
name={workRowSymbolName(row.icon)}
|
||||
size={14}
|
||||
weight="medium"
|
||||
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-xs leading-5 text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-medium text-foreground",
|
||||
iconIsDestructive && "text-rose-600 dark:text-rose-400",
|
||||
)}
|
||||
>
|
||||
{row.summary}
|
||||
</Text>
|
||||
{row.detail ? (
|
||||
<Text className="text-foreground-muted opacity-60"> {row.detail}</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
|
||||
<View className="shrink-0 flex-row items-center gap-px">
|
||||
{props.copiedRowId === row.id ? (
|
||||
<Text className="pr-1 font-t3-medium text-[10px] text-emerald-600 dark:text-emerald-400">
|
||||
Copied
|
||||
</Text>
|
||||
) : null}
|
||||
<View className="h-4 w-4 items-center justify-center">
|
||||
{canExpand ? (
|
||||
<SymbolView
|
||||
name={expanded ? "chevron.up" : "chevron.down"}
|
||||
size={11}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
<View className="h-4 w-4 items-center justify-center">
|
||||
{row.status ? (
|
||||
<SymbolView
|
||||
name={
|
||||
row.status === "failure"
|
||||
? "xmark"
|
||||
: row.status === "success"
|
||||
? "checkmark"
|
||||
: "minus"
|
||||
}
|
||||
size={11}
|
||||
tintColor={row.status === "failure" ? "#e11d48" : props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
|
||||
{expanded && row.fullDetail ? (
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsVerticalScrollIndicator
|
||||
style={{ maxHeight: 240 }}
|
||||
contentContainerStyle={{ paddingRight: 8 }}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
className="text-[11px] leading-[17px] text-foreground-muted"
|
||||
style={{ fontFamily: "ui-monospace" }}
|
||||
>
|
||||
{row.fullDetail}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
{hasOverflow ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={
|
||||
props.expanded
|
||||
? "Show fewer tool calls"
|
||||
: `Show ${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`
|
||||
}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
triggerDisclosureFeedback();
|
||||
props.onToggleGroup();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="h-5 w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={13}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded
|
||||
? "Show fewer tool calls"
|
||||
: `+${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -16,47 +16,26 @@ describe("resolveMarkdownLinkPresentation", () => {
|
||||
resolveMarkdownLinkPresentation("file:///Users/julius/project/src/main.ts#L42C7"),
|
||||
).toEqual({
|
||||
kind: "file",
|
||||
href: "file:///Users/julius/project/src/main.ts#L42C7",
|
||||
icon: "typescript",
|
||||
label: "main.ts:42:7",
|
||||
path: "/Users/julius/project/src/main.ts",
|
||||
line: 42,
|
||||
column: 7,
|
||||
});
|
||||
});
|
||||
|
||||
it("recognizes relative source paths and bare filenames", () => {
|
||||
expect(resolveMarkdownLinkPresentation("apps/mobile/src/index.ts:10")).toEqual({
|
||||
kind: "file",
|
||||
href: "apps/mobile/src/index.ts:10",
|
||||
icon: "typescript",
|
||||
label: "index.ts:10",
|
||||
path: "apps/mobile/src/index.ts",
|
||||
line: 10,
|
||||
});
|
||||
expect(resolveMarkdownLinkPresentation("AGENTS.md")).toEqual({
|
||||
kind: "file",
|
||||
href: "AGENTS.md",
|
||||
icon: "agents",
|
||||
label: "AGENTS.md",
|
||||
path: "AGENTS.md",
|
||||
});
|
||||
expect(resolveMarkdownLinkPresentation("package.json")).toEqual({
|
||||
kind: "file",
|
||||
href: "package.json",
|
||||
icon: "package",
|
||||
label: "package.json",
|
||||
path: "package.json",
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts line fragments from relative file links", () => {
|
||||
expect(resolveMarkdownLinkPresentation("src/main.ts#L18C2")).toMatchObject({
|
||||
kind: "file",
|
||||
path: "src/main.ts",
|
||||
line: 18,
|
||||
column: 2,
|
||||
label: "main.ts:18:2",
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
nativeMarkdownDocumentRuns,
|
||||
nativeMarkdownListItemBlocks,
|
||||
nativeMarkdownTextRuns,
|
||||
nativeMarkdownWithPreservedSoftBreaks,
|
||||
} from "@t3tools/mobile-markdown-text/markdown";
|
||||
|
||||
describe("nativeMarkdownTextRuns", () => {
|
||||
@@ -55,11 +54,7 @@ describe("nativeMarkdownTextRuns", () => {
|
||||
externalHost: "example.com",
|
||||
},
|
||||
{ text: " " },
|
||||
{
|
||||
text: "README.md:12",
|
||||
href: "file:///repo/README.md#L12",
|
||||
fileIcon: "readme",
|
||||
},
|
||||
{ text: "README.md:12", fileIcon: "readme" },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -78,21 +73,6 @@ describe("nativeMarkdownTextRuns", () => {
|
||||
expect(nativeMarkdownTextRuns(node)).toEqual([{ text: "first second\nthird" }]);
|
||||
});
|
||||
|
||||
it("can preserve soft breaks for authored user messages", () => {
|
||||
const node: MarkdownNode = {
|
||||
type: "paragraph",
|
||||
children: [
|
||||
{ type: "text", content: "first" },
|
||||
{ type: "soft_break" },
|
||||
{ type: "text", content: "second" },
|
||||
],
|
||||
};
|
||||
|
||||
expect(nativeMarkdownTextRuns(nativeMarkdownWithPreservedSoftBreaks(node))).toEqual([
|
||||
{ text: "first\nsecond" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("normalizes common inline HTML and entities", () => {
|
||||
const node: MarkdownNode = {
|
||||
type: "paragraph",
|
||||
@@ -150,7 +130,7 @@ describe("nativeMarkdownTextRuns", () => {
|
||||
});
|
||||
|
||||
describe("nativeMarkdownDocumentRuns", () => {
|
||||
it("decorates known skill references as selectable skill links", () => {
|
||||
it("decorates known skill references as selectable skill chips", () => {
|
||||
const node: MarkdownNode = {
|
||||
type: "document",
|
||||
children: [
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { buildThreadFilesNavigation, buildThreadFilesRoutePath } from "./routes";
|
||||
|
||||
const thread = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
};
|
||||
|
||||
describe("thread file routes", () => {
|
||||
it("includes an optional source line in string routes", () => {
|
||||
expect(buildThreadFilesRoutePath(thread, "src/main.ts", 42)).toBe(
|
||||
"/threads/environment-1/thread-1/files/src/main.ts?line=42",
|
||||
);
|
||||
});
|
||||
|
||||
it("encodes each file path segment without encoding separators", () => {
|
||||
expect(buildThreadFilesRoutePath(thread, "docs/My File#1.md")).toBe(
|
||||
"/threads/environment-1/thread-1/files/docs/My%20File%231.md",
|
||||
);
|
||||
});
|
||||
|
||||
it("builds typed navigation params for a file and source line", () => {
|
||||
expect(buildThreadFilesNavigation(thread, "src/main.ts", 42)).toEqual({
|
||||
pathname: "/threads/[environmentId]/[threadId]/files/[...path]",
|
||||
params: {
|
||||
environmentId: "environment-1",
|
||||
threadId: "thread-1",
|
||||
path: ["src", "main.ts"],
|
||||
line: "42",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("targets the files index when no file path is provided", () => {
|
||||
expect(buildThreadFilesNavigation(thread)).toEqual({
|
||||
pathname: "/threads/[environmentId]/[threadId]/files",
|
||||
params: {
|
||||
environmentId: "environment-1",
|
||||
threadId: "thread-1",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -32,27 +32,6 @@ export function buildThreadReviewRoutePath(
|
||||
return `${buildThreadRoutePath(input)}/review`;
|
||||
}
|
||||
|
||||
export function buildThreadFilesRoutePath(
|
||||
input: ThreadRouteInput | PlainThreadRouteInput,
|
||||
relativePath?: string | null,
|
||||
line?: number | null,
|
||||
): string {
|
||||
const basePath = `${buildThreadRoutePath(input)}/files`;
|
||||
if (!relativePath) {
|
||||
return basePath;
|
||||
}
|
||||
|
||||
const pathSegments = relativePath.split("/").filter((segment) => segment.length > 0);
|
||||
if (pathSegments.length === 0) {
|
||||
return basePath;
|
||||
}
|
||||
|
||||
const encodedPath = pathSegments.map(encodeURIComponent).join("/");
|
||||
const lineParam =
|
||||
Number.isFinite(line) && Number(line) > 0 ? `?line=${Math.floor(Number(line))}` : "";
|
||||
return `${basePath}/${encodedPath}${lineParam}`;
|
||||
}
|
||||
|
||||
export function buildThreadTerminalRoutePath(
|
||||
input: ThreadRouteInput | PlainThreadRouteInput,
|
||||
terminalId?: string | null,
|
||||
@@ -92,38 +71,6 @@ export function buildThreadTerminalNavigation(
|
||||
};
|
||||
}
|
||||
|
||||
export function buildThreadFilesNavigation(
|
||||
input: ThreadRouteInput | PlainThreadRouteInput,
|
||||
relativePath?: string | null,
|
||||
line?: number | null,
|
||||
): Href {
|
||||
const environmentId = String(input.environmentId);
|
||||
const threadId = String("threadId" in input ? input.threadId : input.id);
|
||||
const path = relativePath?.split("/").filter((segment) => segment.length > 0) ?? [];
|
||||
|
||||
if (path.length === 0) {
|
||||
return {
|
||||
pathname: "/threads/[environmentId]/[threadId]/files",
|
||||
params: { environmentId, threadId },
|
||||
};
|
||||
}
|
||||
|
||||
const params: {
|
||||
environmentId: string;
|
||||
threadId: string;
|
||||
path: string[];
|
||||
line?: string;
|
||||
} = { environmentId, threadId, path };
|
||||
if (Number.isFinite(line) && Number(line) > 0) {
|
||||
params.line = String(Math.floor(Number(line)));
|
||||
}
|
||||
|
||||
return {
|
||||
pathname: "/threads/[environmentId]/[threadId]/files/[...path]",
|
||||
params,
|
||||
};
|
||||
}
|
||||
|
||||
export function dismissRoute(router: Router) {
|
||||
if (router.canGoBack()) {
|
||||
router.back();
|
||||
|
||||
@@ -161,65 +161,14 @@ describe("buildThreadFeed", () => {
|
||||
turnId: "turn-1",
|
||||
summary: "Run tests",
|
||||
detail: "bun run test",
|
||||
fullDetail: "/bin/zsh -lc 'bun run test'",
|
||||
copyText: "Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
|
||||
icon: "command",
|
||||
fullDetail: null,
|
||||
copyText: "Run tests\nbun run test",
|
||||
toolLike: true,
|
||||
status: "success",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps MCP inputs available to expanded mobile work rows", () => {
|
||||
const turnId = TurnId.make("turn-mcp");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-mcp"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Expandable MCP call",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("mcp-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Call repository tool",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Call repository tool",
|
||||
itemType: "mcp_tool_call",
|
||||
detail: "repository.search",
|
||||
status: "completed",
|
||||
data: {
|
||||
item: {
|
||||
server: "repository",
|
||||
tool: "search",
|
||||
arguments: { query: "work log" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread, [], null)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities[0]?.icon).toBe("wrench");
|
||||
expect(group.activities[0]?.fullDetail).toContain('"query": "work log"');
|
||||
expect(group.activities[0]?.fullDetail).toContain("repository.search");
|
||||
});
|
||||
|
||||
it("folds settled turn work while leaving the terminal answer visible", () => {
|
||||
const turnId = TurnId.make("turn-1");
|
||||
const thread = makeThread({
|
||||
|
||||
@@ -40,19 +40,6 @@ export interface ThreadFeedActivity {
|
||||
readonly detail: string | null;
|
||||
readonly fullDetail: string | null;
|
||||
readonly copyText: string;
|
||||
readonly icon:
|
||||
| "agent"
|
||||
| "alert"
|
||||
| "check"
|
||||
| "command"
|
||||
| "edit"
|
||||
| "eye"
|
||||
| "globe"
|
||||
| "hammer"
|
||||
| "message"
|
||||
| "warning"
|
||||
| "wrench"
|
||||
| "zap";
|
||||
readonly toolLike: boolean;
|
||||
readonly status: "success" | "failure" | "neutral" | null;
|
||||
}
|
||||
@@ -73,7 +60,6 @@ interface WorkLogEntry {
|
||||
itemType?: ToolLifecycleItemType;
|
||||
requestKind?: PendingApproval["requestKind"];
|
||||
toolLifecycleStatus?: WorkLogToolLifecycleStatus;
|
||||
toolData?: unknown;
|
||||
}
|
||||
|
||||
interface DerivedWorkLogEntry extends WorkLogEntry {
|
||||
@@ -228,7 +214,7 @@ function resolvePendingUserInputAnswer(
|
||||
|
||||
function deriveWorkLogEntries(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): DerivedWorkLogEntry[] {
|
||||
): WorkLogEntry[] {
|
||||
const ordered = Arr.sort(activities, activityOrder);
|
||||
const entries: DerivedWorkLogEntry[] = [];
|
||||
for (const activity of ordered) {
|
||||
@@ -239,7 +225,9 @@ function deriveWorkLogEntries(
|
||||
if (isPlanBoundaryToolActivity(activity)) continue;
|
||||
entries.push(toDerivedWorkLogEntry(activity));
|
||||
}
|
||||
return collapseDerivedWorkLogEntries(entries);
|
||||
return collapseDerivedWorkLogEntries(entries).map(
|
||||
({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
|
||||
);
|
||||
}
|
||||
|
||||
function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
|
||||
@@ -313,12 +301,6 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
if (title) {
|
||||
entry.toolTitle = title;
|
||||
}
|
||||
if (itemType === "mcp_tool_call") {
|
||||
const data = asRecord(payload?.data);
|
||||
if (data?.item !== undefined) {
|
||||
entry.toolData = data.item;
|
||||
}
|
||||
}
|
||||
if (itemType) {
|
||||
entry.itemType = itemType;
|
||||
}
|
||||
@@ -383,7 +365,6 @@ function mergeDerivedWorkLogEntries(
|
||||
const requestKind = next.requestKind ?? previous.requestKind;
|
||||
const collapseKey = next.collapseKey ?? previous.collapseKey;
|
||||
const toolLifecycleStatus = next.toolLifecycleStatus ?? previous.toolLifecycleStatus;
|
||||
const toolData = next.toolData ?? previous.toolData;
|
||||
return {
|
||||
...previous,
|
||||
...next,
|
||||
@@ -396,7 +377,6 @@ function mergeDerivedWorkLogEntries(
|
||||
...(requestKind ? { requestKind } : {}),
|
||||
...(collapseKey ? { collapseKey } : {}),
|
||||
...(toolLifecycleStatus ? { toolLifecycleStatus } : {}),
|
||||
...(toolData !== undefined ? { toolData } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -500,52 +480,6 @@ function workEntryStatus(entry: WorkLogEntry): ThreadFeedActivity["status"] {
|
||||
return "neutral";
|
||||
}
|
||||
|
||||
function workEntryIcon(entry: DerivedWorkLogEntry): ThreadFeedActivity["icon"] {
|
||||
if (
|
||||
entry.activityKind === "user-input.requested" ||
|
||||
entry.activityKind === "user-input.resolved"
|
||||
) {
|
||||
return "message";
|
||||
}
|
||||
if (entry.activityKind === "runtime.warning") return "warning";
|
||||
if (entry.requestKind === "command") return "command";
|
||||
if (entry.requestKind === "file-read") return "eye";
|
||||
if (entry.requestKind === "file-change") return "edit";
|
||||
if (entry.itemType === "command_execution" || entry.command) return "command";
|
||||
if (entry.itemType === "file_change" || (entry.changedFiles?.length ?? 0) > 0) return "edit";
|
||||
if (entry.itemType === "web_search") return "globe";
|
||||
if (entry.itemType === "image_view") return "eye";
|
||||
if (entry.itemType === "mcp_tool_call") return "wrench";
|
||||
if (entry.itemType === "dynamic_tool_call" || entry.itemType === "collab_agent_tool_call") {
|
||||
return "hammer";
|
||||
}
|
||||
if (entry.tone === "error") return "alert";
|
||||
if (entry.tone === "thinking") return "agent";
|
||||
if (entry.tone === "info") return "check";
|
||||
return "zap";
|
||||
}
|
||||
|
||||
function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
|
||||
const blocks: string[] = [];
|
||||
const appendUniqueBlock = (value: string | null | undefined) => {
|
||||
const trimmed = value?.trim();
|
||||
if (trimmed && !blocks.includes(trimmed)) {
|
||||
blocks.push(trimmed);
|
||||
}
|
||||
};
|
||||
|
||||
if (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) {
|
||||
appendUniqueBlock(`MCP call\n${JSON.stringify(entry.toolData, null, 2)}`);
|
||||
}
|
||||
appendUniqueBlock(entry.rawCommand ?? entry.command);
|
||||
appendUniqueBlock(entry.detail);
|
||||
if ((entry.changedFiles?.length ?? 0) > 0) {
|
||||
appendUniqueBlock(entry.changedFiles!.join("\n"));
|
||||
}
|
||||
|
||||
return blocks.length > 0 ? blocks.join("\n\n") : null;
|
||||
}
|
||||
|
||||
function workEntryPreview(
|
||||
workEntry: Pick<WorkLogEntry, "detail" | "command" | "changedFiles">,
|
||||
): string | null {
|
||||
@@ -1292,7 +1226,11 @@ export function buildThreadFeed(
|
||||
.map<RawThreadFeedEntry>((entry) => {
|
||||
const summary = workEntryHeading(entry);
|
||||
const detail = workEntryPreview(entry);
|
||||
const fullDetail = buildWorkEntryExpandedBody(entry);
|
||||
const normalizedFullDetail = entry.detail
|
||||
? unwrapKnownShellCommandWrapper(entry.detail)
|
||||
: null;
|
||||
const fullDetail =
|
||||
normalizedFullDetail && normalizedFullDetail !== detail ? normalizedFullDetail : null;
|
||||
return {
|
||||
type: "activity",
|
||||
id: entry.id,
|
||||
@@ -1305,7 +1243,6 @@ export function buildThreadFeed(
|
||||
summary,
|
||||
detail,
|
||||
fullDetail,
|
||||
icon: workEntryIcon(entry),
|
||||
copyText: [summary, detail, fullDetail]
|
||||
.filter((value, index, values): value is string => {
|
||||
return Boolean(value) && values.indexOf(value) === index;
|
||||
|
||||
@@ -89,42 +89,6 @@ describe("AssetAccess", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues exact workspace URLs for image previews", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-image-workspace-",
|
||||
});
|
||||
const assetsDirectory = path.join(root, "assets");
|
||||
const imagePath = path.join(assetsDirectory, "icon.png");
|
||||
const siblingPath = path.join(assetsDirectory, "other.png");
|
||||
yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
|
||||
yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
|
||||
yield* fileSystem.writeFile(siblingPath, new Uint8Array([137, 80, 78, 71]));
|
||||
const canonicalImagePath = yield* fileSystem.realPath(imagePath);
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
path: imagePath,
|
||||
},
|
||||
workspaceRoot: root,
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const separatorIndex = suffix.indexOf("/");
|
||||
const token = suffix.slice(0, separatorIndex);
|
||||
|
||||
expect(yield* resolveAsset(token, "icon.png")).toEqual({
|
||||
kind: "file",
|
||||
path: canonicalImagePath,
|
||||
});
|
||||
expect(yield* resolveAsset(token, "other.png")).toBeNull();
|
||||
expect(yield* resolveAsset(token, "../icon.png")).toBeNull();
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues exact attachment capabilities by attachment id", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
import type { AssetResource } from "@t3tools/contracts";
|
||||
import { AssetAccessError } from "@t3tools/contracts";
|
||||
import {
|
||||
isWorkspaceImagePreviewPath,
|
||||
isWorkspacePreviewEntryPath,
|
||||
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
|
||||
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
|
||||
} from "@t3tools/shared/filePreview";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -30,14 +24,22 @@ export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/
|
||||
|
||||
const SIGNING_SECRET_NAME = "asset-access-signing-key";
|
||||
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
|
||||
const PREVIEWABLE_EXTENSIONS = new Set([".htm", ".html", ".pdf"]);
|
||||
const PREVIEW_ASSET_EXTENSIONS = new Set([
|
||||
...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
|
||||
...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
|
||||
...PREVIEWABLE_EXTENSIONS,
|
||||
".avif",
|
||||
".css",
|
||||
".gif",
|
||||
".ico",
|
||||
".jpeg",
|
||||
".jpg",
|
||||
".js",
|
||||
".mjs",
|
||||
".otf",
|
||||
".png",
|
||||
".svg",
|
||||
".ttf",
|
||||
".webp",
|
||||
".woff",
|
||||
".woff2",
|
||||
]);
|
||||
@@ -50,13 +52,6 @@ const AssetClaimsSchema = Schema.Union([
|
||||
baseRelativePath: Schema.String,
|
||||
expiresAt: Schema.Number,
|
||||
}),
|
||||
Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
kind: Schema.Literal("workspace-file-exact"),
|
||||
workspaceRoot: Schema.String,
|
||||
relativePath: Schema.String,
|
||||
expiresAt: Schema.Number,
|
||||
}),
|
||||
Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
kind: Schema.Literal("attachment"),
|
||||
@@ -149,8 +144,8 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
const resolved = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
|
||||
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
|
||||
if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
|
||||
return yield* failAccess("Only browser documents and images can be previewed.");
|
||||
if (!PREVIEWABLE_EXTENSIONS.has(path.extname(resolved.relativePath).toLowerCase())) {
|
||||
return yield* failAccess("Only HTML and PDF files can open in the browser.");
|
||||
}
|
||||
const canonicalFile = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot,
|
||||
@@ -159,24 +154,15 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
if (!canonicalFile) {
|
||||
return yield* failAccess("Workspace asset was not found.");
|
||||
}
|
||||
const canonicalWorkspaceRoot = yield* fileSystem
|
||||
.realPath(workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause)));
|
||||
claims = isWorkspaceImagePreviewPath(resolved.relativePath)
|
||||
? {
|
||||
version: 1,
|
||||
kind: "workspace-file-exact",
|
||||
workspaceRoot: canonicalWorkspaceRoot,
|
||||
relativePath: resolved.relativePath,
|
||||
expiresAt,
|
||||
}
|
||||
: {
|
||||
version: 1,
|
||||
kind: "workspace-file",
|
||||
workspaceRoot: canonicalWorkspaceRoot,
|
||||
baseRelativePath: path.dirname(resolved.relativePath),
|
||||
expiresAt,
|
||||
};
|
||||
claims = {
|
||||
version: 1,
|
||||
kind: "workspace-file",
|
||||
workspaceRoot: yield* fileSystem
|
||||
.realPath(workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause))),
|
||||
baseRelativePath: path.dirname(resolved.relativePath),
|
||||
expiresAt,
|
||||
};
|
||||
fileName = path.basename(resolved.relativePath);
|
||||
break;
|
||||
}
|
||||
@@ -282,16 +268,6 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
const decodedPath = decodeRelativePath(relativePath);
|
||||
if (decodedPath === null) return null;
|
||||
const path = yield* Path.Path;
|
||||
if (claims.kind === "workspace-file-exact") {
|
||||
if (decodedPath !== path.basename(claims.relativePath)) return null;
|
||||
const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFile({
|
||||
workspaceRoot: claims.workspaceRoot,
|
||||
relativePath: claims.relativePath,
|
||||
});
|
||||
return exactWorkspaceFile
|
||||
? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
const segments = decodedPath.split(/[\\/]/);
|
||||
if (
|
||||
decodedPath.length === 0 ||
|
||||
|
||||
@@ -61,18 +61,6 @@ export interface GitWorkflowServiceShape {
|
||||
readonly createWorktree: (
|
||||
input: VcsCreateWorktreeInput,
|
||||
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
|
||||
readonly fetchRemote: (input: {
|
||||
readonly cwd: string;
|
||||
readonly remoteName: string;
|
||||
}) => Effect.Effect<void, GitCommandError>;
|
||||
readonly resolveRemoteTrackingCommit: (input: {
|
||||
readonly cwd: string;
|
||||
readonly refName: string;
|
||||
readonly fallbackRemoteName: string;
|
||||
}) => Effect.Effect<
|
||||
{ readonly commitSha: string; readonly remoteRefName: string },
|
||||
GitCommandError
|
||||
>;
|
||||
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly createRef: (
|
||||
input: VcsCreateRefInput,
|
||||
@@ -307,14 +295,6 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
|
||||
Effect.andThen(git.createWorktree(input)),
|
||||
),
|
||||
fetchRemote: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
|
||||
Effect.andThen(git.fetchRemote(input)),
|
||||
),
|
||||
resolveRemoteTrackingCommit: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
|
||||
Effect.andThen(git.resolveRemoteTrackingCommit(input)),
|
||||
),
|
||||
removeWorktree: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
|
||||
Effect.andThen(git.removeWorktree(input)),
|
||||
|
||||
@@ -8,18 +8,16 @@ import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts"
|
||||
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const makeFakeHttpServer = (hostname: string, port = 43123) =>
|
||||
HttpServer.HttpServer.of({
|
||||
address: { _tag: "TcpAddress", hostname, port },
|
||||
serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
|
||||
});
|
||||
const fakeHttpServer = makeFakeHttpServer("127.0.0.1");
|
||||
const fakeHttpServer = HttpServer.HttpServer.of({
|
||||
address: { _tag: "TcpAddress", hostname: "127.0.0.1", port: 43123 },
|
||||
serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
|
||||
});
|
||||
const fakeEnvironment = ServerEnvironment.of({
|
||||
getEnvironmentId: Effect.succeed(environmentId),
|
||||
getDescriptor: Effect.die("unused"),
|
||||
});
|
||||
|
||||
const makeRegistry = (now: () => number, httpServer = fakeHttpServer) =>
|
||||
const makeRegistry = (now: () => number) =>
|
||||
McpSessionRegistry.__testing
|
||||
.make({
|
||||
now,
|
||||
@@ -27,7 +25,7 @@ const makeRegistry = (now: () => number, httpServer = fakeHttpServer) =>
|
||||
maximumLifetimeMs: 1_000,
|
||||
})
|
||||
.pipe(
|
||||
Effect.provideService(HttpServer.HttpServer, httpServer),
|
||||
Effect.provideService(HttpServer.HttpServer, fakeHttpServer),
|
||||
Effect.provideService(ServerEnvironment, fakeEnvironment),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
@@ -55,26 +53,6 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("builds MCP endpoints from the bound server host", () =>
|
||||
Effect.gen(function* () {
|
||||
const cases = [
|
||||
["100.64.0.40", "http://100.64.0.40:43123/mcp"],
|
||||
["0.0.0.0", "http://127.0.0.1:43123/mcp"],
|
||||
["localhost", "http://localhost:43123/mcp"],
|
||||
["127.0.0.1", "http://127.0.0.1:43123/mcp"],
|
||||
] as const;
|
||||
|
||||
for (const [hostname, expectedEndpoint] of cases) {
|
||||
const registry = yield* makeRegistry(() => 1_000, makeFakeHttpServer(hostname));
|
||||
const issued = yield* registry.issue({
|
||||
threadId: ThreadId.make(`thread-${hostname}`),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
});
|
||||
expect(issued.config.endpoint).toBe(expectedEndpoint);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("expires credentials after inactivity", () =>
|
||||
Effect.gen(function* () {
|
||||
let timestamp = 1_000;
|
||||
|
||||
@@ -60,17 +60,6 @@ const bytesToHex = (bytes: Uint8Array): string =>
|
||||
|
||||
const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
|
||||
|
||||
const getHttpMcpEndpointHost = (hostname: string): string => {
|
||||
const normalized = hostname.toLowerCase();
|
||||
const endpointHostname =
|
||||
normalized === "0.0.0.0" || normalized === "::" || normalized === "[::]"
|
||||
? "127.0.0.1"
|
||||
: hostname;
|
||||
return endpointHostname.includes(":") && !endpointHostname.startsWith("[")
|
||||
? `[${endpointHostname}]`
|
||||
: endpointHostname;
|
||||
};
|
||||
|
||||
const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
options: McpSessionRegistryOptions = {},
|
||||
) {
|
||||
@@ -84,7 +73,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
const maximumLifetimeMs = options.maximumLifetimeMs ?? DEFAULT_MAXIMUM_LIFETIME_MS;
|
||||
const endpoint =
|
||||
httpServer.address._tag === "TcpAddress"
|
||||
? `http://${getHttpMcpEndpointHost(httpServer.address.hostname)}:${httpServer.address.port}/mcp`
|
||||
? `http://127.0.0.1:${httpServer.address.port}/mcp`
|
||||
: "http://127.0.0.1/mcp";
|
||||
|
||||
const hashToken = (token: string) =>
|
||||
|
||||
@@ -5918,7 +5918,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const bootstrapGitOperations: string[] = [];
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
@@ -5937,33 +5936,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
pr: null,
|
||||
}),
|
||||
);
|
||||
const fetchRemote = vi.fn(
|
||||
(_: Parameters<GitVcsDriver.GitVcsDriverShape["fetchRemote"]>[0]) =>
|
||||
Effect.sync(() => {
|
||||
bootstrapGitOperations.push("fetch");
|
||||
}),
|
||||
);
|
||||
const fetchedOriginCommit = "0123456789abcdef0123456789abcdef01234567";
|
||||
const resolveRemoteTrackingCommit = vi.fn(
|
||||
(_: Parameters<GitVcsDriver.GitVcsDriverShape["resolveRemoteTrackingCommit"]>[0]) =>
|
||||
Effect.sync(() => {
|
||||
bootstrapGitOperations.push("resolve-remote-commit");
|
||||
return {
|
||||
commitSha: fetchedOriginCommit,
|
||||
remoteRefName: "origin/main",
|
||||
};
|
||||
}),
|
||||
);
|
||||
const createWorktree = vi.fn(
|
||||
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
|
||||
Effect.sync(() => {
|
||||
bootstrapGitOperations.push("create-worktree");
|
||||
return {
|
||||
worktree: {
|
||||
refName: "t3code/bootstrap-refName",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
};
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
refName: "t3code/bootstrap-refName",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const runForThread = vi.fn(
|
||||
@@ -5980,8 +5959,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitVcsDriver: {
|
||||
fetchRemote,
|
||||
resolveRemoteTrackingCommit,
|
||||
createWorktree,
|
||||
},
|
||||
vcsStatusBroadcaster: {
|
||||
@@ -6033,7 +6010,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-refName",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
runSetupScript: true,
|
||||
},
|
||||
@@ -6055,24 +6031,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
);
|
||||
assert.deepEqual(createWorktree.mock.calls[0]?.[0], {
|
||||
cwd: "/tmp/project",
|
||||
refName: fetchedOriginCommit,
|
||||
refName: "main",
|
||||
newRefName: "t3code/bootstrap-refName",
|
||||
path: null,
|
||||
});
|
||||
assert.deepEqual(fetchRemote.mock.calls[0]?.[0], {
|
||||
cwd: "/tmp/project",
|
||||
remoteName: "origin",
|
||||
});
|
||||
assert.deepEqual(resolveRemoteTrackingCommit.mock.calls[0]?.[0], {
|
||||
cwd: "/tmp/project",
|
||||
refName: "main",
|
||||
fallbackRemoteName: "origin",
|
||||
});
|
||||
assert.deepEqual(bootstrapGitOperations, [
|
||||
"fetch",
|
||||
"resolve-remote-commit",
|
||||
"create-worktree",
|
||||
]);
|
||||
assert.deepEqual(runForThread.mock.calls[0]?.[0], {
|
||||
threadId: ThreadId.make("thread-bootstrap"),
|
||||
projectId: defaultProjectId,
|
||||
|
||||
@@ -161,22 +161,6 @@ export interface GitFetchRemoteTrackingBranchInput {
|
||||
remoteBranch: string;
|
||||
}
|
||||
|
||||
export interface GitFetchRemoteInput {
|
||||
cwd: string;
|
||||
remoteName: string;
|
||||
}
|
||||
|
||||
export interface GitResolveRemoteTrackingCommitInput {
|
||||
cwd: string;
|
||||
refName: string;
|
||||
fallbackRemoteName: string;
|
||||
}
|
||||
|
||||
export interface GitResolveRemoteTrackingCommitResult {
|
||||
commitSha: string;
|
||||
remoteRefName: string;
|
||||
}
|
||||
|
||||
export interface GitSetBranchUpstreamInput {
|
||||
cwd: string;
|
||||
branch: string;
|
||||
@@ -233,10 +217,6 @@ export interface GitVcsDriverShape {
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
|
||||
readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
|
||||
readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly resolveRemoteTrackingCommit: (
|
||||
input: GitResolveRemoteTrackingCommitInput,
|
||||
) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;
|
||||
readonly fetchRemoteBranch: (
|
||||
input: GitFetchRemoteBranchInput,
|
||||
) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
@@ -442,69 +442,6 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
});
|
||||
|
||||
describe("remote operations", () => {
|
||||
it.effect("creates a worktree from the latest fetched remote commit", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-remote-");
|
||||
const peer = yield* makeTmpDir("git-peer-");
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(remote, ["symbolic-ref", "HEAD", `refs/heads/${initialBranch}`]);
|
||||
const beforeFetch = yield* git(cwd, ["rev-parse", `refs/remotes/origin/${initialBranch}`]);
|
||||
|
||||
yield* git(peer, ["clone", remote, "."]);
|
||||
yield* git(peer, ["config", "user.email", "[email protected]"]);
|
||||
yield* git(peer, ["config", "user.name", "Test"]);
|
||||
yield* writeTextFile(peer, "remote-change.txt", "remote\n");
|
||||
yield* git(peer, ["add", "remote-change.txt"]);
|
||||
yield* git(peer, ["commit", "-m", "remote change"]);
|
||||
yield* git(peer, ["push", "origin", initialBranch]);
|
||||
const remoteHead = yield* git(peer, ["rev-parse", "HEAD"]);
|
||||
assert.notEqual(beforeFetch, remoteHead);
|
||||
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
yield* driver.fetchRemote({ cwd, remoteName: "origin" });
|
||||
|
||||
const resolvedBase = yield* driver.resolveRemoteTrackingCommit({
|
||||
cwd,
|
||||
refName: initialBranch,
|
||||
fallbackRemoteName: "origin",
|
||||
});
|
||||
const explicitlyResolvedBase = yield* driver.resolveRemoteTrackingCommit({
|
||||
cwd,
|
||||
refName: `origin/${initialBranch}`,
|
||||
fallbackRemoteName: "origin",
|
||||
});
|
||||
|
||||
assert.deepEqual(resolvedBase, {
|
||||
commitSha: remoteHead,
|
||||
remoteRefName: `origin/${initialBranch}`,
|
||||
});
|
||||
assert.deepEqual(explicitlyResolvedBase, resolvedBase);
|
||||
assert.equal(yield* git(cwd, ["rev-parse", initialBranch]), beforeFetch);
|
||||
|
||||
const pathService = yield* Path.Path;
|
||||
const worktreePath = pathService.join(
|
||||
yield* makeTmpDir("git-fetched-worktrees-"),
|
||||
"fetched-origin",
|
||||
);
|
||||
yield* driver.createWorktree({
|
||||
cwd,
|
||||
path: worktreePath,
|
||||
refName: resolvedBase.commitSha,
|
||||
newRefName: "t3code/fetched-origin",
|
||||
});
|
||||
|
||||
assert.equal(yield* git(worktreePath, ["rev-parse", "HEAD"]), remoteHead);
|
||||
assert.equal(
|
||||
yield* driver.readConfigValue(worktreePath, "branch.t3code/fetched-origin.remote"),
|
||||
null,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pushes with upstream setup and skips when already up to date", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
|
||||
@@ -2188,38 +2188,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
);
|
||||
});
|
||||
|
||||
const fetchRemote: GitVcsDriver.GitVcsDriverShape["fetchRemote"] = Effect.fn("fetchRemote")(
|
||||
function* (input) {
|
||||
yield* executeGit(
|
||||
"GitVcsDriver.fetchRemote",
|
||||
input.cwd,
|
||||
["fetch", "--quiet", input.remoteName],
|
||||
{
|
||||
env: STATUS_UPSTREAM_REFRESH_ENV,
|
||||
fallbackErrorMessage: `git fetch ${input.remoteName} failed`,
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const resolveRemoteTrackingCommit: GitVcsDriver.GitVcsDriverShape["resolveRemoteTrackingCommit"] =
|
||||
Effect.fn("resolveRemoteTrackingCommit")(function* (input) {
|
||||
const remoteNames = yield* listRemoteNames(input.cwd);
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(
|
||||
input.refName,
|
||||
remoteNames.toSorted((left, right) => right.length - left.length),
|
||||
);
|
||||
const remoteRefName =
|
||||
parsedRemoteRef?.remoteRef ?? `${input.fallbackRemoteName}/${input.refName}`;
|
||||
const commitSha = yield* runGitStdout("GitVcsDriver.resolveRemoteTrackingCommit", input.cwd, [
|
||||
"rev-parse",
|
||||
"--verify",
|
||||
`refs/remotes/${remoteRefName}^{commit}`,
|
||||
]).pipe(Effect.map((stdout) => stdout.trim()));
|
||||
|
||||
return { commitSha, remoteRefName };
|
||||
});
|
||||
|
||||
const fetchRemoteBranch: GitVcsDriver.GitVcsDriverShape["fetchRemoteBranch"] = Effect.fn(
|
||||
"fetchRemoteBranch",
|
||||
)(function* (input) {
|
||||
@@ -2445,8 +2413,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
fetchPullRequestBranch,
|
||||
ensureRemote,
|
||||
resolvePrimaryRemoteName,
|
||||
fetchRemote,
|
||||
resolveRemoteTrackingCommit,
|
||||
fetchRemoteBranch,
|
||||
fetchRemoteTrackingBranch,
|
||||
setBranchUpstream,
|
||||
|
||||
+1
-14
@@ -694,22 +694,9 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
|
||||
}
|
||||
|
||||
if (bootstrap?.prepareWorktree) {
|
||||
let worktreeBaseRef = bootstrap.prepareWorktree.baseBranch;
|
||||
if (bootstrap.prepareWorktree.startFromOrigin) {
|
||||
yield* gitWorkflow.fetchRemote({
|
||||
cwd: bootstrap.prepareWorktree.projectCwd,
|
||||
remoteName: "origin",
|
||||
});
|
||||
const resolvedRemoteBase = yield* gitWorkflow.resolveRemoteTrackingCommit({
|
||||
cwd: bootstrap.prepareWorktree.projectCwd,
|
||||
refName: bootstrap.prepareWorktree.baseBranch,
|
||||
fallbackRemoteName: "origin",
|
||||
});
|
||||
worktreeBaseRef = resolvedRemoteBase.commitSha;
|
||||
}
|
||||
const worktree = yield* gitWorkflow.createWorktree({
|
||||
cwd: bootstrap.prepareWorktree.projectCwd,
|
||||
refName: worktreeBaseRef,
|
||||
refName: bootstrap.prepareWorktree.baseBranch,
|
||||
newRefName: bootstrap.prepareWorktree.branch,
|
||||
path: null,
|
||||
});
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@tanstack/react-router": "^1.160.2",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { Children, isValidElement, type ReactElement, type ReactNode } from "react";
|
||||
import { RouterProvider } from "@tanstack/react-router";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
|
||||
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
|
||||
import type { AppRouter } from "./router";
|
||||
import { AppRoot } from "./AppRoot";
|
||||
|
||||
describe("AppRoot", () => {
|
||||
it("shares the application atom registry with routed UI and the Electron browser host", () => {
|
||||
const root = AppRoot({ router: {} as AppRouter });
|
||||
|
||||
expect(root.type).toBe(AppAtomRegistryProvider);
|
||||
const children = Children.toArray(
|
||||
(root as ReactElement<{ readonly children: ReactNode }>).props.children,
|
||||
);
|
||||
expect(children).toHaveLength(2);
|
||||
expect(isValidElement(children[0]) && children[0].type).toBe(RouterProvider);
|
||||
expect(isValidElement(children[1]) && children[1].type).toBe(ElectronBrowserHost);
|
||||
});
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
import { RouterProvider } from "@tanstack/react-router";
|
||||
|
||||
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
|
||||
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
|
||||
import type { AppRouter } from "./router";
|
||||
|
||||
/**
|
||||
* Owns renderer-wide providers. The Electron browser host intentionally sits
|
||||
* outside the router so its webviews survive route transitions, but it must
|
||||
* share the same atom registry as routed UI.
|
||||
*/
|
||||
export function AppRoot({ router }: { readonly router: AppRouter }) {
|
||||
return (
|
||||
<AppAtomRegistryProvider>
|
||||
<RouterProvider router={router} />
|
||||
<ElectronBrowserHost />
|
||||
</AppAtomRegistryProvider>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { useEffect, useMemo } from "react";
|
||||
|
||||
import { isElectron } from "~/env";
|
||||
import { useTheme } from "~/hooks/useTheme";
|
||||
import { useActivePreviewSessions } from "~/previewStateStore";
|
||||
import { usePreviewStateStore } from "~/previewStateStore";
|
||||
|
||||
import { readPreviewAnnotationTheme } from "./annotationTheme";
|
||||
import { useBrowserPointerStore } from "./browserPointerStore";
|
||||
@@ -13,7 +13,7 @@ import { HostedBrowserWebview } from "./HostedBrowserWebview";
|
||||
|
||||
export function ElectronBrowserHost() {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const previewByThreadKey = useActivePreviewSessions();
|
||||
const previewByThreadKey = usePreviewStateStore((state) => state.byThreadKey);
|
||||
const sessions = useMemo(
|
||||
() =>
|
||||
Object.entries(previewByThreadKey).flatMap(([threadKey, previewState]) => {
|
||||
|
||||
@@ -7,9 +7,9 @@ import { useCallback, useEffect, useRef } from "react";
|
||||
import { previewBridge } from "~/components/preview/previewBridge";
|
||||
import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
|
||||
|
||||
import { useActiveBrowserRecordingTabId } from "./browserRecording";
|
||||
import { useBrowserRecordingStore } from "./browserRecording";
|
||||
import { useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
import { acquireDesktopTab, type AcquiredDesktopTab } from "./desktopTabLifetime";
|
||||
import { acquireDesktopTab } from "./desktopTabLifetime";
|
||||
import { usePreviewWebviewConfig } from "./previewWebviewConfigState";
|
||||
|
||||
interface ElectronWebview extends HTMLElement {
|
||||
@@ -34,21 +34,13 @@ export function HostedBrowserWebview(props: {
|
||||
const { threadRef, tabId, initialUrl } = props;
|
||||
const config = usePreviewWebviewConfig(threadRef.environmentId);
|
||||
const initialSrcRef = useRef(initialUrl ?? "about:blank");
|
||||
const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
|
||||
const webviewRef = useRef<ElectronWebview | null>(null);
|
||||
const presentation = useBrowserSurfaceStore(useShallow((state) => state.byTabId[tabId] ?? null));
|
||||
const recording = useActiveBrowserRecordingTabId() === tabId;
|
||||
const recording = useBrowserRecordingStore((state) => state.activeTabId === tabId);
|
||||
|
||||
usePreviewBridge({ threadRef, tabId });
|
||||
|
||||
useEffect(() => {
|
||||
const lease = acquireDesktopTab(tabId);
|
||||
tabLeaseRef.current = lease;
|
||||
return () => {
|
||||
if (tabLeaseRef.current === lease) tabLeaseRef.current = null;
|
||||
lease.release();
|
||||
};
|
||||
}, [tabId]);
|
||||
useEffect(() => acquireDesktopTab(tabId), [tabId]);
|
||||
|
||||
const setWebviewRef = useCallback((node: HTMLElement | null) => {
|
||||
webviewRef.current = node as ElectronWebview | null;
|
||||
@@ -59,34 +51,19 @@ export function HostedBrowserWebview(props: {
|
||||
const webview = webviewRef.current;
|
||||
const bridge = previewBridge;
|
||||
if (!webview || !config || !bridge) return;
|
||||
let disposed = false;
|
||||
const register = () => {
|
||||
const lease = tabLeaseRef.current;
|
||||
if (!lease) return;
|
||||
void (async () => {
|
||||
try {
|
||||
// The main-process tab and the DOM webview are created by separate
|
||||
// effects. Wait for the former so registration cannot race and fail
|
||||
// with PreviewTabNotFoundError on a fast about:blank attachment.
|
||||
await lease.ready;
|
||||
if (disposed || webviewRef.current !== webview) return;
|
||||
const webContentsId = webview.getWebContentsId();
|
||||
if (Number.isInteger(webContentsId) && webContentsId > 0) {
|
||||
await bridge.registerWebview(tabId, webContentsId);
|
||||
}
|
||||
} catch {
|
||||
// did-attach/dom-ready will retry if the guest was not ready yet.
|
||||
try {
|
||||
const webContentsId = webview.getWebContentsId();
|
||||
if (Number.isInteger(webContentsId) && webContentsId > 0) {
|
||||
void bridge.registerWebview(tabId, webContentsId);
|
||||
}
|
||||
})();
|
||||
} catch {
|
||||
// A later dom-ready will retry registration.
|
||||
}
|
||||
};
|
||||
webview.addEventListener("did-attach", register);
|
||||
webview.addEventListener("dom-ready", register);
|
||||
register();
|
||||
return () => {
|
||||
disposed = true;
|
||||
webview.removeEventListener("did-attach", register);
|
||||
webview.removeEventListener("dom-ready", register);
|
||||
};
|
||||
return () => webview.removeEventListener("dom-ready", register);
|
||||
}, [config, tabId]);
|
||||
|
||||
if (!config) return null;
|
||||
|
||||
@@ -2,11 +2,9 @@ import type {
|
||||
DesktopPreviewRecordingArtifact,
|
||||
DesktopPreviewRecordingFrame,
|
||||
} from "@t3tools/contracts";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { create } from "zustand";
|
||||
|
||||
import { previewBridge } from "~/components/preview/previewBridge";
|
||||
import { appAtomRegistry } from "~/rpc/atomRegistry";
|
||||
import { useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
|
||||
interface ActiveRecording {
|
||||
@@ -19,15 +17,22 @@ interface ActiveRecording {
|
||||
readonly startedAt: string;
|
||||
}
|
||||
|
||||
const activeBrowserRecordingTabIdAtom = Atom.make<string | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel("preview:active-browser-recording-tab"),
|
||||
);
|
||||
|
||||
export function useActiveBrowserRecordingTabId(): string | null {
|
||||
return useAtomValue(activeBrowserRecordingTabIdAtom);
|
||||
interface BrowserRecordingState {
|
||||
activeTabId: string | null;
|
||||
startedAt: string | null;
|
||||
lastArtifact: DesktopPreviewRecordingArtifact | null;
|
||||
setActive: (tabId: string | null, startedAt: string | null) => void;
|
||||
setArtifact: (artifact: DesktopPreviewRecordingArtifact) => void;
|
||||
}
|
||||
|
||||
export const useBrowserRecordingStore = create<BrowserRecordingState>()((set) => ({
|
||||
activeTabId: null,
|
||||
startedAt: null,
|
||||
lastArtifact: null,
|
||||
setActive: (activeTabId, startedAt) => set({ activeTabId, startedAt }),
|
||||
setArtifact: (lastArtifact) => set({ lastArtifact }),
|
||||
}));
|
||||
|
||||
let active: ActiveRecording | null = null;
|
||||
let unsubscribeFrames: (() => void) | null = null;
|
||||
|
||||
@@ -51,30 +56,9 @@ const drawFrame = (frame: DesktopPreviewRecordingFrame): void => {
|
||||
image.src = `data:image/jpeg;base64,${frame.data}`;
|
||||
};
|
||||
|
||||
const stopMediaRecorder = async (recorder: MediaRecorder): Promise<void> => {
|
||||
if (recorder.state === "inactive") return;
|
||||
const stopped = new Promise<void>((resolve) =>
|
||||
recorder.addEventListener("stop", () => resolve(), { once: true }),
|
||||
);
|
||||
recorder.stop();
|
||||
await stopped;
|
||||
};
|
||||
|
||||
const clearActiveRecording = (recording: ActiveRecording): void => {
|
||||
if (active !== recording) return;
|
||||
active = null;
|
||||
unsubscribeFrames?.();
|
||||
unsubscribeFrames = null;
|
||||
appAtomRegistry.set(activeBrowserRecordingTabIdAtom, null);
|
||||
};
|
||||
|
||||
export async function startBrowserRecording(tabId: string): Promise<string> {
|
||||
export async function startBrowserRecording(tabId: string): Promise<void> {
|
||||
const bridge = previewBridge;
|
||||
if (!bridge) throw new Error("Browser recording is unavailable.");
|
||||
if (active) {
|
||||
if (active.tabId === tabId) return active.startedAt;
|
||||
throw new Error("Another preview tab is already being recorded.");
|
||||
}
|
||||
if (!bridge || active) return;
|
||||
const rect = useBrowserSurfaceStore.getState().byTabId[tabId]?.rect;
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, rect?.width ?? 1280);
|
||||
@@ -91,17 +75,15 @@ export async function startBrowserRecording(tabId: string): Promise<string> {
|
||||
recorder.addEventListener("dataavailable", (event) => {
|
||||
if (event.data.size > 0) chunks.push(event.data);
|
||||
});
|
||||
const recording = { tabId, canvas, context, recorder, chunks, mimeType, startedAt };
|
||||
active = recording;
|
||||
active = { tabId, canvas, context, recorder, chunks, mimeType, startedAt };
|
||||
unsubscribeFrames ??= bridge.recording.onFrame(drawFrame);
|
||||
recorder.start(1_000);
|
||||
try {
|
||||
await bridge.recording.startScreencast(tabId);
|
||||
appAtomRegistry.set(activeBrowserRecordingTabIdAtom, tabId);
|
||||
return startedAt;
|
||||
useBrowserRecordingStore.getState().setActive(tabId, startedAt);
|
||||
} catch (error) {
|
||||
await stopMediaRecorder(recorder);
|
||||
clearActiveRecording(recording);
|
||||
active = null;
|
||||
recorder.stop();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -112,17 +94,22 @@ export async function stopBrowserRecording(
|
||||
const bridge = previewBridge;
|
||||
const recording = active;
|
||||
if (!bridge || !recording || recording.tabId !== tabId) return null;
|
||||
try {
|
||||
await bridge.recording.stopScreencast(tabId);
|
||||
await stopMediaRecorder(recording.recorder);
|
||||
const blob = new Blob(recording.chunks, { type: recording.mimeType });
|
||||
return await bridge.recording.save(
|
||||
tabId,
|
||||
recording.mimeType,
|
||||
new Uint8Array(await blob.arrayBuffer()),
|
||||
);
|
||||
} finally {
|
||||
await stopMediaRecorder(recording.recorder);
|
||||
clearActiveRecording(recording);
|
||||
}
|
||||
await bridge.recording.stopScreencast(tabId);
|
||||
const stopped = new Promise<void>((resolve) =>
|
||||
recording.recorder.addEventListener("stop", () => resolve(), { once: true }),
|
||||
);
|
||||
recording.recorder.stop();
|
||||
await stopped;
|
||||
const blob = new Blob(recording.chunks, { type: recording.mimeType });
|
||||
const artifact = await bridge.recording.save(
|
||||
tabId,
|
||||
recording.mimeType,
|
||||
new Uint8Array(await blob.arrayBuffer()),
|
||||
);
|
||||
active = null;
|
||||
unsubscribeFrames?.();
|
||||
unsubscribeFrames = null;
|
||||
useBrowserRecordingStore.getState().setActive(null, null);
|
||||
useBrowserRecordingStore.getState().setArtifact(artifact);
|
||||
return artifact;
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const { closeTab, createTab } = vi.hoisted(() => ({
|
||||
closeTab: vi.fn(async () => undefined),
|
||||
createTab: vi.fn<() => Promise<void>>(),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/preview/previewBridge", () => ({
|
||||
previewBridge: { closeTab, createTab },
|
||||
}));
|
||||
|
||||
import { acquireDesktopTab } from "./desktopTabLifetime";
|
||||
|
||||
describe("desktopTabLifetime", () => {
|
||||
beforeEach(() => {
|
||||
closeTab.mockClear();
|
||||
createTab.mockClear();
|
||||
});
|
||||
|
||||
it("shares tab creation readiness across concurrent leases", async () => {
|
||||
let resolveCreation: (() => void) | undefined;
|
||||
createTab.mockReturnValueOnce(
|
||||
new Promise<void>((resolve) => {
|
||||
resolveCreation = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
const first = acquireDesktopTab("tab_readiness");
|
||||
const second = acquireDesktopTab("tab_readiness");
|
||||
|
||||
expect(createTab).toHaveBeenCalledOnce();
|
||||
expect(first.ready).toBe(second.ready);
|
||||
|
||||
let ready = false;
|
||||
void first.ready.then(() => {
|
||||
ready = true;
|
||||
});
|
||||
await Promise.resolve();
|
||||
expect(ready).toBe(false);
|
||||
|
||||
resolveCreation?.();
|
||||
await first.ready;
|
||||
expect(ready).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -3,42 +3,28 @@ import { previewBridge } from "~/components/preview/previewBridge";
|
||||
interface DesktopTabLease {
|
||||
references: number;
|
||||
closeTimer: number | null;
|
||||
ready: Promise<void>;
|
||||
}
|
||||
|
||||
const leases = new Map<string, DesktopTabLease>();
|
||||
|
||||
export interface AcquiredDesktopTab {
|
||||
readonly ready: Promise<void>;
|
||||
readonly release: () => void;
|
||||
}
|
||||
|
||||
export function acquireDesktopTab(tabId: string): AcquiredDesktopTab {
|
||||
const current =
|
||||
leases.get(tabId) ??
|
||||
({
|
||||
references: 0,
|
||||
closeTimer: null,
|
||||
ready: previewBridge?.createTab(tabId) ?? Promise.resolve(),
|
||||
} satisfies DesktopTabLease);
|
||||
export function acquireDesktopTab(tabId: string): () => void {
|
||||
const current = leases.get(tabId) ?? { references: 0, closeTimer: null };
|
||||
if (current.closeTimer !== null) window.clearTimeout(current.closeTimer);
|
||||
current.references += 1;
|
||||
current.closeTimer = null;
|
||||
leases.set(tabId, current);
|
||||
if (current.references === 1) void previewBridge?.createTab(tabId);
|
||||
|
||||
return {
|
||||
ready: current.ready,
|
||||
release: () => {
|
||||
const lease = leases.get(tabId);
|
||||
if (!lease) return;
|
||||
lease.references = Math.max(0, lease.references - 1);
|
||||
if (lease.references > 0) return;
|
||||
lease.closeTimer = window.setTimeout(() => {
|
||||
const latest = leases.get(tabId);
|
||||
if (!latest || latest.references > 0) return;
|
||||
leases.delete(tabId);
|
||||
void previewBridge?.closeTab(tabId);
|
||||
}, 0);
|
||||
},
|
||||
return () => {
|
||||
const lease = leases.get(tabId);
|
||||
if (!lease) return;
|
||||
lease.references = Math.max(0, lease.references - 1);
|
||||
if (lease.references > 0) return;
|
||||
lease.closeTimer = window.setTimeout(() => {
|
||||
const latest = leases.get(tabId);
|
||||
if (!latest || latest.references > 0) return;
|
||||
leases.delete(tabId);
|
||||
void previewBridge?.closeTab(tabId);
|
||||
}, 0);
|
||||
};
|
||||
}
|
||||
@@ -15,11 +15,7 @@ import * as Data from "effect/Data";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { resolveAssetUrl } from "~/assets/assetUrls";
|
||||
import {
|
||||
applyPreviewServerSnapshot,
|
||||
isPreviewSupportedInRuntime,
|
||||
rememberPreviewUrl,
|
||||
} from "~/previewStateStore";
|
||||
import { isPreviewSupportedInRuntime, usePreviewStateStore } from "~/previewStateStore";
|
||||
import { useRightPanelStore } from "~/rightPanelStore";
|
||||
|
||||
export const isBrowserPreviewFile = (path: string): boolean =>
|
||||
@@ -46,8 +42,8 @@ export async function openUrlInPreview<E>(input: {
|
||||
input: { threadId: input.threadRef.threadId, url: input.url },
|
||||
});
|
||||
return mapAtomCommandResult(result, (snapshot) => {
|
||||
applyPreviewServerSnapshot(input.threadRef, snapshot);
|
||||
rememberPreviewUrl(input.threadRef, input.url);
|
||||
usePreviewStateStore.getState().applyServerSnapshot(input.threadRef, snapshot);
|
||||
usePreviewStateStore.getState().rememberUrl(input.threadRef, input.url);
|
||||
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { createContext, use, type ReactNode } from "react";
|
||||
|
||||
const OpenAddProjectCommandPaletteContext = createContext<(() => void) | null>(null);
|
||||
|
||||
export function OpenAddProjectCommandPaletteProvider(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly openAddProject: () => void;
|
||||
}) {
|
||||
return (
|
||||
<OpenAddProjectCommandPaletteContext value={props.openAddProject}>
|
||||
{props.children}
|
||||
</OpenAddProjectCommandPaletteContext>
|
||||
);
|
||||
}
|
||||
|
||||
export function useOpenAddProjectCommandPalette(): () => void {
|
||||
const openAddProject = use(OpenAddProjectCommandPaletteContext);
|
||||
if (!openAddProject) {
|
||||
throw new Error("Command palette actions must be used inside CommandPalette");
|
||||
}
|
||||
return openAddProject;
|
||||
}
|
||||
|
||||
/** Read at event time so the chat tree does not subscribe to transient dialog state. */
|
||||
export function isCommandPaletteOpen(): boolean {
|
||||
return (
|
||||
typeof document !== "undefined" && document.querySelector("[data-command-palette]") !== null
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { create } from "zustand";
|
||||
|
||||
interface CommandPaletteOpenIntent {
|
||||
kind: "add-project";
|
||||
requestId: number;
|
||||
}
|
||||
|
||||
interface CommandPaletteStore {
|
||||
open: boolean;
|
||||
openIntent: CommandPaletteOpenIntent | null;
|
||||
setOpen: (open: boolean) => void;
|
||||
toggleOpen: () => void;
|
||||
openAddProject: () => void;
|
||||
clearOpenIntent: () => void;
|
||||
}
|
||||
|
||||
export const useCommandPaletteStore = create<CommandPaletteStore>((set) => ({
|
||||
open: false,
|
||||
openIntent: null,
|
||||
setOpen: (open) => set({ open, ...(open ? {} : { openIntent: null }) }),
|
||||
toggleOpen: () =>
|
||||
set((state) => ({ open: !state.open, ...(state.open ? { openIntent: null } : {}) })),
|
||||
openAddProject: () =>
|
||||
set((state) => ({
|
||||
open: true,
|
||||
openIntent: {
|
||||
kind: "add-project",
|
||||
requestId: (state.openIntent?.requestId ?? 0) + 1,
|
||||
},
|
||||
})),
|
||||
clearOpenIntent: () => set({ openIntent: null }),
|
||||
}));
|
||||
@@ -3,6 +3,10 @@ import { useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import { Sidebar, SidebarProvider, SidebarRail } from "./ui/sidebar";
|
||||
import {
|
||||
clearShortcutModifierState,
|
||||
syncShortcutModifierStateFromKeyboardEvent,
|
||||
} from "../shortcutModifierState";
|
||||
|
||||
const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width";
|
||||
const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16;
|
||||
@@ -10,6 +14,28 @@ const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16;
|
||||
export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
syncShortcutModifierStateFromKeyboardEvent(event);
|
||||
};
|
||||
const onWindowKeyUp = (event: KeyboardEvent) => {
|
||||
syncShortcutModifierStateFromKeyboardEvent(event);
|
||||
};
|
||||
const onWindowBlur = () => {
|
||||
clearShortcutModifierState();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown, true);
|
||||
window.addEventListener("keyup", onWindowKeyUp, true);
|
||||
window.addEventListener("blur", onWindowBlur);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown, true);
|
||||
window.removeEventListener("keyup", onWindowKeyUp, true);
|
||||
window.removeEventListener("blur", onWindowBlur);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const onMenuAction = window.desktopBridge?.onMenuAction;
|
||||
if (typeof onMenuAction !== "function") {
|
||||
|
||||
@@ -45,8 +45,6 @@ interface BranchToolbarProps {
|
||||
effectiveEnvModeOverride?: EnvMode;
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
startFromOrigin: boolean;
|
||||
onStartFromOriginChange: (startFromOrigin: boolean) => void;
|
||||
envLocked: boolean;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
@@ -198,8 +196,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
startFromOrigin,
|
||||
onStartFromOriginChange,
|
||||
envLocked,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
@@ -283,8 +279,6 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
{...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
|
||||
{...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
|
||||
{...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
|
||||
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||
/>
|
||||
|
||||
@@ -5,12 +5,11 @@ import {
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import type { EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { ChevronDownIcon, GitBranchIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
|
||||
import { ChevronDownIcon, GitBranchIcon, SearchIcon } from "lucide-react";
|
||||
import {
|
||||
useCallback,
|
||||
useDeferredValue,
|
||||
useEffect,
|
||||
useId,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useOptimistic,
|
||||
@@ -38,8 +37,6 @@ import {
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import { Switch } from "./ui/switch";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxEmpty,
|
||||
@@ -61,8 +58,6 @@ interface BranchToolbarBranchSelectorProps {
|
||||
effectiveEnvModeOverride?: "local" | "worktree";
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (refName: string | null) => void;
|
||||
startFromOrigin: boolean;
|
||||
onStartFromOriginChange: (startFromOrigin: boolean) => void;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
@@ -95,12 +90,9 @@ export function BranchToolbarBranchSelector({
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
startFromOrigin,
|
||||
onStartFromOriginChange,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarBranchSelectorProps) {
|
||||
const startFromOriginSwitchId = useId();
|
||||
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
|
||||
const updateThreadMetadata = useAtomCommand(
|
||||
threadEnvironment.updateMetadata,
|
||||
@@ -682,34 +674,6 @@ export function BranchToolbarBranchSelector({
|
||||
/>
|
||||
</ComboboxListVirtualized>
|
||||
</div>
|
||||
{isSelectingWorktreeBase ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<label
|
||||
htmlFor={startFromOriginSwitchId}
|
||||
className="flex cursor-pointer items-center justify-between gap-3 border-t border-border/60 px-3 py-2 text-xs"
|
||||
>
|
||||
<span className="flex min-w-0 items-center gap-1.5 font-medium text-muted-foreground">
|
||||
<RefreshCwIcon aria-hidden="true" className="size-3 shrink-0 opacity-70" />
|
||||
<span className="truncate">Start from origin</span>
|
||||
</span>
|
||||
<Switch
|
||||
id={startFromOriginSwitchId}
|
||||
checked={startFromOrigin}
|
||||
className="[--thumb-size:--spacing(3.5)]"
|
||||
aria-label="Start worktree from origin"
|
||||
onCheckedChange={(checked) => onStartFromOriginChange(Boolean(checked))}
|
||||
/>
|
||||
</label>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-72 whitespace-normal leading-tight">
|
||||
Creates the worktree from the latest matching branch on origin instead of your local
|
||||
branch.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
|
||||
</div>
|
||||
</ComboboxPopup>
|
||||
|
||||
@@ -99,7 +99,7 @@ import {
|
||||
} from "../types";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { isCommandPaletteOpen } from "../commandPaletteContext";
|
||||
import { useCommandPaletteStore } from "../commandPaletteStore";
|
||||
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
|
||||
import { useMediaQuery } from "../hooks/useMediaQuery";
|
||||
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
|
||||
@@ -112,11 +112,9 @@ import {
|
||||
} from "../rightPanelStore";
|
||||
import {
|
||||
isPreviewSupportedInRuntime,
|
||||
setActivePreviewTab,
|
||||
useThreadPreviewState,
|
||||
selectThreadPreviewState,
|
||||
usePreviewStateStore,
|
||||
} from "../previewStateStore";
|
||||
import { addBrowserSurface } from "./preview/addBrowserSurface";
|
||||
import { closePreviewSession } from "./preview/closePreviewSession";
|
||||
import { subscribePreviewAction } from "./preview/previewActionBus";
|
||||
import { getConfiguredPreviewUrls } from "./preview/previewEmptyStateLogic";
|
||||
import { PreviewAutomationOwner } from "./preview/PreviewAutomationOwner";
|
||||
@@ -141,7 +139,6 @@ import { getProviderModelCapabilities, resolveSelectableProvider } from "../prov
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { resolveAppModelSelectionForInstance } from "../modelSelection";
|
||||
import { getTerminalFocusOwner } from "../lib/terminalFocus";
|
||||
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
|
||||
import {
|
||||
deriveLogicalProjectKeyFromSettings,
|
||||
selectProjectGroupingSettings,
|
||||
@@ -1130,10 +1127,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const [pendingServerThreadEnvMode, setPendingServerThreadEnvMode] =
|
||||
useState<DraftThreadEnvMode | null>(null);
|
||||
const [pendingServerThreadBranch, setPendingServerThreadBranch] = useState<string | null>();
|
||||
const [
|
||||
pendingServerThreadStartFromOriginByThreadId,
|
||||
setPendingServerThreadStartFromOriginByThreadId,
|
||||
] = useState<Record<string, boolean>>({});
|
||||
const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage(
|
||||
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
|
||||
{},
|
||||
@@ -1269,7 +1262,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
);
|
||||
const activeFileSurface =
|
||||
activeRightPanelSurface?.kind === "file" ? activeRightPanelSurface : null;
|
||||
const activePreviewState = useThreadPreviewState(activeThreadRef);
|
||||
const activePreviewState = usePreviewStateStore((state) =>
|
||||
selectThreadPreviewState(state.byThreadKey, activeThreadRef),
|
||||
);
|
||||
const panelTerminalIds = useMemo(
|
||||
() =>
|
||||
new Set(
|
||||
@@ -2751,8 +2746,23 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}, [activeThreadRef, dismissPlanSidebarForCurrentTurn]);
|
||||
const createBrowserSurface = useCallback(() => {
|
||||
if (!activeThreadRef) return;
|
||||
void addBrowserSurface({ threadRef: activeThreadRef, openPreview });
|
||||
}, [activeThreadRef, openPreview]);
|
||||
const activeTabId = activePreviewState.activeTabId;
|
||||
if (activeTabId) {
|
||||
useRightPanelStore.getState().openBrowser(activeThreadRef, activeTabId);
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
const result = await openPreview({
|
||||
environmentId: activeThreadRef.environmentId,
|
||||
input: { threadId: activeThreadRef.threadId },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
return;
|
||||
}
|
||||
usePreviewStateStore.getState().applyServerSnapshot(activeThreadRef, result.value);
|
||||
useRightPanelStore.getState().openBrowser(activeThreadRef, result.value.tabId);
|
||||
})();
|
||||
}, [activePreviewState.activeTabId, activeThreadRef, openPreview]);
|
||||
const addDiffSurface = useCallback(() => {
|
||||
if (!activeThreadRef || !isServerThread || !isGitRepo) return;
|
||||
useRightPanelStore.getState().open(activeThreadRef, "diff");
|
||||
@@ -2797,14 +2807,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
search: (previous) => ({ ...stripDiffSearchParams(previous), diff: undefined }),
|
||||
});
|
||||
}
|
||||
const activeTabId = activePreviewState.activeTabId;
|
||||
if (activeTabId) {
|
||||
useRightPanelStore.getState().openBrowser(activeThreadRef, activeTabId);
|
||||
} else {
|
||||
createBrowserSurface();
|
||||
}
|
||||
createBrowserSurface();
|
||||
}, [
|
||||
activePreviewState.activeTabId,
|
||||
activeThreadRef,
|
||||
createBrowserSurface,
|
||||
diffOpen,
|
||||
@@ -2929,7 +2933,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id);
|
||||
if (surface.kind === "preview" && surface.resourceId) {
|
||||
setActivePreviewTab(activeThreadRef, surface.resourceId);
|
||||
usePreviewStateStore.getState().setActiveTab(activeThreadRef, surface.resourceId);
|
||||
}
|
||||
if (surface.kind === "terminal") {
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
@@ -2989,11 +2993,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
|
||||
for (const surface of surfaces) {
|
||||
if (surface.kind === "preview" && surface.resourceId) {
|
||||
void closePreviewSession({
|
||||
closePreview,
|
||||
snapshot: activePreviewState.sessions[surface.resourceId] ?? null,
|
||||
tabId: surface.resourceId,
|
||||
threadRef: activeThreadRef,
|
||||
usePreviewStateStore.getState().removeSession(activeThreadRef, surface.resourceId);
|
||||
void closePreview({
|
||||
environmentId: activeThreadRef.environmentId,
|
||||
input: { threadId: activeThreadRef.threadId, tabId: surface.resourceId },
|
||||
});
|
||||
}
|
||||
if (surface.kind === "terminal") {
|
||||
@@ -3017,7 +3020,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
},
|
||||
[
|
||||
activeThreadRef,
|
||||
activePreviewState.sessions,
|
||||
closePreview,
|
||||
closeTerminalMutation,
|
||||
diffOpen,
|
||||
@@ -3035,7 +3037,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
activeThreadRef,
|
||||
);
|
||||
if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) {
|
||||
setActivePreviewTab(activeThreadRef, nextActiveSurface.resourceId);
|
||||
usePreviewStateStore.getState().setActiveTab(activeThreadRef, nextActiveSurface.resourceId);
|
||||
}
|
||||
}, [activeThreadRef]);
|
||||
const closeRightPanelSurface = useCallback(
|
||||
@@ -3335,12 +3337,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
canOverrideServerThreadEnvMode && pendingServerThreadBranch !== undefined
|
||||
? pendingServerThreadBranch
|
||||
: (activeThread?.branch ?? null);
|
||||
const startFromOrigin = isLocalDraftThread
|
||||
? (draftThread?.startFromOrigin ?? false)
|
||||
: canOverrideServerThreadEnvMode
|
||||
? (pendingServerThreadStartFromOriginByThreadId[activeThread?.id ?? ""] ??
|
||||
settings.newWorktreesStartFromOrigin)
|
||||
: false;
|
||||
const sendEnvMode = resolveSendEnvMode({
|
||||
requestedEnvMode: envMode,
|
||||
isGitRepo,
|
||||
@@ -3426,7 +3422,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (event: globalThis.KeyboardEvent) => {
|
||||
if (!activeThreadId || isCommandPaletteOpen()) {
|
||||
if (!activeThreadId || useCommandPaletteStore.getState().open) {
|
||||
return;
|
||||
}
|
||||
const terminalFocusOwner = getTerminalFocusOwner();
|
||||
@@ -3903,7 +3899,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
projectCwd: activeProject.workspaceRoot,
|
||||
baseBranch: baseBranchForWorktree,
|
||||
branch: buildTemporaryWorktreeBranchName(randomHex),
|
||||
...(startFromOrigin ? { startFromOrigin: true } : {}),
|
||||
},
|
||||
runSetupScript: true,
|
||||
}
|
||||
@@ -4589,10 +4584,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
if (isLocalDraftThread) {
|
||||
setDraftThreadContext(composerDraftTarget, {
|
||||
envMode: mode,
|
||||
startFromOrigin: resolveNewDraftStartFromOrigin({
|
||||
envMode: mode,
|
||||
newWorktreesStartFromOrigin: settings.newWorktreesStartFromOrigin,
|
||||
}),
|
||||
...(mode === "worktree" && draftThread?.worktreePath ? { worktreePath: null } : {}),
|
||||
});
|
||||
}
|
||||
@@ -4603,29 +4594,12 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
composerDraftTarget,
|
||||
draftThread?.worktreePath,
|
||||
isLocalDraftThread,
|
||||
settings.newWorktreesStartFromOrigin,
|
||||
setPendingServerThreadEnvMode,
|
||||
scheduleComposerFocus,
|
||||
setDraftThreadContext,
|
||||
],
|
||||
);
|
||||
|
||||
const onStartFromOriginChange = (nextStartFromOrigin: boolean) => {
|
||||
if (canOverrideServerThreadEnvMode && activeThread) {
|
||||
setPendingServerThreadStartFromOriginByThreadId((current) =>
|
||||
current[activeThread.id] === nextStartFromOrigin
|
||||
? current
|
||||
: { ...current, [activeThread.id]: nextStartFromOrigin },
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (isLocalDraftThread) {
|
||||
setDraftThreadContext(composerDraftTarget, {
|
||||
startFromOrigin: nextStartFromOrigin,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const onExpandTimelineImage = useCallback((preview: ExpandedImagePreview) => {
|
||||
setExpandedImage(preview);
|
||||
}, []);
|
||||
@@ -4959,8 +4933,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(canOverrideServerThreadEnvMode ? { effectiveEnvModeOverride: envMode } : {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
|
||||
@@ -36,14 +36,13 @@ import {
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { OpenAddProjectCommandPaletteProvider } from "../commandPaletteContext";
|
||||
import { useCommandPaletteStore } from "../commandPaletteStore";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { readLocalApi } from "../localApi";
|
||||
@@ -323,49 +322,10 @@ function errorMessage(error: unknown): string {
|
||||
return "An error occurred.";
|
||||
}
|
||||
|
||||
interface CommandPaletteOpenIntent {
|
||||
readonly kind: "add-project";
|
||||
}
|
||||
|
||||
interface CommandPaletteUiState {
|
||||
readonly open: boolean;
|
||||
readonly openIntent: CommandPaletteOpenIntent | null;
|
||||
}
|
||||
|
||||
type CommandPaletteUiAction =
|
||||
| { readonly _tag: "SetOpen"; readonly open: boolean }
|
||||
| { readonly _tag: "Toggle" }
|
||||
| { readonly _tag: "OpenAddProject" }
|
||||
| { readonly _tag: "ClearOpenIntent" };
|
||||
|
||||
function reduceCommandPaletteUiState(
|
||||
state: CommandPaletteUiState,
|
||||
action: CommandPaletteUiAction,
|
||||
): CommandPaletteUiState {
|
||||
switch (action._tag) {
|
||||
case "SetOpen":
|
||||
return {
|
||||
open: action.open,
|
||||
openIntent: action.open ? state.openIntent : null,
|
||||
};
|
||||
case "Toggle":
|
||||
return { open: !state.open, openIntent: null };
|
||||
case "OpenAddProject":
|
||||
return { open: true, openIntent: { kind: "add-project" } };
|
||||
case "ClearOpenIntent":
|
||||
return state.openIntent ? { ...state, openIntent: null } : state;
|
||||
}
|
||||
}
|
||||
|
||||
export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
const [state, dispatch] = useReducer(reduceCommandPaletteUiState, {
|
||||
open: false,
|
||||
openIntent: null,
|
||||
});
|
||||
const setOpen = useCallback((open: boolean) => dispatch({ _tag: "SetOpen", open }), []);
|
||||
const toggleOpen = useCallback(() => dispatch({ _tag: "Toggle" }), []);
|
||||
const openAddProject = useCallback(() => dispatch({ _tag: "OpenAddProject" }), []);
|
||||
const clearOpenIntent = useCallback(() => dispatch({ _tag: "ClearOpenIntent" }), []);
|
||||
const open = useCommandPaletteStore((store) => store.open);
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
const toggleOpen = useCommandPaletteStore((store) => store.toggleOpen);
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
|
||||
const routeTarget = useParams({
|
||||
@@ -400,48 +360,37 @@ export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
}, [keybindings, terminalOpen, toggleOpen]);
|
||||
|
||||
return (
|
||||
<OpenAddProjectCommandPaletteProvider openAddProject={openAddProject}>
|
||||
<ComposerHandleContext value={composerHandleRef}>
|
||||
<CommandDialog open={state.open} onOpenChange={setOpen}>
|
||||
{children}
|
||||
<CommandPaletteDialog
|
||||
open={state.open}
|
||||
openIntent={state.openIntent}
|
||||
setOpen={setOpen}
|
||||
clearOpenIntent={clearOpenIntent}
|
||||
/>
|
||||
</CommandDialog>
|
||||
</ComposerHandleContext>
|
||||
</OpenAddProjectCommandPaletteProvider>
|
||||
<ComposerHandleContext value={composerHandleRef}>
|
||||
<CommandDialog open={open} onOpenChange={setOpen}>
|
||||
{children}
|
||||
<CommandPaletteDialog />
|
||||
</CommandDialog>
|
||||
</ComposerHandleContext>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandPaletteDialog(props: {
|
||||
readonly open: boolean;
|
||||
readonly openIntent: CommandPaletteOpenIntent | null;
|
||||
readonly setOpen: (open: boolean) => void;
|
||||
readonly clearOpenIntent: () => void;
|
||||
}) {
|
||||
if (!props.open) {
|
||||
function CommandPaletteDialog() {
|
||||
const open = useCommandPaletteStore((store) => store.open);
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setOpen(false);
|
||||
};
|
||||
}, [setOpen]);
|
||||
|
||||
if (!open) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<OpenCommandPaletteDialog
|
||||
openIntent={props.openIntent}
|
||||
setOpen={props.setOpen}
|
||||
clearOpenIntent={props.clearOpenIntent}
|
||||
/>
|
||||
);
|
||||
return <OpenCommandPaletteDialog />;
|
||||
}
|
||||
|
||||
function OpenCommandPaletteDialog(props: {
|
||||
readonly openIntent: CommandPaletteOpenIntent | null;
|
||||
readonly setOpen: (open: boolean) => void;
|
||||
readonly clearOpenIntent: () => void;
|
||||
}) {
|
||||
function OpenCommandPaletteDialog() {
|
||||
const navigate = useNavigate();
|
||||
const { clearOpenIntent, openIntent, setOpen } = props;
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
const openIntent = useCommandPaletteStore((store) => store.openIntent);
|
||||
const clearOpenIntent = useCommandPaletteStore((store) => store.clearOpenIntent);
|
||||
const composerHandleRef = useComposerHandleContext();
|
||||
const [query, setQuery] = useState("");
|
||||
const deferredQuery = useDeferredValue(query);
|
||||
@@ -1517,7 +1466,6 @@ function OpenCommandPaletteDialog(props: {
|
||||
<CommandDialogPopup
|
||||
aria-label="Command palette"
|
||||
className="overflow-hidden p-0"
|
||||
data-command-palette="true"
|
||||
data-testid="command-palette"
|
||||
finalFocus={() => {
|
||||
composerHandleRef?.current?.focusAtEnd();
|
||||
|
||||
@@ -237,7 +237,6 @@ describe("resolveSidebarNewThreadSeedContext", () => {
|
||||
branch: "feature/draft",
|
||||
worktreePath: "/repo/.t3/worktrees/draft",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
@@ -279,14 +278,12 @@ describe("resolveSidebarNewThreadSeedContext", () => {
|
||||
branch: "feature/new-draft",
|
||||
worktreePath: "/repo/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
branch: "feature/new-draft",
|
||||
worktreePath: "/repo/worktree",
|
||||
envMode: "worktree",
|
||||
startFromOrigin: true,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -189,13 +189,11 @@ export function resolveSidebarNewThreadSeedContext(input: {
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
envMode: SidebarNewThreadEnvMode;
|
||||
startFromOrigin: boolean;
|
||||
} | null;
|
||||
}): {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
envMode: SidebarNewThreadEnvMode;
|
||||
startFromOrigin?: boolean;
|
||||
} {
|
||||
if (input.defaultEnvMode === "worktree") {
|
||||
return {
|
||||
@@ -208,7 +206,6 @@ export function resolveSidebarNewThreadSeedContext(input: {
|
||||
branch: input.activeDraftThread.branch,
|
||||
worktreePath: input.activeDraftThread.worktreePath,
|
||||
envMode: input.activeDraftThread.envMode,
|
||||
startFromOrigin: input.activeDraftThread.startFromOrigin,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -97,12 +97,12 @@ import {
|
||||
threadJumpIndexFromCommand,
|
||||
threadTraversalDirectionFromCommand,
|
||||
} from "../keybindings";
|
||||
import { isModelPickerOpen } from "../modelPickerVisibility";
|
||||
import { useModelPickerOpen } from "../modelPickerOpenState";
|
||||
import { useShortcutModifierState } from "../shortcutModifierState";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
|
||||
import { useDesktopUpdateState } from "../state/desktopUpdate";
|
||||
import { useDesktopUpdateState } from "../lib/desktopUpdateReactQuery";
|
||||
|
||||
import { useThreadActions } from "../hooks/useThreadActions";
|
||||
import { projectEnvironment } from "../state/projects";
|
||||
@@ -174,7 +174,7 @@ import {
|
||||
useSidebar,
|
||||
} from "./ui/sidebar";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
|
||||
import { useCommandPaletteStore } from "../commandPaletteStore";
|
||||
import {
|
||||
getSidebarThreadIdsToPrewarm,
|
||||
resolveAdjacentThreadId,
|
||||
@@ -323,7 +323,7 @@ interface SidebarThreadRowProps {
|
||||
renamingCommittedRef: React.RefObject<boolean>;
|
||||
confirmingArchiveThreadKey: string | null;
|
||||
setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>;
|
||||
confirmArchiveButtonRefs: Map<string, HTMLButtonElement>;
|
||||
confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>;
|
||||
handleThreadClick: (
|
||||
event: React.MouseEvent,
|
||||
threadRef: ScopedThreadRef,
|
||||
@@ -608,9 +608,9 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
const handleConfirmArchiveRef = useCallback(
|
||||
(element: HTMLButtonElement | null) => {
|
||||
if (element) {
|
||||
confirmArchiveButtonRefs.set(threadKey, element);
|
||||
confirmArchiveButtonRefs.current.set(threadKey, element);
|
||||
} else {
|
||||
confirmArchiveButtonRefs.delete(threadKey);
|
||||
confirmArchiveButtonRefs.current.delete(threadKey);
|
||||
}
|
||||
},
|
||||
[confirmArchiveButtonRefs, threadKey],
|
||||
@@ -636,7 +636,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
event.stopPropagation();
|
||||
setConfirmingArchiveThreadKey(threadKey);
|
||||
requestAnimationFrame(() => {
|
||||
confirmArchiveButtonRefs.get(threadKey)?.focus();
|
||||
confirmArchiveButtonRefs.current.get(threadKey)?.focus();
|
||||
});
|
||||
},
|
||||
[confirmArchiveButtonRefs, setConfirmingArchiveThreadKey, threadKey],
|
||||
@@ -888,7 +888,7 @@ interface SidebarProjectThreadListProps {
|
||||
renamingCommittedRef: React.RefObject<boolean>;
|
||||
confirmingArchiveThreadKey: string | null;
|
||||
setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>;
|
||||
confirmArchiveButtonRefs: Map<string, HTMLButtonElement>;
|
||||
confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>;
|
||||
attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void;
|
||||
handleThreadClick: (
|
||||
event: React.MouseEvent,
|
||||
@@ -1223,7 +1223,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
>("inherit");
|
||||
const renamingCommittedRef = useRef(false);
|
||||
const renamingInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const confirmArchiveButtonRefs = useMemo(() => new Map<string, HTMLButtonElement>(), []);
|
||||
const confirmArchiveButtonRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
const memberProjectByScopedKey = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
@@ -1875,7 +1875,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
branch: currentActiveDraftThread.branch,
|
||||
worktreePath: currentActiveDraftThread.worktreePath,
|
||||
envMode: currentActiveDraftThread.envMode,
|
||||
startFromOrigin: currentActiveDraftThread.startFromOrigin,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
@@ -1890,9 +1889,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
? { worktreePath: seedContext.worktreePath }
|
||||
: {}),
|
||||
envMode: seedContext.envMode,
|
||||
...(seedContext.startFromOrigin !== undefined
|
||||
? { startFromOrigin: seedContext.startFromOrigin }
|
||||
: {}),
|
||||
}),
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
@@ -3040,13 +3036,8 @@ export default function Sidebar() {
|
||||
select: (params) => resolveThreadRouteRef(params),
|
||||
});
|
||||
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
|
||||
const routeTerminalOpen = useTerminalUiStateStore((state) =>
|
||||
routeThreadRef
|
||||
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
|
||||
: false,
|
||||
);
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const openAddProjectCommandPalette = useOpenAddProjectCommandPalette();
|
||||
const openAddProjectCommandPalette = useCommandPaletteStore((store) => store.openAddProject);
|
||||
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
|
||||
ReadonlySet<string>
|
||||
>(() => new Set());
|
||||
@@ -3054,11 +3045,12 @@ export default function Sidebar() {
|
||||
const dragInProgressRef = useRef(false);
|
||||
const suppressProjectClickAfterDragRef = useRef(false);
|
||||
const suppressProjectClickForContextMenuRef = useRef(false);
|
||||
const desktopUpdateState = useDesktopUpdateState();
|
||||
const { data: desktopUpdateState = null } = useDesktopUpdateState();
|
||||
const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
|
||||
const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
|
||||
const platform = navigator.platform;
|
||||
const shortcutModifiers = useShortcutModifierState();
|
||||
const modelPickerOpen = useModelPickerOpen();
|
||||
const { environments } = useEnvironments();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const environmentLabelById = useMemo(
|
||||
@@ -3160,10 +3152,15 @@ export default function Sidebar() {
|
||||
const getCurrentSidebarShortcutContext = useCallback(
|
||||
() => ({
|
||||
terminalFocus: isTerminalFocused(),
|
||||
terminalOpen: routeTerminalOpen,
|
||||
modelPickerOpen: isModelPickerOpen(),
|
||||
terminalOpen: routeThreadRef
|
||||
? selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
routeThreadRef,
|
||||
).terminalOpen
|
||||
: false,
|
||||
modelPickerOpen,
|
||||
}),
|
||||
[routeTerminalOpen],
|
||||
[modelPickerOpen, routeThreadRef],
|
||||
);
|
||||
const newThreadShortcutLabelOptions = useMemo(
|
||||
() => ({
|
||||
@@ -3246,26 +3243,22 @@ export default function Sidebar() {
|
||||
dragInProgressRef.current = false;
|
||||
}, []);
|
||||
|
||||
const animatedProjectListsRef = useRef<WeakSet<HTMLElement> | null>(null);
|
||||
const animatedProjectListsRef = useRef(new WeakSet<HTMLElement>());
|
||||
const attachProjectListAutoAnimateRef = useCallback((node: HTMLElement | null) => {
|
||||
const animatedProjectLists =
|
||||
animatedProjectListsRef.current ?? (animatedProjectListsRef.current = new WeakSet());
|
||||
if (!node || animatedProjectLists.has(node)) {
|
||||
if (!node || animatedProjectListsRef.current.has(node)) {
|
||||
return;
|
||||
}
|
||||
autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS);
|
||||
animatedProjectLists.add(node);
|
||||
animatedProjectListsRef.current.add(node);
|
||||
}, []);
|
||||
|
||||
const animatedThreadListsRef = useRef<WeakSet<HTMLElement> | null>(null);
|
||||
const animatedThreadListsRef = useRef(new WeakSet<HTMLElement>());
|
||||
const attachThreadListAutoAnimateRef = useCallback((node: HTMLElement | null) => {
|
||||
const animatedThreadLists =
|
||||
animatedThreadListsRef.current ?? (animatedThreadListsRef.current = new WeakSet());
|
||||
if (!node || animatedThreadLists.has(node)) {
|
||||
if (!node || animatedThreadListsRef.current.has(node)) {
|
||||
return;
|
||||
}
|
||||
autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS);
|
||||
animatedThreadLists.add(node);
|
||||
animatedThreadListsRef.current.add(node);
|
||||
}, []);
|
||||
|
||||
const visibleThreads = useMemo(
|
||||
@@ -3367,11 +3360,19 @@ export default function Sidebar() {
|
||||
() => [...threadJumpCommandByKey.keys()],
|
||||
[threadJumpCommandByKey],
|
||||
);
|
||||
const sidebarShortcutContext = {
|
||||
terminalFocus: false,
|
||||
terminalOpen: routeTerminalOpen,
|
||||
modelPickerOpen: isModelPickerOpen(),
|
||||
};
|
||||
const sidebarShortcutContext = useMemo(
|
||||
() => ({
|
||||
terminalFocus: false,
|
||||
terminalOpen: routeThreadRef
|
||||
? selectThreadTerminalUiState(
|
||||
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
|
||||
routeThreadRef,
|
||||
).terminalOpen
|
||||
: false,
|
||||
modelPickerOpen,
|
||||
}),
|
||||
[modelPickerOpen, routeThreadRef],
|
||||
);
|
||||
const threadJumpLabelByKey = useMemo(
|
||||
() =>
|
||||
buildThreadJumpLabelMap({
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
getTriggerDisplayModelLabel,
|
||||
getTriggerDisplayModelName,
|
||||
} from "./providerIconUtils";
|
||||
import { setModelPickerOpen } from "../../modelPickerOpenState";
|
||||
import type { ProviderInstanceEntry } from "../../providerInstances";
|
||||
|
||||
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
@@ -78,6 +79,13 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setModelPickerOpen(isMenuOpen);
|
||||
return () => {
|
||||
setModelPickerOpen(false);
|
||||
};
|
||||
}, [isMenuOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isMenuOpen) {
|
||||
return;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import type {
|
||||
PreviewAutomationNavigateInput,
|
||||
@@ -11,14 +12,14 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { useCallback, useEffect, useId, useRef } from "react";
|
||||
|
||||
import {
|
||||
applyPreviewServerSnapshot,
|
||||
readThreadPreviewState,
|
||||
subscribeThreadPreviewState,
|
||||
} from "~/previewStateStore";
|
||||
import { selectThreadPreviewState, usePreviewStateStore } from "~/previewStateStore";
|
||||
import { useRightPanelStore } from "~/rightPanelStore";
|
||||
import { resolveBrowserNavigationTarget } from "~/browser/browserTargetResolver";
|
||||
import { startBrowserRecording, stopBrowserRecording } from "~/browser/browserRecording";
|
||||
import {
|
||||
startBrowserRecording,
|
||||
stopBrowserRecording,
|
||||
useBrowserRecordingStore,
|
||||
} from "~/browser/browserRecording";
|
||||
import { previewEnvironment } from "~/state/preview";
|
||||
import { useEnvironmentQuery } from "~/state/query";
|
||||
import { useEnvironmentConnectionState } from "~/state/environments";
|
||||
@@ -51,7 +52,7 @@ const waitForDesktopOverlay = async (
|
||||
): Promise<void> => {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() <= deadline) {
|
||||
const state = readThreadPreviewState(threadRef);
|
||||
const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, threadRef);
|
||||
const tabId = state.snapshot?.tabId;
|
||||
if (tabId && state.desktopOverlay && previewBridge) {
|
||||
const status = await previewBridge.automation.status(tabId);
|
||||
@@ -92,7 +93,7 @@ const currentStatus = async (
|
||||
threadRef: ScopedThreadRef,
|
||||
visible: boolean,
|
||||
): Promise<PreviewAutomationStatus> => {
|
||||
const state = readThreadPreviewState(threadRef);
|
||||
const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, threadRef);
|
||||
const tabId = state.snapshot?.tabId ?? null;
|
||||
if (tabId && previewBridge && state.desktopOverlay) {
|
||||
const status = await previewBridge.automation.status(tabId);
|
||||
@@ -175,7 +176,10 @@ export function PreviewAutomationOwner(props: {
|
||||
error.name = "PreviewAutomationUnavailableError";
|
||||
throw error;
|
||||
}
|
||||
const state = readThreadPreviewState(threadRef);
|
||||
const state = selectThreadPreviewState(
|
||||
usePreviewStateStore.getState().byThreadKey,
|
||||
threadRef,
|
||||
);
|
||||
const tabId = request.tabId ?? state.snapshot?.tabId ?? null;
|
||||
switch (request.operation) {
|
||||
case "status":
|
||||
@@ -196,7 +200,7 @@ export function PreviewAutomationOwner(props: {
|
||||
throw squashAtomCommandFailure(result);
|
||||
}
|
||||
const snapshot = result.value;
|
||||
applyPreviewServerSnapshot(threadRef, snapshot);
|
||||
usePreviewStateStore.getState().applyServerSnapshot(threadRef, snapshot);
|
||||
activeTabId = snapshot.tabId;
|
||||
} else if (input.url && previewBridge) {
|
||||
await previewBridge.navigate(activeTabId, input.url);
|
||||
@@ -263,11 +267,11 @@ export function PreviewAutomationOwner(props: {
|
||||
);
|
||||
case "recordingStart": {
|
||||
if (!tabId) throw new Error("Preview tab is not initialized.");
|
||||
const startedAt = await startBrowserRecording(tabId);
|
||||
await startBrowserRecording(tabId);
|
||||
return {
|
||||
tabId,
|
||||
recording: true,
|
||||
startedAt,
|
||||
startedAt: useBrowserRecordingStore.getState().startedAt,
|
||||
};
|
||||
}
|
||||
case "recordingStop": {
|
||||
@@ -318,7 +322,10 @@ export function PreviewAutomationOwner(props: {
|
||||
if (!observation.shouldReport) return;
|
||||
|
||||
const ownerState = ownerStateRef.current;
|
||||
const state = readThreadPreviewState(ownerState.threadRef);
|
||||
const state = selectThreadPreviewState(
|
||||
usePreviewStateStore.getState().byThreadKey,
|
||||
ownerState.threadRef,
|
||||
);
|
||||
void reportAutomationOwner({
|
||||
environmentId: ownerState.threadRef.environmentId,
|
||||
input: {
|
||||
@@ -335,7 +342,10 @@ export function PreviewAutomationOwner(props: {
|
||||
|
||||
useEffect(() => {
|
||||
const report = () => {
|
||||
const state = readThreadPreviewState(threadRef);
|
||||
const state = selectThreadPreviewState(
|
||||
usePreviewStateStore.getState().byThreadKey,
|
||||
threadRef,
|
||||
);
|
||||
void reportAutomationOwner({
|
||||
environmentId: threadRef.environmentId,
|
||||
input: {
|
||||
@@ -351,8 +361,9 @@ export function PreviewAutomationOwner(props: {
|
||||
};
|
||||
report();
|
||||
window.addEventListener("focus", report);
|
||||
const unsubscribe = subscribeThreadPreviewState(threadRef, (state, previous) => {
|
||||
if (state.snapshot?.tabId !== previous.snapshot?.tabId) {
|
||||
const unsubscribe = usePreviewStateStore.subscribe((state, previous) => {
|
||||
const key = scopedThreadKey(threadRef);
|
||||
if (state.byThreadKey[key]?.snapshot?.tabId !== previous.byThreadKey[key]?.snapshot?.tabId) {
|
||||
report();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useComposerDraftStore } from "~/composerDraftStore";
|
||||
import { previewAnnotationScreenshotFile } from "~/lib/previewAnnotation";
|
||||
import { ensureLocalApi } from "~/localApi";
|
||||
import { rememberPreviewUrl, useThreadPreviewState } from "~/previewStateStore";
|
||||
import { selectThreadPreviewState, usePreviewStateStore } from "~/previewStateStore";
|
||||
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
|
||||
import { useEnvironment, useEnvironmentHttpBaseUrl } from "~/state/environments";
|
||||
import { previewEnvironment } from "~/state/preview";
|
||||
@@ -31,7 +31,7 @@ import { AgentBrowserCursor } from "./AgentBrowserCursor";
|
||||
import {
|
||||
startBrowserRecording,
|
||||
stopBrowserRecording,
|
||||
useActiveBrowserRecordingTabId,
|
||||
useBrowserRecordingStore,
|
||||
} from "~/browser/browserRecording";
|
||||
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
|
||||
|
||||
@@ -51,10 +51,14 @@ const localApi = typeof window === "undefined" ? null : ensureLocalApi();
|
||||
export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls, visible }: Props) {
|
||||
const [focusUrlNonce, setFocusUrlNonce] = useState<number | undefined>(undefined);
|
||||
const [pickActive, setPickActive] = useState(false);
|
||||
const activeRecordingTabId = useActiveBrowserRecordingTabId();
|
||||
const activeRecordingTabId = useBrowserRecordingStore((state) => state.activeTabId);
|
||||
const pickActiveRef = useRef(false);
|
||||
const isMountedRef = useRef(true);
|
||||
const previewState = useThreadPreviewState(threadRef);
|
||||
const previewState = usePreviewStateStore((state) =>
|
||||
selectThreadPreviewState(state.byThreadKey, threadRef),
|
||||
);
|
||||
const applyServerSnapshot = usePreviewStateStore((state) => state.applyServerSnapshot);
|
||||
const rememberUrl = usePreviewStateStore((state) => state.rememberUrl);
|
||||
const addPreviewAnnotation = useComposerDraftStore((store) => store.addPreviewAnnotation);
|
||||
const addImage = useComposerDraftStore((store) => store.addImage);
|
||||
const environment = useEnvironment(threadRef.environmentId);
|
||||
@@ -100,19 +104,21 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
// Drive the webview imperatively; `usePreviewBridge` mirrors the
|
||||
// resolved URL back to the server so other clients stay in sync.
|
||||
await previewBridge.navigate(tabId, resolvedUrl);
|
||||
rememberPreviewUrl(threadRef, resolvedUrl);
|
||||
rememberUrl(threadRef, resolvedUrl);
|
||||
} else {
|
||||
await openPreviewSession({
|
||||
openPreview: open,
|
||||
threadRef,
|
||||
url: resolvedUrl,
|
||||
applyServerSnapshot,
|
||||
rememberUrl,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Server-side `failed` event renders the unreachable view.
|
||||
}
|
||||
},
|
||||
[open, tabId, threadRef],
|
||||
[applyServerSnapshot, open, rememberUrl, tabId, threadRef],
|
||||
);
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
|
||||
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user