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
8 changes: 8 additions & 0 deletions frontend/src/lib/pages/MigrationAssistant.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import Activity from '@lucide/svelte/icons/activity';
import DialogFooter from '../dialogs/DialogFooter.svelte';
import { t } from '../stores/i18n.svelte.js';
import { invalidateWorkspaceConfiguration } from '../stores/referenceDataInvalidation.js';

let {
configurationSet = null,
Expand Down Expand Up @@ -321,6 +322,13 @@

migrationSuccess = true;

// The migration reassigned the affected workspaces inside its own
// transaction. Its plural endpoint only clears screen configs, so drop
// each workspace's catalogs, status options, and priorities explicitly.
for (const affectedWorkspaceId of migrationAnalysis?.affected_workspaces ?? []) {
invalidateWorkspaceConfiguration(affectedWorkspaceId);
}

// Close the assistant after a brief delay
setTimeout(() => {
closeAssistant();
Expand Down
27 changes: 27 additions & 0 deletions frontend/src/lib/stores/referenceDataInvalidation.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import { workspaceDataStore } from './workspaceDataStore.svelte.js';
* - `store`: a `workspaceDataStore` field,
* - `editor`: a `collectionEditorOptions` family,
* - `screenConfigs`: cached effective configurations,
* - `configurationChanged`: reload the assigned workspace through the store's
* reset/initialization lifecycle and reset the editor caches,
* - `fullRefresh`: everything (used for cross-cutting changes).
*
* Matching is deliberately coarse: re-fetching an unchanged family is cheap and
Expand Down Expand Up @@ -39,6 +41,10 @@ const REFERENCE_ENDPOINTS = [
{ match: /\/(?:time\/projects)(?:\/|$)/, store: 'projects', editor: 'projects' },
{ match: /\/(?:labels)(?:\/|$)/, store: 'labels' },
{ match: /\/(?:configuration-sets|screens|workflows)(?:\/|$)/, screenConfigs: true },
// Workspace-scoped assignment (WI-1359): PUT /workspaces/:id/configuration-set.
// The singular endpoint reassigns the workspace, so reload it through the
// normal lifecycle and reset the editor caches.
{ match: /\/configuration-set(?:\/|$)/, configurationChanged: true },
// Object translations change display names across several directories.
{ match: /\/(?:object-translations)(?:\/|$)/, fullRefresh: true },
{ match: /^\/workspaces\/\d+$/, store: 'workspace' },
Expand Down Expand Up @@ -85,11 +91,32 @@ export function applyReferenceInvalidation(
else editorOptions.invalidate(workspaceId, rule.editor);
}
if (rule.screenConfigs) store.invalidateScreenConfigs?.();
if (rule.configurationChanged && workspaceId != null) {
invalidateWorkspaceConfiguration(workspaceId, { store, editorOptions });
}
}

return true;
}

/**
* Apply an assigned-configuration change for one workspace. The migration path
* reassigns the workspace inside its own POST, whose plural endpoint only clears
* screen configs, so the caller names the affected workspaces explicitly. This
* is also the rule the direct assignment endpoint matches.
*/
export function invalidateWorkspaceConfiguration(
workspaceId,
{ store = workspaceDataStore, editorOptions = collectionEditorOptions } = {}
) {
if (workspaceId == null) return false;
// Reset the editor caches, then reload the active workspace through the
// store's reset/initialization lifecycle, which rejects superseded reads.
editorOptions.reset?.();
void store.reloadForConfigurationChange?.(workspaceId);
return true;
}

/** Subscribe the app shell to successful mutations. Returns an unsubscribe. */
export function registerReferenceDataInvalidation() {
if (typeof window === 'undefined') return () => {};
Expand Down
23 changes: 23 additions & 0 deletions frontend/src/lib/stores/workspaceDataStore.svelte.js
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,29 @@ class WorkspaceDataStore {
this.#screenConfigPromises.clear();
}

/**
* Apply an assigned-configuration change for one workspace. Drops cached
* effective configurations and, when the workspace is active, reloads it
* through the normal reset/initialization lifecycle. The reset advances the
* generation, so a bootstrap read that started before the change cannot
* install its stale catalogs afterwards. A configuration change is rare, so
* the extra reads are preferable to a second invalidation counter.
*/
async reloadForConfigurationChange(workspaceId) {
const id = Number(workspaceId);
if (!Number.isInteger(id) || id <= 0) return;
if (this.workspaceId !== id) {
// Not active: drop the cached effective configurations; the next
// activation bootstraps fresh through initialize().
this.invalidateScreenConfigs();
return;
}
// Active: reset and reload through the normal lifecycle so the generation
// advances and a bootstrap read from before the change is discarded.
this.reset();
await this.initialize(id);
}

#storeScreenConfig(key, config) {
this.screenConfigs = { ...this.screenConfigs, [key]: config };
this.#touchScreenConfig(key);
Expand Down
36 changes: 36 additions & 0 deletions internal/aitools/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,17 @@ type Env struct {
PageApplicationService *services.PageApplicationService
// PageDiagramService owns immutable Page-diagram attachment mutations.
PageDiagramService *services.PageDiagramService
// ItemApplication is the shared, fully wired item mutation pipeline (create
// and update). Tools must route item writes through it so agent writes get
// the same mention processing, cache invalidation, and created/updated
// events as the HTTP surfaces. Nil-safe: a local pipeline without the
// server's emitters is constructed on demand.
ItemApplication *services.ItemApplicationService
// TimeWorklogService is the shared worklog validation and persistence
// boundary. log_time routes through it so the description policy and
// warnings match the HTTP surfaces. Nil-safe: a local service is
// constructed on demand.
TimeWorklogService *services.TimeWorklogService
// ActionService is the optional cache-invalidation hook for tools that
// create or mutate actions. Nil-safe: tools must check before calling
// InvalidateWorkspaceCache so they degrade to "next periodic refresh"
Expand Down Expand Up @@ -127,6 +138,31 @@ func (e *Env) audit(actionType, resourceType string, resourceID int, resourceNam
}
}

// itemApplication returns the configured item mutation pipeline, or a local
// one when the embedder did not supply the server's shared instance. The
// fallback keeps tools working without the process-wide emitters, matching the
// pre-injection behavior.
func (e *Env) itemApplication() *services.ItemApplicationService {
if e.ItemApplication != nil {
return e.ItemApplication
}
return services.NewItemApplicationService(
e.DB,
e.PermService,
services.NewItemCreationService(e.DB, e.PermService),
services.NewItemUpdateApplicationService(e.DB, e.PermService),
services.NewItemDeletionApplicationService(e.DB, e.PermService),
)
}

// timeWorklogService returns the configured worklog service, or a local one.
func (e *Env) timeWorklogService() *services.TimeWorklogService {
if e.TimeWorklogService != nil {
return e.TimeWorklogService
}
return services.NewTimeWorklogService(e.DB)
}

// HasWorkspaceAccess reports whether the caller can touch the given workspace.
func (e *Env) HasWorkspaceAccess(workspaceID int) bool {
for _, id := range e.AccessibleWorkspaceIDs {
Expand Down
64 changes: 31 additions & 33 deletions internal/aitools/items.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ func init() {
Risk: RiskMedium,
Description: "Create a new work item in a workspace. Optionally set custom fields with custom_field_values, keyed by numeric field ID from list_custom_fields.",
Scopes: []string{auth.ScopeItemsWrite},
Run: func(_ context.Context, env *Env, args createItemArgs) (any, error) {
Run: func(ctx context.Context, env *Env, args createItemArgs) (any, error) {
if strings.TrimSpace(args.Title) == "" {
return map[string]string{"error": "title is required"}, nil
}
Expand Down Expand Up @@ -344,33 +344,33 @@ func init() {
if !validationResult.Valid {
return map[string]string{"error": validationResult.Error}, nil
}
customFieldValuesJSON, err := services.EncodeCustomFieldValuesJSON(env.DB, args.CustomFieldValues)
if err != nil {
if _, err := services.EncodeCustomFieldValuesJSON(env.DB, args.CustomFieldValues); err != nil {
return map[string]string{"error": err.Error()}, nil //nolint:nilerr // surface as a tool error in JSON, not as a protocol error
}
itemID, err := services.CreateItem(env.DB, services.ItemCreationParams{
WorkspaceID: args.WorkspaceID,
Title: title,
Description: desc,
StatusID: args.StatusID,
PriorityID: args.PriorityID,
AssigneeID: args.AssigneeID,
ParentID: args.ParentID,
ItemTypeID: args.ItemTypeID,
CreatorID: &env.UserID,
ValidatingUserID: env.UserID,
CustomFieldValuesJSON: customFieldValuesJSON,
PermService: env.PermService,
EventMetadata: env.eventMetadata(),
// Route through the shared application service so the canonical created
// event and downstream effects fire exactly once, as they do for the
// HTTP surfaces.
created, err := env.itemApplication().Create(ctx, services.AuditActor{
UserID: env.UserID, Username: env.Username,
}, services.ItemCreateInput{
WorkspaceID: args.WorkspaceID,
Title: title,
Description: desc,
StatusID: args.StatusID,
PriorityID: args.PriorityID,
AssigneeID: args.AssigneeID,
ParentID: args.ParentID,
ItemTypeID: args.ItemTypeID,
CustomFieldValues: args.CustomFieldValues,
EventMetadata: env.eventMetadata(),
})
if err != nil {
if errors.Is(err, services.ErrItemForbidden) {
return map[string]string{"error": "permission denied"}, nil
}
return map[string]string{"error": fmt.Sprintf("create failed: %s", err.Error())}, nil //nolint:nilerr // surface as a tool error in JSON, not as a protocol error
}
env.AuditWrite(logger.ResourceItem, int(itemID), "create_item", title)
created, err := services.NewItemCRUDService(env.DB).GetByID(int(itemID))
if err != nil {
return map[string]any{"id": itemID}, nil //nolint:nilerr // surface as a tool error in JSON, not as a protocol error
}
env.AuditWrite(logger.ResourceItem, created.ID, "create_item", created.Title)
return itemToSummary(created), nil
},
})
Expand All @@ -385,7 +385,7 @@ func init() {
Risk: RiskMedium,
Description: "Update fields on an existing work item. Identifies the item by numeric ID or key. Use transition_item to change status (workflow + condition rules apply).",
Scopes: []string{auth.ScopeItemsWrite},
Run: func(_ context.Context, env *Env, args updateItemArgs) (any, error) {
Run: func(ctx context.Context, env *Env, args updateItemArgs) (any, error) {
itemID, err := resolveItemID(env.DB, args.ItemID, args.ItemKey)
if err != nil {
return map[string]string{"error": err.Error()}, nil //nolint:nilerr // surface as a tool error in JSON, not as a protocol error
Expand All @@ -412,20 +412,18 @@ func init() {
if len(updateData) == 0 {
return map[string]string{"error": "no fields to update"}, nil
}
result, err := services.NewItemUpdateService(env.DB).
WithPermissionService(env.PermService).
UpdateItem(services.UpdateItemRequest{
ItemID: itemID,
UpdateData: updateData,
UserID: env.UserID,
EventMetadata: env.eventMetadata(),
})
result, err := env.itemApplication().UpdateFieldsWithMetadata(ctx, services.AuditActor{
UserID: env.UserID, Username: env.Username,
}, itemID, updateData, env.eventMetadata())
if err != nil {
if errors.Is(err, services.ErrItemForbidden) {
return map[string]string{"error": "permission denied"}, nil
}
return map[string]string{"error": fmt.Sprintf("update failed: %s", err.Error())}, nil //nolint:nilerr // surface as a tool error in JSON, not as a protocol error
}
env.AuditWrite(logger.ResourceItem, itemID, "update_item", result.Item.Title)
env.AuditWrite(logger.ResourceItem, itemID, "update_item", result.Title)
out := map[string]any{
"item": itemToSummary(result.Item),
"item": itemToSummary(result),
"changed_fields": changed,
}
return out, nil
Expand Down
56 changes: 41 additions & 15 deletions internal/aitools/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ type logTimeOut struct {
EndTimeLocal string `json:"end_time_local"`
StartAt string `json:"start_at"`
EndAt string `json:"end_at"`
// Warnings lists policy adjustments applied to the description, matching
// the HTTP worklog responses so a caller learns its text was shortened.
Warnings []string `json:"warnings,omitempty"`
}

// ----------------------------------------------------------------------------
Expand Down Expand Up @@ -298,32 +301,38 @@ func init() {
if toolErr != nil {
return toolErr, nil
}
id, err := repository.NewTimeWorklogRepository(env.DB).Create(repository.NewWorklog{
// Route through the shared worklog service so the description policy and
// warnings match the HTTP surfaces. PreserveStored keeps the interval
// already parsed above instead of re-deriving it.
result, err := env.timeWorklogService().Create(env.UserID, services.WorklogMutationInput{
ProjectID: args.ProjectID,
UserID: env.UserID,
ItemID: itemID,
Description: args.Description,
DateUnix: services.WorklogDateUnix(date),
StartTimeUnix: startUnix,
EndTimeUnix: endUnix,
Date: args.Date,
Timezone: resolvedTimezone,
UserTimezone: env.Timezone,
DurationMinutes: durationMins,
StoredStartUnix: startUnix,
StoredEndUnix: endUnix,
PreserveStored: true,
})
if err != nil {
return nil, err
return worklogServiceError(err)
}
env.AuditWrite(resourceTimeWorklog, int(id), "log_time", args.Description)
env.AuditWrite(resourceTimeWorklog, result.Worklog.ID, "log_time", result.Worklog.Description)
return logTimeOut{
ID: id,
ID: int64(result.Worklog.ID),
ProjectID: args.ProjectID,
ProjectName: project.Name,
Date: args.Date,
DurationMinutes: durationMins,
Description: args.Description,
Timezone: resolvedTimezone,
StartTimeLocal: time.Unix(startUnix, 0).In(location).Format("15:04"),
EndTimeLocal: time.Unix(endUnix, 0).In(location).Format("15:04"),
StartAt: time.Unix(startUnix, 0).UTC().Format(time.RFC3339),
EndAt: time.Unix(endUnix, 0).UTC().Format(time.RFC3339),
DurationMinutes: result.DurationMinutes,
Description: result.Worklog.Description,
Timezone: result.Timezone,
StartTimeLocal: time.Unix(result.StartTimeUnix, 0).In(result.Location).Format("15:04"),
EndTimeLocal: time.Unix(result.EndTimeUnix, 0).In(result.Location).Format("15:04"),
StartAt: time.Unix(result.StartTimeUnix, 0).UTC().Format(time.RFC3339),
EndAt: time.Unix(result.EndTimeUnix, 0).UTC().Format(time.RFC3339),
Warnings: result.Warnings,
}, nil
},
})
Expand Down Expand Up @@ -390,6 +399,23 @@ func init() {
})
}

// worklogServiceError maps a TimeWorklogService error to a tool response.
// Known input errors are reported in the payload; anything else is an
// unexpected storage failure and is returned as a Go error so MCP marks the
// call failed instead of reporting success.
func worklogServiceError(err error) (map[string]string, error) {
switch {
case errors.Is(err, services.ErrWorklogProjectNotFound):
return map[string]string{"error": "project not found"}, nil
case errors.Is(err, services.ErrWorklogProjectInactive):
return map[string]string{"error": "project is not active"}, nil
case errors.Is(err, services.ErrWorklogInvalidInput):
return map[string]string{"error": err.Error()}, nil
default:
return nil, err
}
}

// resolveOptionalItemRef resolves the optional work-item reference time tools
// accept (numeric item_id or item_key like PROJ-42). Returns (nil, nil) when
// neither is provided. Resolution failures and items outside the caller's
Expand Down
24 changes: 19 additions & 5 deletions internal/handlers/ai.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,17 @@ type AIHandler struct {
actionService *services.ActionService
pageApplicationService *services.PageApplicationService
pageDiagramService *services.PageDiagramService
conversations *repository.AgentConversationRepository
agentBindings *repository.WorkspaceAgentBindingRepository
commentService *services.CommentService
approvalService *services.ApprovalService
chatLLMs chatLLMResolver
// itemApplication is the shared item mutation pipeline used by mutating
// chat tools so agent writes match the HTTP surfaces. Installed after
// construction because server wiring builds it late.
itemApplication *services.ItemApplicationService
// timeWorklogService is the shared worklog boundary used by log_time.
timeWorklogService *services.TimeWorklogService
conversations *repository.AgentConversationRepository
agentBindings *repository.WorkspaceAgentBindingRepository
commentService *services.CommentService
approvalService *services.ApprovalService
chatLLMs chatLLMResolver
// llmUsage meters each chat turn's token/cost against its own agent_runs
// row, so the model's identity and the turn's spend outlive the response.
llmUsage *repository.LLMUsageRepository
Expand Down Expand Up @@ -85,6 +91,14 @@ func (h *AIHandler) SetConversationDependencies(comments *services.CommentServic
h.approvalService = approvals
}

// SetMutationServices installs the shared item and worklog pipelines used by
// mutating chat tools. Server wiring builds them after the handler, so this is
// called once those services exist.
func (h *AIHandler) SetMutationServices(itemApplication *services.ItemApplicationService, worklogs *services.TimeWorklogService) {
h.itemApplication = itemApplication
h.timeWorklogService = worklogs
}

// PlanMyDayResponse is the response for the Plan My Day endpoint.
type PlanMyDayResponse struct {
Activities []PlannedActivity `json:"activities"`
Expand Down
2 changes: 2 additions & 0 deletions internal/handlers/ai_dependencies.go
Original file line number Diff line number Diff line change
Expand Up @@ -900,6 +900,8 @@ func (h *AIHandler) Chat(w http.ResponseWriter, r *http.Request) {
CommentService: h.commentService,
ApprovalService: h.approvalService,
ActionService: h.actionService,
ItemApplication: h.itemApplication,
TimeWorklogService: h.timeWorklogService,
PageApplicationService: h.pageApplicationService,
PageDiagramService: h.pageDiagramService,
}
Expand Down
Loading
Loading