Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions packages/api/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import * as HttpServerResponse from "@effect/platform/HttpServerResponse"
import * as HttpServerError from "@effect/platform/HttpServerError"
import * as ParseResult from "effect/ParseResult"
import * as Schema from "effect/Schema"
import { renderError, type AppError } from "@effect-template/lib/usecases/errors"

import { ApiAuthRequiredError, ApiBadRequestError, ApiConflictError, ApiInternalError, ApiNotFoundError, describeUnknown } from "./api/errors.js"
import {
Expand Down Expand Up @@ -92,6 +93,32 @@ type ApiError =
| HttpServerError.RequestError
| PlatformError

const appErrorTags = new Set<string>([
"FileExistsError",
"CloneFailedError",
"AgentFailedError",
"DockerAccessError",
"DockerCommandError",
"ConfigNotFoundError",
"ConfigDecodeError",
"ScrapArchiveInvalidError",
"ScrapArchiveNotFoundError",
"ScrapTargetDirUnsupportedError",
"ScrapWipeRefusedError",
"InputCancelledError",
"InputReadError",
"PortProbeError",
"AuthError",
"CommandFailedError"
])

const isAppError = (error: unknown): error is AppError =>
typeof error === "object" &&
error !== null &&
"_tag" in error &&
typeof error["_tag"] === "string" &&
appErrorTags.has(error["_tag"])

const jsonResponse = (data: unknown, status: number) =>
Effect.map(HttpServerResponse.json(data), (response) => HttpServerResponse.setStatus(response, status))

Expand Down Expand Up @@ -154,6 +181,10 @@ const errorResponse = (error: ApiError | unknown) => {
return jsonResponse({ error: { type: error._tag, message: error.message } }, 500)
}

if (isAppError(error)) {
return jsonResponse({ error: { type: error._tag, message: renderError(error) } }, 400)
}

return jsonResponse(
{
error: {
Expand Down
11 changes: 9 additions & 2 deletions packages/api/src/services/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
downAllDockerGitProjects,
listProjectItems,
readProjectConfig,
renderError,
runDockerComposeUpWithPortCheck
} from "@effect-template/lib"
import * as FileSystem from "@effect/platform/FileSystem"
Expand All @@ -19,7 +20,7 @@ import type { ProjectItem } from "@effect-template/lib/usecases/projects"
import { Effect, Either } from "effect"

import type { CreateProjectRequest, ProjectDetails, ProjectStatus, ProjectSummary } from "../api/contracts.js"
import { ApiInternalError, ApiNotFoundError, ApiBadRequestError } from "../api/errors.js"
import { ApiConflictError, ApiInternalError, ApiNotFoundError, ApiBadRequestError } from "../api/errors.js"
import { ensureGithubAuthForCreate } from "./auth.js"
import { emitProjectEvent } from "./events.js"

Expand Down Expand Up @@ -308,7 +309,13 @@ export const createProjectFromRequest = (
})
)

yield* _(createProject(command))
yield* _(
createProject(command).pipe(
Effect.catchTag("DockerIdentityConflictError", (error) =>
Effect.fail(new ApiConflictError({ message: renderError(error) }))
)
)
)

const project = yield* _(
resolveCreatedProject(
Expand Down
49 changes: 48 additions & 1 deletion packages/api/tests/projects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { NodeContext } from "@effect/platform-node"
import { describe, expect, it } from "@effect/vitest"
import { Effect } from "effect"

import { seedAuthorizedKeysForCreate } from "../src/services/projects.js"
import { ApiConflictError } from "../src/api/errors.js"
import { createProjectFromRequest, seedAuthorizedKeysForCreate } from "../src/services/projects.js"

const withTempDir = <A, E, R>(
use: (tempDir: string) => Effect.Effect<A, E, R>
Expand Down Expand Up @@ -86,4 +87,50 @@ describe("projects service", () => {
expect(projectContents).toBe(`${hostKey}\n`)
})
).pipe(Effect.provide(NodeContext.layer)))

it.effect("maps duplicate docker identities to API conflict for create", () =>
withTempDir((root) =>
Effect.gen(function*(_) {
const path = yield* _(Path.Path)
const projectsRoot = path.join(root, ".docker-git")

yield* _(
withProjectsRoot(
projectsRoot,
withWorkingDirectory(
root,
createProjectFromRequest({
repoUrl: "https://git.example.test/test-owner-a/openclaw_autodeployer.git",
repoRef: "main",
sshPort: "2237",
skipGithubAuth: true,
up: false
})
)
)
)

const error = yield* _(
withProjectsRoot(
projectsRoot,
withWorkingDirectory(
root,
createProjectFromRequest({
repoUrl: "https://git.example.test/test-owner-b/openclaw_autodeployer.git",
repoRef: "main",
sshPort: "2238",
skipGithubAuth: true,
up: false
}).pipe(Effect.flip)
)
)
)

expect(error).toBeInstanceOf(ApiConflictError)
if (error instanceof ApiConflictError) {
expect(error.message).toContain("Docker identities are already owned")
expect(error.message).toContain("dg-openclaw_autodeployer")
}
})
).pipe(Effect.provide(NodeContext.layer)))
})
2 changes: 1 addition & 1 deletion packages/app/src/docker-git/cli/usage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ Options:
--mcp-playwright | --no-mcp-playwright Enable Playwright MCP + Chromium sidecar (default: --no-mcp-playwright)
--auto[=claude|codex] Auto-execute an agent; without value picks by auth, random if both are available
--active apply-all: apply only to currently running containers (skip stopped ones)
--force Overwrite existing files, remove conflicting containers, and wipe compose volumes
--force Overwrite existing files, replace conflicting docker-git projects/containers, and wipe compose volumes
--force-env Reset project env defaults only (keep workspace volume/data)
-h, --help Show this help

Expand Down
176 changes: 170 additions & 6 deletions packages/app/src/docker-git/open-project.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { ProjectItem } from "@lib/usecases/projects"
import { defaultTemplateConfig } from "@lib/core/domain"
import { runDockerInspectContainerRuntimeInfo, type DockerContainerRuntimeInfo } from "@lib/shell/docker"
import { buildSshCommand, connectProjectSsh, probeProjectSshReady, type ProjectItem } from "@lib/usecases/projects"
import { Effect, pipe } from "effect"

import type { OpenCommand } from "@lib/core/domain"
Expand All @@ -12,9 +14,16 @@ import { resolveApiProjectItem } from "./project-item.js"

type OpenResolvedProjectSshDeps<E, R> = {
readonly log: (message: string) => Effect.Effect<void, E, R>
readonly resolvePreferredItem: (item: ProjectItem) => Effect.Effect<ProjectItem | null, E, R>
readonly probeReady: (item: ProjectItem) => Effect.Effect<boolean, E, R>
readonly connect: (item: ProjectItem) => Effect.Effect<void, E, R>
readonly connectWithUp: (item: ProjectItem) => Effect.Effect<void, E, R>
}

type ResolveOpenProjectDeps<E, R> = {
readonly inspectRuntime: (containerName: string) => Effect.Effect<DockerContainerRuntimeInfo | null, E, R>
}

const normalizeText = (value: string): string => value.trim().toLowerCase()

const normalizePath = (value: string): string => {
Expand Down Expand Up @@ -96,6 +105,36 @@ const preferSingleRunning = (
return running.length === 1 ? (running[0] ?? null) : null
}

const exactRuntimeMatches = (
selector: string,
projects: ReadonlyArray<ApiProjectDetails>
): ReadonlyArray<ApiProjectDetails> => {
const normalizedSelector = normalizeText(selector)
if (normalizedSelector.length === 0) {
return []
}
return projects.filter((project) =>
normalizedSelector === normalizeText(project.containerName) ||
normalizedSelector === normalizeText(project.serviceName)
)
}

const resolvesExactRuntimeSelector = (
selector: string,
projects: ReadonlyArray<ApiProjectDetails>
): ApiProjectDetails | null => {
if (projects.length === 0) {
return null
}

const matches = exactRuntimeMatches(selector, projects)
if (matches.length !== projects.length) {
return null
}

return preferSingleRunning(matches) ?? matches[0] ?? null
}

const resolveUniqueProject = (
matches: ReadonlyArray<ApiProjectDetails>,
notFoundMessage: string,
Expand Down Expand Up @@ -162,6 +201,11 @@ export const selectOpenProject = (
)

if (directMatches.length > 0) {
const exactRuntimeMatch = resolvesExactRuntimeSelector(trimmed, directMatches)
if (exactRuntimeMatch !== null) {
return Effect.succeed(exactRuntimeMatch)
}

return resolveUniqueProject(
directMatches,
`No docker-git project matched '${trimmed}'.`,
Expand All @@ -177,6 +221,45 @@ export const selectOpenProject = (
)
}

const uniqueContainerNames = (projects: ReadonlyArray<ApiProjectDetails>): ReadonlyArray<string> =>
Array.from(new Set(projects.map((project) => project.containerName)))

export const resolveRuntimeOwnedProject = <E, R>(
projects: ReadonlyArray<ApiProjectDetails>,
selector: string | undefined,
deps: ResolveOpenProjectDeps<E, R>
): Effect.Effect<ApiProjectDetails | null, E, R> =>
Effect.gen(function*(_) {
const trimmed = selector?.trim() ?? ""
const matches = exactRuntimeMatches(trimmed, projects)
if (matches.length === 0) {
return null
}

for (const containerName of uniqueContainerNames(matches)) {
const runtime = yield* _(deps.inspectRuntime(containerName))
const ownerDir = runtime?.projectWorkingDir
if (ownerDir === undefined) {
continue
}
const owner = matches.find((project) => normalizePath(project.projectDir) === normalizePath(ownerDir))
if (owner !== undefined) {
return owner
}
}

return null
})

export const resolveOpenProjectEffect = <E, R>(
projects: ReadonlyArray<ApiProjectDetails>,
selector: string | undefined,
deps: ResolveOpenProjectDeps<E, R>
): Effect.Effect<ApiProjectDetails, ProjectResolutionError | E, R> =>
resolveRuntimeOwnedProject(projects, selector, deps).pipe(
Effect.flatMap((ownedProject) => ownedProject === null ? selectOpenProject(projects, selector) : Effect.succeed(ownedProject))
)

const listProjectDetails = () =>
Effect.gen(function*(_) {
const summaries = yield* _(listProjects())
Expand All @@ -190,20 +273,96 @@ const listProjectDetails = () =>
return details.filter((project): project is ApiProjectDetails => project !== null)
})

const withProjectItemIpAddress = (
item: ProjectItem,
ipAddress: string
): ProjectItem => ({
...item,
ipAddress,
sshCommand: buildSshCommand(
{
...defaultTemplateConfig,
containerName: item.containerName,
serviceName: item.serviceName,
sshUser: item.sshUser,
sshPort: item.sshPort,
repoUrl: item.repoUrl,
repoRef: item.repoRef,
targetDir: item.targetDir,
envGlobalPath: item.envGlobalPath,
envProjectPath: item.envProjectPath,
codexAuthPath: item.codexAuthPath,
codexSharedAuthPath: item.codexAuthPath,
codexHome: item.codexHome,
clonedOnHostname: item.clonedOnHostname
},
item.sshKeyPath,
ipAddress
)
})

const sameConnectionTarget = (left: ProjectItem, right: ProjectItem): boolean =>
left.ipAddress === right.ipAddress &&
left.sshPort === right.sshPort &&
left.sshKeyPath === right.sshKeyPath &&
left.sshUser === right.sshUser

const attemptDirectConnect = <E, R>(
item: ProjectItem,
deps: Pick<OpenResolvedProjectSshDeps<E, R>, "connect" | "log" | "probeReady">
): Effect.Effect<boolean, E, R> =>
deps.probeReady(item).pipe(
Effect.flatMap((ready) =>
ready
? pipe(
deps.log(`Opening SSH: ${item.sshCommand}`),
Effect.zipRight(deps.connect(item)),
Effect.as(true)
)
: Effect.succeed(false)
)
)

export const openResolvedProjectSshEffect = <E, R>(
item: ProjectItem,
deps: OpenResolvedProjectSshDeps<E, R>
) =>
pipe(
deps.log(`Opening SSH: ${item.sshCommand}`),
Effect.zipRight(deps.connectWithUp(item))
)
Effect.gen(function*(_) {
const preferredItem = yield* _(deps.resolvePreferredItem(item))
if (preferredItem !== null) {
const connected = yield* _(attemptDirectConnect(preferredItem, deps))
if (connected) {
return
}
}

const shouldRetryOriginal = preferredItem === null || !sameConnectionTarget(preferredItem, item)
if (shouldRetryOriginal) {
const connected = yield* _(attemptDirectConnect(item, deps))
if (connected) {
return
}
}

yield* _(deps.log(`Opening SSH: ${item.sshCommand}`))
yield* _(deps.connectWithUp(item))
})

export const openResolvedProjectSsh = (
item: ProjectItem
) =>
openResolvedProjectSshEffect(item, {
log: (message) => Effect.log(message),
resolvePreferredItem: (selected) =>
runDockerInspectContainerRuntimeInfo(process.cwd(), selected.containerName).pipe(
Effect.map((runtime) =>
runtime !== null && runtime.ipAddress.length > 0
? withProjectItemIpAddress(selected, runtime.ipAddress)
: null
)
),
probeReady: (selected) => probeProjectSshReady(selected),
connect: (selected) => connectProjectSsh(selected),
connectWithUp: (selected) => connectMenuProjectSshWithUp(selected)
})

Expand All @@ -212,7 +371,12 @@ export const openExistingProjectSsh = (
) =>
Effect.gen(function*(_) {
const projects = yield* _(listProjectDetails())
const project = yield* _(selectOpenProject(projects, command.projectDir ?? command.projectRef))
const selector = command.projectDir ?? command.projectRef
const project = yield* _(
resolveOpenProjectEffect(projects, selector, {
inspectRuntime: (containerName) => runDockerInspectContainerRuntimeInfo(process.cwd(), containerName)
})
)
const item = yield* _(resolveApiProjectItem(project))
yield* _(openResolvedProjectSsh(item))
})
Loading
Loading