Timer safety: length limit, server-side saving, stop on close

- Maximum timer length setting (default 10h): a timer that runs past it
  is stopped at the limit and its entry's comment is flagged, so a
  forgotten timer can't add a night or weekend of hours
- StopwatchTimerTickJob saves a running timer's time every minute on the
  server (no browser needed) and stops it at the limit on time; open
  tabs keep saving too
- Timer updates lock the user's preference row and re-read the timer, so
  simultaneous saves (several tabs, the job) never add time twice
- Closing an issue stops timers running on it before anything else (e.g.
  billing) uses its time; deleting a time entry only stops the timer
  running on that entry
- Issue timers require a visible issue; starting again moves the timer
  instead of raising "timer is already running"
- Tests updated and extended (limit, locking, tick job, close, delete,
  visibility, issue context menu); CI runs on Redmine 7.0
- Upstream's German notes translated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
This commit is contained in:
Claude committed 2026-10-29 00:13:21 -04:00
1 parent c3d6948735
commit 626db60658
15 files changed
+366 -36

No files matched your search

+10
View File
@@ -4,6 +4,7 @@ module Stopwatch
def self.setup
Stopwatch::IssuesControllerPatch.apply
::TimeEntry.prepend Stopwatch::TimeEntryPatch
::Issue.prepend Stopwatch::IssuePatch
::User.prepend Stopwatch::UserPatch
Stopwatch::Hooks # just load it
end
@@ -41,6 +42,15 @@ module Stopwatch
end
end
# Longest a timer may run before it is stopped automatically (hours), or nil for no limit.
# Protects against a forgotten timer adding a night or weekend to a time entry.
def self.max_timer_hours
value = settings['max_timer_hours']
return 10.0 if value.nil? # setting never saved: use the default
hours = value.to_s.strip.tr(',', '.').to_f
hours.positive? ? hours : nil
end
# Colour-code the issue Start/Stop links (green to start, red to stop)
def self.highlighted_links
settings['highlighted_links'].to_s == '1'
+26
View File
@@ -0,0 +1,26 @@
module Stopwatch
# When an issue is closed, stop any timer still running on it, so the time logged on the issue is
# final before anything uses it (e.g. billing that runs when an issue closes). Otherwise the timer
# would keep adding hours to an entry that was already billed.
module IssuePatch
extend ActiveSupport::Concern
prepended do
after_save :stop_timers_on_close, if: -> { saved_change_to_status_id? && closed? }
end
def stop_timers_on_close
user_ids = time_entries.distinct.pluck(:user_id)
User.where(id: user_ids).find_each do |user|
timer = Stopwatch::Timer.new(user)
next unless timer.running? && timer.time_entry&.issue_id == id
timer.stop
Rails.logger.info "[Stopwatch] Stopped user ##{user.id}'s timer because issue ##{id} was closed"
end
rescue StandardError => e
# Never block closing the issue
Rails.logger.error "[Stopwatch] Could not stop timers for issue ##{id}: #{e.class}: #{e.message}"
end
end
end
+2 -1
View File
@@ -6,9 +6,10 @@ module Stopwatch
before_destroy :stop_timer
end
# Stop the user's timer only if it is running on this entry (deleting another entry used to stop it)
def stop_timer
t = Stopwatch::Timer.new(user)
t.update(stop: true) if t.running?
t.update(stop: true) if t.running? && t.time_entry_id == id
end
end
end
+88 -14
View File
@@ -1,8 +1,13 @@
require 'json'
require 'securerandom'
module Stopwatch
# A user's running timer. Stored as JSON in the user's preferences:
# started_at - when time was last saved into the time entry (nil when stopped)
# time_entry_id - the time entry the timer adds to
# session_hours - hours already added since the timer was started, for the maximum timer length
# tick_token - identifies this start's chain of server-side saves (StopwatchTimerTickJob)
class Timer
class HourFormatter
include ApplicationHelper
@@ -19,7 +24,6 @@ module Stopwatch
end
end
attr_reader :user
def initialize(user)
@@ -30,29 +34,52 @@ module Stopwatch
data[:started_at].present?
end
# Starts the timer on time_entry. If a timer is already running (e.g. after a double click), its
# time is saved and the timer moves to the new entry, instead of failing.
def start(time_entry = nil)
fail "timer is already running" if running?
data[:started_at] = Time.now.to_i
data[:time_entry_id] = time_entry.id if time_entry
save
token = SecureRandom.hex(8)
locked do
apply_elapsed_time(stop: true) if running?
data[:started_at] = Time.now.to_i
data[:session_hours] = 0.0
data[:time_entry_id] = time_entry&.id
data[:tick_token] = token
save
end
# Keep saving the time on the server every minute while it runs
StopwatchTimerTickJob.schedule(user.id, token)
end
def stop
update stop: true
end
# saves currently logged time to the time entry and resets the started_at
# timestamp to either nil (stop: true) or current time.
# Saves the time elapsed since the last save into the time entry, then stops the timer
# (stop: true) or keeps it running from now. The timer record is locked meanwhile, so two requests
# at the same moment (e.g. two open tabs) can't add the same time twice. Once a timer reaches the
# maximum timer length it is stopped at the limit and the entry's comment says so.
def update(stop: false)
if hours = runtime_hours and entry = self.time_entry
time_entry.update_column :hours, entry.read_attribute(:hours) + hours
locked do
if running?
apply_elapsed_time(stop: stop)
save
end
end
data[:started_at] = stop || !running? ? nil : Time.now.to_i
save
end
def tick_token
data[:tick_token]
end
# True when the running timer has reached the maximum timer length and should be stopped
def over_limit?
max = Stopwatch.max_timer_hours
running? && max.present? && data[:session_hours].to_f + (runtime_hours || 0) >= max
end
# Hours to display: what's saved on the entry plus the running time (never beyond the limit)
def time_spent
h = runtime_hours || 0
h = unsaved_hours
if e = time_entry
h += e.hours
end
@@ -89,12 +116,59 @@ module Stopwatch
@data ||= (t = user.pref[:current_timer]) ? JSON.parse(t).symbolize_keys : {}
end
# Runs the block with the user's preference row locked, after re-reading the saved timer
def locked
pref = user.pref
pref.save! if pref.new_record?
pref.with_lock do
@data = nil
yield
end
end
# Running time not yet saved into the entry, limited by the maximum timer length
def unsaved_hours
hours = runtime_hours || 0
max = Stopwatch.max_timer_hours
max ? [hours, [max - data[:session_hours].to_f, 0].max].min : hours
end
def apply_elapsed_time(stop:)
hours = unsaved_hours
capped = over_limit?
entry = time_entry
if entry && (hours.positive? || capped)
attributes = {}
attributes[:hours] = entry.read_attribute(:hours).to_f + hours if hours.positive?
attributes[:comments] = capped_comment(entry) if capped
entry.update_columns(attributes) if attributes.any?
end
if stop || capped
Rails.logger.info "[Stopwatch] Timer for user ##{user.id} stopped at the #{Stopwatch.max_timer_hours}h limit" if capped
data[:started_at] = nil
data[:session_hours] = 0.0
else
data[:started_at] = Time.now.to_i
data[:session_hours] = data[:session_hours].to_f + hours
end
end
# Notes on the entry that the timer hit the limit, so someone can correct the hours
def capped_comment(entry)
note = I18n.t(:text_stopwatch_timer_capped, hours: Stopwatch.max_timer_hours.to_s.sub(/\.0\z/, ''))
comments = entry.comments.to_s
return comments if comments.include?(note)
[comments.presence, note].compact.join(' ').truncate(1024)
end
def runtime_hours
if start = data[:started_at]
runtime = Time.now.to_i - start
return runtime.to_f / 1.hour
end
end
end
end