Skip to content

Make the clock per team end to end: server, live updates and UI - #643

Closed
morepriyam with Copilot wants to merge 5 commits into
mainfrom
copilot/make-clock-per-team-end-to-end
Closed

morepriyam with Copilot wants to merge 5 commits into
mainfrom
copilot/make-clock-per-team-end-to-end

Conversation

Copilot AI commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

The server keeps a clock per team but never enforced it. The UI showed one global shift, and live updates covered only the selected team. Several server paths read "the" open shift with findOne({ userId, endTime: null }). With shifts open in two teams that read was arbitrary. It caused stale tabs, a header timer showing another team's shift, timers nested under the wrong shift, and clock-outs that stopped other teams' timers.

This PR makes the clock per team in every layer.

Server: one open shift per (user, team)

  • Unique index. A partial unique index unique_open_shift_per_team on clockevents { userId, teamId } where endTime: null.
  • Startup cleanup. Runs before the index is created. Per (user, team) it keeps the newest open shift and ends each older one where the next began, so hours never overlap. The planner is the pure function in open-shift-dedupe.js. Each closed shift goes through closeShift, which closes its break and ticket timers and computes accumulatedTime. Its Agenda jobs are cancelled and each closure is logged.
  • Clock-in refusal. clock.start refuses with already-clocked-in while that team's shift is open, including when an insert race hits a duplicate key (11000). It no longer silently closes the open shift with zero hours. A shift open in another team doesn't block it.
  • Agenda cancel timing. cancelClockJobs and cancelClockJobsByName now wait for initAgenda. Without this, a cancel issued during the startup cleanup would hit an undefined _agenda.

Stop by session

  • clock.stop. It accepts { clockEventId }, and teamId alone still works. A clockEventId together with a teamId that doesn't match is refused. A call with neither is refused, not resolved to an arbitrary shift.
  • Per-shift timer stop. Clock-out stops only the ticket timers inside that shift (by clockEventId), not closeAllForUser. This covers both clock.stop and the auto clock-out's stopActiveClock.
  • findOpenShift(userId, teamId) returns null when there is no team. Without the guard, the driver's ignoreUndefined would drop teamId: undefined and match any team.

Team-aware reads

  • clock.myOpenShifts replaces clock.activeForUser and returns every open shift of the user.
  • requireActiveShift (ticket timers). It resolves the shift from the ticket's team, then the caller's teamId hint, then the only open shift. Otherwise it fails with shift-ambiguous.
  • Redmine's hasOpenShift now asks whether any shift is open, instead of returning one arbitrary shift.

Live updates

  • New publication. clock.liveOpenShifts publishes ClockEvents.find({ userId: this.userId, endTime: null }).
  • TeamContext.openShifts. Holds a teamId → shift map fetched from clock.myOpenShifts. A change in the publication triggers a refetch, and stale responses are dropped. activeClockEvent is now openShifts[selectedTeamId].
  • Team views. clock.liveForTeams stays for team views (Work, Huddle).

UI

  • Selected team's shift. The Clock page, header timer and Break button show and control the selected team's shift. useClockToggle stops by clockEventId.
  • OtherTeamShifts. Shows "Also on the clock in Team A" with a Switch button that selects the team's org first when needed. It renders in an aria-live region.
  • Refused clock-in. The reason is shown on the selected team's page, and the live map corrects the state.
  • TodayStatusCard for other users. It now reads that user's open session from clock.timesheet instead of showing the viewer's own shift.
  • aria-busy on .clock-status. Set until open shifts load. E2E uses it to wait for the page.
// Before: whichever shift Mongo returned first
await ClockEvents.findOneAsync({ userId, endTime: null });
// After
await findOpenShift(userId, teamId); // null without a team
await findOpenShifts(userId);        // all of the user's open shifts, one per team at most

Decisions on the issue's open questions

These are the current calls and are up for review:

  • Overlapping hours. Timesheets still count both teams' hours, and manual entries still refuse any cross-team overlap.
  • Personal and Redmine tickets. Their timers attach to the hinted (selected) team's shift, or the only open shift. Otherwise they are refused with shift-ambiguous.
  • Auto clock-out. It stays per shift.

Tests and release note

  • Backend. clock-per-team.test.ts covers:

    • the index;
    • a parallel-start race;
    • the refusal;
    • two teams open at once;
    • timer nesting and the ambiguity rule;
    • stop by session;
    • a mismatched or missing target;
    • recorded hours.

    open-shift-dedupe.test.ts covers the cleanup planner.

  • E2E. realtime/per-team-clock.spec.ts uses two devices on two teams and checks the live "also on the clock" notice and a clock-out that leaves the other team's timer running.

  • Release note. release-notes/1.0.6.md. Its version and date need confirming against the next release.

Copilot AI self-assigned this Oct 5, 2026
Copilot AI balanced review requested due to automatic review settings October 5, 2026 15:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review any files in this pull request. Check if the Files changed in this pull request are included in default exclusions.

… shifts, selected-team UI

Co-authored-by: morepriyam <118034652+morepriyam@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings October 5, 2026 15:21

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Live break synchronization, index enforcement, stale reminder handling, outdated tests, and missing backend coverage remain unresolved.

Review effort: Balanced
Findings: 2 High severity · 3 Medium severity · 1 Low severity

Open (6)

Comment thread meteor-backend/server/clock.js Resolved
Comment on lines +1324 to 1326
Wormhole.expose('clock.myOpenShifts', {
description: "The caller's open shifts, at most one per team",
inputSchema: { type: 'object', properties: {} },

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clock.test.ts and plan-gate.test.ts now call clock.myOpenShifts and assert on the returned array. The e2e Redmine settings mock now routes clock_myOpenShifts too. All of this landed in cfa3b2a.

Comment thread src/features/timers/TodayStatusCard.tsx Resolved
Comment thread src/lib/TeamContext.tsx Resolved
Comment on lines +120 to +126
Meteor.startup(async () => {
for (let attempt = 1; attempt <= 3; attempt++) {
try {
await closeDuplicateOpenShifts();
await ClockEvents.createIndexAsync(
{ userId: 1, teamId: 1 },
{ unique: true, partialFilterExpression: { endTime: null }, name: OPEN_SHIFT_INDEX }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tests/clock-per-team.test.ts covers concurrent same-team starts, the index rejecting a second open shift at the database, shifts open in two teams at once, stopping by clockEventId, and stopping one shift while the other's timer keeps running. The duplicate-cleanup rule is unit-tested in open-shift-dedupe.test.ts. These landed in cfa3b2a, with an extra test for the other-viewer lookup in a91f4eb.

Co-authored-by: morepriyam <118034652+morepriyam@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings October 5, 2026 15:36
…rized open-shift lookup

Co-authored-by: morepriyam <118034652+morepriyam@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Unresolved concurrency, startup-invariant, legacy-timer, and cross-user state issues can leave clocks or timers inconsistent.

Review effort: Balanced
Findings: 2 High severity · 2 Medium severity · 1 Low severity

Open (5)
Resolved since last review (3)
Previously missed (3)

In code that hasn't changed since last review

Medium severity Resume lookup fails for legacy pre-link timer sessions

meteor-backend/​server/​timer-core.js:78

Legacy running sessions are deliberately matched by shiftSessionSelector through a null/missing clockEventId, but this resume lookup now requires an exact shift ID. After deployment, pausing a pre-link timer closes it and resuming the break can no longer find or restart it. Use the same legacy-compatible ID predicate here.

Medium severity Removing team members leaves their open shifts inaccessible

src/​features/​clock/​OtherTeamShifts.tsx:52

A team admin can remove a member without closing that member's open clock event (teams.removeMember only pulls membership). The shift then remains in openShifts, but its team is absent from allTeams, so this condition removes the only Switch control and the user cannot select or clock out that shift. Close shifts on membership removal or provide a direct clock-out action for unresolved teams.

Medium severity User switch briefly displays the previous user's clock data

src/​lib/​TeamContext.tsx:424

The request token prevents an old response from landing, but an in-place sign-in from user A directly to user B leaves A's openShifts visible and clockReady true until B's request resolves. TeamProvider remains mounted across that transition, so the header/settings can briefly render A's clock data for B. Clear or user-key this state immediately when userId changes, while retaining the stale-request guard.

Comment on lines +239 to +242
export async function closeShift(event, now) {
const eventId = hexId(event._id);

// Close any running timer sessions for this user (mirrors clock.stop).
await closeAllForUser(userId, now);
await closeTimersForShift(event.userId, eventId, now);
Comment on lines +106 to +108
cancelClockJobs(shiftId).catch((err) =>
console.error('[agenda] cancelClockJobs for duplicate shift failed:', err)
);
Copilot AI balanced review requested due to automatic review settings October 5, 2026 15:44
…ore Agenda init

Co-authored-by: morepriyam <118034652+morepriyam@users.noreply.github.com>
Copilot AI changed the title [WIP] Make the clock per team end to end: Server, live updates and UI Make the clock per team end to end: server, live updates and UI Oct 5, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Per-team pause/resume can lose legacy timers or create multiple running timers, and open-shift authorization and profile status remain inconsistent.

Review effort: Balanced
Findings: 3 High severity · 2 Medium severity · 1 Low severity

Open (6)
Resolved since last review (1)
Previously missed (3)

In code that hasn't changed since last review

Medium severity Resume excludes legacy sessions paused without a clock event

meteor-backend/​server/​timer-core.js:78

Legacy running sessions are selected and closed on pause via shiftSessionSelector, which explicitly includes clockEventId: null, but this lookup excludes that same legacy session on resume. Pausing a pre-link timer therefore stops it permanently instead of restarting it. Match both the current shift ID and null here as well.

Medium severity Own profile hides open shifts from other teams

src/​features/​timers/​TodayStatusCard.tsx:58

Using TeamContext only for the current user is no longer equivalent to this person-wide lookup: activeClockEvent now contains only the selected team's shift. On the user's own Profile → Work page, selecting an off-clock team hides this card even when another team has an open shift, while viewing another user correctly shows their newest open shift. Use openShifts (or this endpoint) for the own-profile branch too.

Low severity Sentence has a mismatched subject

release-notes/​1.0.6.md:20

This sentence has a mismatched subject: “Clock in or out … catches up.” Separate the action from the device that catches up.

Comment on lines +681 to 683
const closedTimer = await findClosedAtTime(userId, eventId, openBreak.startTime);
if (closedTimer) {
await restartTimerForWorkItem(userId, closedTimer.workItemId, now, eventId);
Comment on lines +154 to +158
const sharedAdminTeam = await Teams.findOneAsync({
admins: requesterId,
$or: [{ members: targetUserId }, { admins: targetUserId }],
});
if (!sharedAdminTeam) throw new Meteor.Error('forbidden', 'Not allowed to view timesheet');
Copilot AI balanced review requested due to automatic review settings October 5, 2026 15:50

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🔵 Needs a closer look

Legacy timer resume, cleanup accounting, reminder lifecycle, accessibility, and release-version issues remain unresolved.

Review effort: Balanced
Findings: 3 High severity · 2 Medium severity · 1 Low severity

Open (6)
Previously missed (5)

In code that hasn't changed since last review

Medium severity Completed breaks after cutoff are over-deducted during migration

meteor-backend/​server/​clock-core.js:262

The duplicate-shift cleanup calls closeShift with a historical now, but completed breaks can extend past that cutoff. computeDeductedBreakSeconds uses a completed break's stored end unchanged, so time after the newly assigned shift end is deducted and the migrated accumulatedTime is too low. Normalize the breaks to the retained shift interval before calculating the deduction.

Medium severity Legacy paused sessions are not resumed for the current shift

meteor-backend/​server/​timer-core.js:78

Legacy running sessions are deliberately selected and stopped by closeRunningForShift when clockEventId is null, but this lookup can only find sessions already tagged with the current shift. Resuming from a break therefore never restarts a legacy timer that this same shift just paused. Include null in the clock-event selector here, matching shiftSessionSelector.

Medium severity Pending reminder remains actionable after its shift closes

src/​features/​notifications/​ShiftReminderContext.tsx:115

When a displayed reminder's shift closes, this effect reruns and returns here, but it never clears the existing pendingNotif. The modal therefore remains actionable after a manual or automatic clock-out and can submit a response for a closed shift. Clear the pending reminder when its clockEventId is no longer present in the open-shift set.

Low severity Package version does not match the 1.0.6 release note

release-notes/​1.0.6.md:2

The app still declares version 1.0.5 in package.json, while the release-note guide requires this version to match the OTA bundle's package version. As written, this PR adds a 1.0.6 note without making the app a 1.0.6 release. Confirm the target release and either bump the package version or merge this content into the note for the version that will ship.

Low severity First cross-device notice is not announced by the live region

src/​features/​clock/​OtherTeamShifts.tsx:29

This live region does not exist while there are no other shifts, so the first notice is inserted together with a newly mounted aria-live container. Screen readers generally announce mutations to an existing live region, not its initial mounted content, so the cross-device clock-in may remain silent. Keep the empty <ul aria-live="polite"> mounted and only add/remove its list items.

@morepriyam morepriyam closed this Oct 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Make the Clock Per-Team End to End: Server, Live Updates and UI

3 participants