This repository was archived by the owner on Oct 10, 2026. It is now read-only.
Repository navigation
feat: server utilities from dpcode #67
Closed
Closed
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
aa32c84
feat: add server utilities from dpcode
aaditagrawal 5fb0a44
fix: remove dpcode-specific discovery service, resolve CI errors
aaditagrawal 01bec4f
fix: resolve CI type errors for server-utils PR
aaditagrawal 75e2edd
fix: resolve remaining CI errors
aaditagrawal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| import { Schema } from "effect"; | ||
|
|
||
| /** | ||
| * GitCommandError - Git command execution failed. | ||
| */ | ||
| export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()("GitCommandError", { | ||
| operation: Schema.String, | ||
| command: Schema.String, | ||
| cwd: Schema.String, | ||
| detail: Schema.String, | ||
| cause: Schema.optional(Schema.Defect), | ||
| }) { | ||
| override get message(): string { | ||
| return `Git command failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * GitHubCliError - GitHub CLI execution or authentication failed. | ||
| */ | ||
| export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", { | ||
| operation: Schema.String, | ||
| detail: Schema.String, | ||
| cause: Schema.optional(Schema.Defect), | ||
| }) { | ||
| override get message(): string { | ||
| return `GitHub CLI failed in ${this.operation}: ${this.detail}`; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * TextGenerationError - Commit or PR text generation failed. | ||
| */ | ||
| export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()( | ||
| "TextGenerationError", | ||
| { | ||
| operation: Schema.String, | ||
| detail: Schema.String, | ||
| cause: Schema.optional(Schema.Defect), | ||
| }, | ||
| ) { | ||
| override get message(): string { | ||
| return `Text generation failed in ${this.operation}: ${this.detail}`; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * GitManagerError - Stacked Git workflow orchestration failed. | ||
| */ | ||
| export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()("GitManagerError", { | ||
| operation: Schema.String, | ||
| detail: Schema.String, | ||
| cause: Schema.optional(Schema.Defect), | ||
| }) { | ||
| override get message(): string { | ||
| return `Git manager failed in ${this.operation}: ${this.detail}`; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * GitManagerServiceError - Errors emitted by stacked Git workflow orchestration. | ||
| */ | ||
| export type GitManagerServiceError = | ||
| | GitManagerError | ||
| | GitCommandError | ||
| | GitHubCliError | ||
| | TextGenerationError; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| import { existsSync } from "node:fs"; | ||
| import { join } from "node:path"; | ||
|
|
||
| export function isGitRepository(cwd: string): boolean { | ||
| return existsSync(join(cwd, ".git")); | ||
| } | ||
96 changes: 96 additions & 0 deletions
96
apps/server/src/orchestration/projectMetadataProjection.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| import type { OrchestrationEvent } from "@t3tools/contracts"; | ||
| import { Effect, Option } from "effect"; | ||
|
|
||
| import type { ProjectionRepositoryError } from "../persistence/Errors.ts"; | ||
| import type { ProjectionProjectRepositoryShape } from "../persistence/Services/ProjectionProjects.ts"; | ||
| import type { ProjectionStateRepositoryShape } from "../persistence/Services/ProjectionState.ts"; | ||
|
|
||
| export type ProjectMetadataOrchestrationEvent = Extract< | ||
| OrchestrationEvent, | ||
| { type: "project.created" | "project.meta-updated" | "project.deleted" } | ||
| >; | ||
|
|
||
| export const PROJECT_METADATA_SNAPSHOT_PROJECTORS = [ | ||
| "projection.projects", | ||
| "projection.threads", | ||
| "projection.thread-messages", | ||
| "projection.thread-proposed-plans", | ||
| "projection.thread-activities", | ||
| "projection.thread-sessions", | ||
| "projection.checkpoints", | ||
| ] as const; | ||
|
|
||
| export const applyProjectMetadataProjection = (input: { | ||
| readonly event: ProjectMetadataOrchestrationEvent; | ||
| readonly projectionProjectRepository: ProjectionProjectRepositoryShape; | ||
| }): Effect.Effect<void, ProjectionRepositoryError> => | ||
| Effect.gen(function* () { | ||
| switch (input.event.type) { | ||
| case "project.created": | ||
| yield* input.projectionProjectRepository.upsert({ | ||
| projectId: input.event.payload.projectId, | ||
| title: input.event.payload.title, | ||
| workspaceRoot: input.event.payload.workspaceRoot, | ||
| defaultModelSelection: input.event.payload.defaultModelSelection, | ||
| scripts: input.event.payload.scripts, | ||
| createdAt: input.event.payload.createdAt, | ||
| updatedAt: input.event.payload.updatedAt, | ||
| deletedAt: null, | ||
| }); | ||
| break; | ||
|
|
||
| case "project.meta-updated": { | ||
| const existingRow = yield* input.projectionProjectRepository.getById({ | ||
| projectId: input.event.payload.projectId, | ||
| }); | ||
| if (Option.isSome(existingRow)) { | ||
| yield* input.projectionProjectRepository.upsert({ | ||
| ...existingRow.value, | ||
| ...(input.event.payload.title !== undefined | ||
| ? { title: input.event.payload.title } | ||
| : {}), | ||
| ...(input.event.payload.workspaceRoot !== undefined | ||
| ? { workspaceRoot: input.event.payload.workspaceRoot } | ||
| : {}), | ||
| ...(input.event.payload.defaultModelSelection !== undefined | ||
| ? { defaultModelSelection: input.event.payload.defaultModelSelection } | ||
| : {}), | ||
| ...(input.event.payload.scripts !== undefined | ||
| ? { scripts: input.event.payload.scripts } | ||
| : {}), | ||
| updatedAt: input.event.payload.updatedAt, | ||
| }); | ||
| } | ||
| break; | ||
| } | ||
|
|
||
| case "project.deleted": { | ||
| const existingRow = yield* input.projectionProjectRepository.getById({ | ||
| projectId: input.event.payload.projectId, | ||
| }); | ||
| if (Option.isSome(existingRow)) { | ||
| yield* input.projectionProjectRepository.upsert({ | ||
| ...existingRow.value, | ||
| deletedAt: input.event.payload.deletedAt, | ||
| updatedAt: input.event.payload.deletedAt, | ||
| }); | ||
| } | ||
| break; | ||
|
Comment on lines
+42
to
+78
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fail fast when update/delete arrives before the row exists. If 🤖 Prompt for AI Agents |
||
| } | ||
| } | ||
| }); | ||
|
|
||
| export const advanceProjectMetadataSnapshotState = (input: { | ||
| readonly event: ProjectMetadataOrchestrationEvent; | ||
| readonly projectionStateRepository: ProjectionStateRepositoryShape; | ||
| }): Effect.Effect<void, ProjectionRepositoryError> => | ||
| Effect.forEach( | ||
| PROJECT_METADATA_SNAPSHOT_PROJECTORS, | ||
| (projector) => | ||
| input.projectionStateRepository.upsert({ | ||
| projector, | ||
| lastAppliedSequence: input.event.sequence, | ||
| updatedAt: input.event.occurredAt, | ||
| }), | ||
| { concurrency: 1 }, | ||
| ).pipe(Effect.asVoid); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,182 @@ | ||
| import fs from "node:fs"; | ||
| import http from "node:http"; | ||
| import os from "node:os"; | ||
| import path from "node:path"; | ||
|
|
||
| import { afterEach, describe, expect, it } from "vitest"; | ||
| import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute"; | ||
|
|
||
| interface HttpResponse { | ||
| statusCode: number; | ||
| contentType: string | null; | ||
| body: string; | ||
| } | ||
|
|
||
| const tempDirs: string[] = []; | ||
|
|
||
| function makeTempDir(prefix: string): string { | ||
| const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); | ||
| tempDirs.push(dir); | ||
| return dir; | ||
| } | ||
|
|
||
| async function withRouteServer(run: (baseUrl: string) => Promise<void>): Promise<void> { | ||
| const server = http.createServer((req, res) => { | ||
| const url = new URL(req.url ?? "/", "http://127.0.0.1"); | ||
| if (tryHandleProjectFaviconRequest(url, res)) { | ||
| return; | ||
| } | ||
| res.writeHead(404, { "Content-Type": "text/plain" }); | ||
| res.end("Not Found"); | ||
| }); | ||
|
|
||
| await new Promise<void>((resolve, reject) => { | ||
| server.listen(0, "127.0.0.1", (error?: Error) => { | ||
| if (error) { | ||
| reject(error); | ||
| return; | ||
| } | ||
| resolve(); | ||
| }); | ||
| }); | ||
|
|
||
| const address = server.address(); | ||
| if (typeof address !== "object" || address === null) { | ||
| throw new Error("Expected server address to be an object"); | ||
| } | ||
| const baseUrl = `http://127.0.0.1:${address.port}`; | ||
|
|
||
| try { | ||
| await run(baseUrl); | ||
| } finally { | ||
| await new Promise<void>((resolve, reject) => { | ||
| server.close((error?: Error) => { | ||
| if (error) { | ||
| reject(error); | ||
| return; | ||
| } | ||
| resolve(); | ||
| }); | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| async function request(baseUrl: string, pathname: string): Promise<HttpResponse> { | ||
| const response = await fetch(`${baseUrl}${pathname}`); | ||
| return { | ||
| statusCode: response.status, | ||
| contentType: response.headers.get("content-type"), | ||
| body: await response.text(), | ||
| }; | ||
| } | ||
|
|
||
| describe("tryHandleProjectFaviconRequest", () => { | ||
| afterEach(() => { | ||
| for (const dir of tempDirs.splice(0, tempDirs.length)) { | ||
| fs.rmSync(dir, { recursive: true, force: true }); | ||
| } | ||
| }); | ||
|
|
||
| it("returns 400 when cwd is missing", async () => { | ||
| await withRouteServer(async (baseUrl) => { | ||
| const response = await request(baseUrl, "/api/project-favicon"); | ||
| expect(response.statusCode).toBe(400); | ||
| expect(response.body).toBe("Missing cwd parameter"); | ||
| }); | ||
| }); | ||
|
|
||
| it("serves a well-known favicon file from the project root", async () => { | ||
| const projectDir = makeTempDir("t3code-favicon-route-root-"); | ||
| fs.writeFileSync(path.join(projectDir, "favicon.svg"), "<svg>favicon</svg>", "utf8"); | ||
|
|
||
| await withRouteServer(async (baseUrl) => { | ||
| const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`; | ||
| const response = await request(baseUrl, pathname); | ||
| expect(response.statusCode).toBe(200); | ||
| expect(response.contentType).toContain("image/svg+xml"); | ||
| expect(response.body).toBe("<svg>favicon</svg>"); | ||
| }); | ||
| }); | ||
|
|
||
| it("resolves icon href from source files when no well-known favicon exists", async () => { | ||
| const projectDir = makeTempDir("t3code-favicon-route-source-"); | ||
| const iconPath = path.join(projectDir, "public", "brand", "logo.svg"); | ||
| fs.mkdirSync(path.dirname(iconPath), { recursive: true }); | ||
| fs.writeFileSync( | ||
| path.join(projectDir, "index.html"), | ||
| '<link rel="icon" href="/brand/logo.svg">', | ||
| ); | ||
| fs.writeFileSync(iconPath, "<svg>brand</svg>", "utf8"); | ||
|
|
||
| await withRouteServer(async (baseUrl) => { | ||
| const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`; | ||
| const response = await request(baseUrl, pathname); | ||
| expect(response.statusCode).toBe(200); | ||
| expect(response.contentType).toContain("image/svg+xml"); | ||
| expect(response.body).toBe("<svg>brand</svg>"); | ||
| }); | ||
| }); | ||
|
|
||
| it("resolves icon link when href appears before rel in HTML", async () => { | ||
| const projectDir = makeTempDir("t3code-favicon-route-html-order-"); | ||
| const iconPath = path.join(projectDir, "public", "brand", "logo.svg"); | ||
| fs.mkdirSync(path.dirname(iconPath), { recursive: true }); | ||
| fs.writeFileSync( | ||
| path.join(projectDir, "index.html"), | ||
| '<link href="/brand/logo.svg" rel="icon">', | ||
| ); | ||
| fs.writeFileSync(iconPath, "<svg>brand-html-order</svg>", "utf8"); | ||
|
|
||
| await withRouteServer(async (baseUrl) => { | ||
| const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`; | ||
| const response = await request(baseUrl, pathname); | ||
| expect(response.statusCode).toBe(200); | ||
| expect(response.contentType).toContain("image/svg+xml"); | ||
| expect(response.body).toBe("<svg>brand-html-order</svg>"); | ||
| }); | ||
| }); | ||
|
|
||
| it("resolves object-style icon metadata when href appears before rel", async () => { | ||
| const projectDir = makeTempDir("t3code-favicon-route-obj-order-"); | ||
| const iconPath = path.join(projectDir, "public", "brand", "obj.svg"); | ||
| fs.mkdirSync(path.dirname(iconPath), { recursive: true }); | ||
| fs.mkdirSync(path.join(projectDir, "src"), { recursive: true }); | ||
| fs.writeFileSync( | ||
| path.join(projectDir, "src", "root.tsx"), | ||
| 'const links = [{ href: "/brand/obj.svg", rel: "icon" }];', | ||
| "utf8", | ||
| ); | ||
| fs.writeFileSync(iconPath, "<svg>brand-obj-order</svg>", "utf8"); | ||
|
|
||
| await withRouteServer(async (baseUrl) => { | ||
| const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`; | ||
| const response = await request(baseUrl, pathname); | ||
| expect(response.statusCode).toBe(200); | ||
| expect(response.contentType).toContain("image/svg+xml"); | ||
| expect(response.body).toBe("<svg>brand-obj-order</svg>"); | ||
| }); | ||
| }); | ||
|
|
||
| it("serves a fallback favicon when no icon exists", async () => { | ||
| const projectDir = makeTempDir("t3code-favicon-route-fallback-"); | ||
|
|
||
| await withRouteServer(async (baseUrl) => { | ||
| const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`; | ||
| const response = await request(baseUrl, pathname); | ||
| expect(response.statusCode).toBe(200); | ||
| expect(response.contentType).toContain("image/svg+xml"); | ||
| expect(response.body).toContain('data-fallback="project-favicon"'); | ||
| }); | ||
| }); | ||
|
|
||
| it("returns 204 when fallback=none and no icon exists", async () => { | ||
| const projectDir = makeTempDir("t3code-favicon-route-no-fallback-"); | ||
|
|
||
| await withRouteServer(async (baseUrl) => { | ||
| const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}&fallback=none`; | ||
| const response = await request(baseUrl, pathname); | ||
| expect(response.statusCode).toBe(204); | ||
| expect(response.body).toBe(""); | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Harden repo detection to avoid false positives from arbitrary
.gitartifacts.The current predicate returns
truefor any existing.gitpath, even malformed files. Since this result gates git workflows, a malformed.gitcan incorrectly enable downstream git operations.🔧 Proposed hardening
🤖 Prompt for AI Agents